babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets an array of textures on the engine to be used in the shader.
  861. * @param channel Name of the variable.
  862. * @param textures Textures to set.
  863. */
  864. Effect.prototype.setTextureArray = function (channel, textures) {
  865. if (this._samplers.indexOf(channel + "Ex") === -1) {
  866. var initialPos = this._samplers.indexOf(channel);
  867. for (var index = 1; index < textures.length; index++) {
  868. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  869. }
  870. }
  871. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  872. };
  873. /**
  874. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  875. * @param channel Name of the sampler variable.
  876. * @param postProcess Post process to get the input texture from.
  877. */
  878. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  879. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  880. };
  881. /** @ignore */
  882. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  883. var cache = this._valueCache[uniformName];
  884. var flag = matrix.updateFlag;
  885. if (cache !== undefined && cache === flag) {
  886. return false;
  887. }
  888. this._valueCache[uniformName] = flag;
  889. return true;
  890. };
  891. /** @ignore */
  892. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  893. var cache = this._valueCache[uniformName];
  894. if (!cache) {
  895. cache = [x, y];
  896. this._valueCache[uniformName] = cache;
  897. return true;
  898. }
  899. var changed = false;
  900. if (cache[0] !== x) {
  901. cache[0] = x;
  902. changed = true;
  903. }
  904. if (cache[1] !== y) {
  905. cache[1] = y;
  906. changed = true;
  907. }
  908. return changed;
  909. };
  910. /** @ignore */
  911. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  912. var cache = this._valueCache[uniformName];
  913. if (!cache) {
  914. cache = [x, y, z];
  915. this._valueCache[uniformName] = cache;
  916. return true;
  917. }
  918. var changed = false;
  919. if (cache[0] !== x) {
  920. cache[0] = x;
  921. changed = true;
  922. }
  923. if (cache[1] !== y) {
  924. cache[1] = y;
  925. changed = true;
  926. }
  927. if (cache[2] !== z) {
  928. cache[2] = z;
  929. changed = true;
  930. }
  931. return changed;
  932. };
  933. /** @ignore */
  934. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  935. var cache = this._valueCache[uniformName];
  936. if (!cache) {
  937. cache = [x, y, z, w];
  938. this._valueCache[uniformName] = cache;
  939. return true;
  940. }
  941. var changed = false;
  942. if (cache[0] !== x) {
  943. cache[0] = x;
  944. changed = true;
  945. }
  946. if (cache[1] !== y) {
  947. cache[1] = y;
  948. changed = true;
  949. }
  950. if (cache[2] !== z) {
  951. cache[2] = z;
  952. changed = true;
  953. }
  954. if (cache[3] !== w) {
  955. cache[3] = w;
  956. changed = true;
  957. }
  958. return changed;
  959. };
  960. /**
  961. * Binds a buffer to a uniform.
  962. * @param buffer Buffer to bind.
  963. * @param name Name of the uniform variable to bind to.
  964. */
  965. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  966. var bufferName = this._uniformBuffersNames[name];
  967. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  968. return;
  969. }
  970. Effect._baseCache[bufferName] = buffer;
  971. this._engine.bindUniformBufferBase(buffer, bufferName);
  972. };
  973. /**
  974. * Binds block to a uniform.
  975. * @param blockName Name of the block to bind.
  976. * @param index Index to bind.
  977. */
  978. Effect.prototype.bindUniformBlock = function (blockName, index) {
  979. this._engine.bindUniformBlock(this._program, blockName, index);
  980. };
  981. /**
  982. * Sets an interger value on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param value Value to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setInt = function (uniformName, value) {
  988. var cache = this._valueCache[uniformName];
  989. if (cache !== undefined && cache === value)
  990. return this;
  991. this._valueCache[uniformName] = value;
  992. this._engine.setInt(this.getUniform(uniformName), value);
  993. return this;
  994. };
  995. /**
  996. * Sets an int array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setIntArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setIntArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets an float array on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param array array to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setFloatArray = function (uniformName, array) {
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1052. * @param uniformName Name of the variable.
  1053. * @param array array to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1063. * @param uniformName Name of the variable.
  1064. * @param array array to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1074. * @param uniformName Name of the variable.
  1075. * @param array array to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1079. this._valueCache[uniformName] = null;
  1080. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1081. return this;
  1082. };
  1083. /**
  1084. * Sets an array on a uniform variable.
  1085. * @param uniformName Name of the variable.
  1086. * @param array array to be set.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setArray = function (uniformName, array) {
  1090. this._valueCache[uniformName] = null;
  1091. this._engine.setArray(this.getUniform(uniformName), array);
  1092. return this;
  1093. };
  1094. /**
  1095. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1096. * @param uniformName Name of the variable.
  1097. * @param array array to be set.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setArray2 = function (uniformName, array) {
  1101. this._valueCache[uniformName] = null;
  1102. this._engine.setArray2(this.getUniform(uniformName), array);
  1103. return this;
  1104. };
  1105. /**
  1106. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1107. * @param uniformName Name of the variable.
  1108. * @param array array to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setArray3 = function (uniformName, array) {
  1112. this._valueCache[uniformName] = null;
  1113. this._engine.setArray3(this.getUniform(uniformName), array);
  1114. return this;
  1115. };
  1116. /**
  1117. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1118. * @param uniformName Name of the variable.
  1119. * @param array array to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setArray4 = function (uniformName, array) {
  1123. this._valueCache[uniformName] = null;
  1124. this._engine.setArray4(this.getUniform(uniformName), array);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets matrices on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param matrices matrices to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1134. if (!matrices) {
  1135. return this;
  1136. }
  1137. this._valueCache[uniformName] = null;
  1138. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets matrix on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param matrix matrix to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1148. if (this._cacheMatrix(uniformName, matrix)) {
  1149. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1155. * @param uniformName Name of the variable.
  1156. * @param matrix matrix to be set.
  1157. * @returns this effect.
  1158. */
  1159. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1160. this._valueCache[uniformName] = null;
  1161. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1166. * @param uniformName Name of the variable.
  1167. * @param matrix matrix to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1171. this._valueCache[uniformName] = null;
  1172. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param value value to be set.
  1179. * @returns this effect.
  1180. */
  1181. Effect.prototype.setFloat = function (uniformName, value) {
  1182. var cache = this._valueCache[uniformName];
  1183. if (cache !== undefined && cache === value)
  1184. return this;
  1185. this._valueCache[uniformName] = value;
  1186. this._engine.setFloat(this.getUniform(uniformName), value);
  1187. return this;
  1188. };
  1189. /**
  1190. * Sets a boolean on a uniform variable.
  1191. * @param uniformName Name of the variable.
  1192. * @param bool value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setBool = function (uniformName, bool) {
  1196. var cache = this._valueCache[uniformName];
  1197. if (cache !== undefined && cache === bool)
  1198. return this;
  1199. this._valueCache[uniformName] = bool;
  1200. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Vector2 on a uniform variable.
  1205. * @param uniformName Name of the variable.
  1206. * @param vector2 vector2 to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1210. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1211. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a float2 on a uniform variable.
  1217. * @param uniformName Name of the variable.
  1218. * @param x First float in float2.
  1219. * @param y Second float in float2.
  1220. * @returns this effect.
  1221. */
  1222. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1223. if (this._cacheFloat2(uniformName, x, y)) {
  1224. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1225. }
  1226. return this;
  1227. };
  1228. /**
  1229. * Sets a Vector3 on a uniform variable.
  1230. * @param uniformName Name of the variable.
  1231. * @param vector3 Value to be set.
  1232. * @returns this effect.
  1233. */
  1234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1235. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1236. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1237. }
  1238. return this;
  1239. };
  1240. /**
  1241. * Sets a float3 on a uniform variable.
  1242. * @param uniformName Name of the variable.
  1243. * @param x First float in float3.
  1244. * @param y Second float in float3.
  1245. * @param z Third float in float3.
  1246. * @returns this effect.
  1247. */
  1248. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1249. if (this._cacheFloat3(uniformName, x, y, z)) {
  1250. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1251. }
  1252. return this;
  1253. };
  1254. /**
  1255. * Sets a Vector4 on a uniform variable.
  1256. * @param uniformName Name of the variable.
  1257. * @param vector4 Value to be set.
  1258. * @returns this effect.
  1259. */
  1260. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1261. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1262. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1263. }
  1264. return this;
  1265. };
  1266. /**
  1267. * Sets a float4 on a uniform variable.
  1268. * @param uniformName Name of the variable.
  1269. * @param x First float in float4.
  1270. * @param y Second float in float4.
  1271. * @param z Third float in float4.
  1272. * @param w Fourth float in float4.
  1273. * @returns this effect.
  1274. */
  1275. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1276. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1277. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1278. }
  1279. return this;
  1280. };
  1281. /**
  1282. * Sets a Color3 on a uniform variable.
  1283. * @param uniformName Name of the variable.
  1284. * @param color3 Value to be set.
  1285. * @returns this effect.
  1286. */
  1287. Effect.prototype.setColor3 = function (uniformName, color3) {
  1288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1289. this._engine.setColor3(this.getUniform(uniformName), color3);
  1290. }
  1291. return this;
  1292. };
  1293. /**
  1294. * Sets a Color4 on a uniform variable.
  1295. * @param uniformName Name of the variable.
  1296. * @param color3 Value to be set.
  1297. * @param alpha Alpha value to be set.
  1298. * @returns this effect.
  1299. */
  1300. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1301. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1302. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1303. }
  1304. return this;
  1305. };
  1306. /**
  1307. * Sets a Color4 on a uniform variable
  1308. * @param uniformName defines the name of the variable
  1309. * @param color4 defines the value to be set
  1310. * @returns this effect.
  1311. */
  1312. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1313. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1314. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1315. }
  1316. return this;
  1317. };
  1318. /**
  1319. * Resets the cache of effects.
  1320. */
  1321. Effect.ResetCache = function () {
  1322. Effect._baseCache = {};
  1323. };
  1324. Effect._uniqueIdSeed = 0;
  1325. Effect._baseCache = {};
  1326. Effect._sourceCache = {};
  1327. // Statics
  1328. /**
  1329. * Store of each shader (The can be looked up using effect.key)
  1330. */
  1331. Effect.ShadersStore = {};
  1332. /**
  1333. * Store of each included file for a shader (The can be looked up using effect.key)
  1334. */
  1335. Effect.IncludesShadersStore = {};
  1336. return Effect;
  1337. }());
  1338. BABYLON.Effect = Effect;
  1339. })(BABYLON || (BABYLON = {}));
  1340. //# sourceMappingURL=babylon.effect.js.map
  1341. //# sourceMappingURL=babylon.types.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. var KeyboardEventTypes = /** @class */ (function () {
  1345. function KeyboardEventTypes() {
  1346. }
  1347. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1348. get: function () {
  1349. return KeyboardEventTypes._KEYDOWN;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1355. get: function () {
  1356. return KeyboardEventTypes._KEYUP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. KeyboardEventTypes._KEYDOWN = 0x01;
  1362. KeyboardEventTypes._KEYUP = 0x02;
  1363. return KeyboardEventTypes;
  1364. }());
  1365. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1366. var KeyboardInfo = /** @class */ (function () {
  1367. function KeyboardInfo(type, event) {
  1368. this.type = type;
  1369. this.event = event;
  1370. }
  1371. return KeyboardInfo;
  1372. }());
  1373. BABYLON.KeyboardInfo = KeyboardInfo;
  1374. /**
  1375. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1376. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1377. */
  1378. var KeyboardInfoPre = /** @class */ (function (_super) {
  1379. __extends(KeyboardInfoPre, _super);
  1380. function KeyboardInfoPre(type, event) {
  1381. var _this = _super.call(this, type, event) || this;
  1382. _this.skipOnPointerObservable = false;
  1383. return _this;
  1384. }
  1385. return KeyboardInfoPre;
  1386. }(KeyboardInfo));
  1387. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1388. })(BABYLON || (BABYLON = {}));
  1389. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1390. var BABYLON;
  1391. (function (BABYLON) {
  1392. var PointerEventTypes = /** @class */ (function () {
  1393. function PointerEventTypes() {
  1394. }
  1395. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1396. get: function () {
  1397. return PointerEventTypes._POINTERDOWN;
  1398. },
  1399. enumerable: true,
  1400. configurable: true
  1401. });
  1402. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1403. get: function () {
  1404. return PointerEventTypes._POINTERUP;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1410. get: function () {
  1411. return PointerEventTypes._POINTERMOVE;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERWHEEL;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERPICK;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERTAP;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERDOUBLETAP;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. PointerEventTypes._POINTERDOWN = 0x01;
  1445. PointerEventTypes._POINTERUP = 0x02;
  1446. PointerEventTypes._POINTERMOVE = 0x04;
  1447. PointerEventTypes._POINTERWHEEL = 0x08;
  1448. PointerEventTypes._POINTERPICK = 0x10;
  1449. PointerEventTypes._POINTERTAP = 0x20;
  1450. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1451. return PointerEventTypes;
  1452. }());
  1453. BABYLON.PointerEventTypes = PointerEventTypes;
  1454. var PointerInfoBase = /** @class */ (function () {
  1455. function PointerInfoBase(type, event) {
  1456. this.type = type;
  1457. this.event = event;
  1458. }
  1459. return PointerInfoBase;
  1460. }());
  1461. BABYLON.PointerInfoBase = PointerInfoBase;
  1462. /**
  1463. * This class is used to store pointer related info for the onPrePointerObservable event.
  1464. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1465. */
  1466. var PointerInfoPre = /** @class */ (function (_super) {
  1467. __extends(PointerInfoPre, _super);
  1468. function PointerInfoPre(type, event, localX, localY) {
  1469. var _this = _super.call(this, type, event) || this;
  1470. _this.skipOnPointerObservable = false;
  1471. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1472. return _this;
  1473. }
  1474. return PointerInfoPre;
  1475. }(PointerInfoBase));
  1476. BABYLON.PointerInfoPre = PointerInfoPre;
  1477. /**
  1478. * This type contains all the data related to a pointer event in Babylon.js.
  1479. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1480. */
  1481. var PointerInfo = /** @class */ (function (_super) {
  1482. __extends(PointerInfo, _super);
  1483. function PointerInfo(type, event, pickInfo) {
  1484. var _this = _super.call(this, type, event) || this;
  1485. _this.pickInfo = pickInfo;
  1486. return _this;
  1487. }
  1488. return PointerInfo;
  1489. }(PointerInfoBase));
  1490. BABYLON.PointerInfo = PointerInfo;
  1491. })(BABYLON || (BABYLON = {}));
  1492. //# sourceMappingURL=babylon.pointerEvents.js.map
  1493. var BABYLON;
  1494. (function (BABYLON) {
  1495. BABYLON.ToGammaSpace = 1 / 2.2;
  1496. BABYLON.ToLinearSpace = 2.2;
  1497. BABYLON.Epsilon = 0.001;
  1498. /**
  1499. * Class used to hold a RBG color
  1500. */
  1501. var Color3 = /** @class */ (function () {
  1502. /**
  1503. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1504. * @param r defines the red component (between 0 and 1, default is 0)
  1505. * @param g defines the green component (between 0 and 1, default is 0)
  1506. * @param b defines the blue component (between 0 and 1, default is 0)
  1507. */
  1508. function Color3(
  1509. /**
  1510. * Defines the red component (between 0 and 1, default is 0)
  1511. */
  1512. r,
  1513. /**
  1514. * Defines the green component (between 0 and 1, default is 0)
  1515. */
  1516. g,
  1517. /**
  1518. * Defines the blue component (between 0 and 1, default is 0)
  1519. */
  1520. b) {
  1521. if (r === void 0) { r = 0; }
  1522. if (g === void 0) { g = 0; }
  1523. if (b === void 0) { b = 0; }
  1524. this.r = r;
  1525. this.g = g;
  1526. this.b = b;
  1527. }
  1528. /**
  1529. * Creates a string with the Color3 current values
  1530. * @returns the string representation of the Color3 object
  1531. */
  1532. Color3.prototype.toString = function () {
  1533. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1534. };
  1535. /**
  1536. * Returns the string "Color3"
  1537. * @returns "Color3"
  1538. */
  1539. Color3.prototype.getClassName = function () {
  1540. return "Color3";
  1541. };
  1542. /**
  1543. * Compute the Color3 hash code
  1544. * @returns an unique number that can be used to hash Color3 objects
  1545. */
  1546. Color3.prototype.getHashCode = function () {
  1547. var hash = this.r || 0;
  1548. hash = (hash * 397) ^ (this.g || 0);
  1549. hash = (hash * 397) ^ (this.b || 0);
  1550. return hash;
  1551. };
  1552. // Operators
  1553. /**
  1554. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1555. * @param array defines the array where to store the r,g,b components
  1556. * @param index defines an optional index in the target array to define where to start storing values
  1557. * @returns the current Color3 object
  1558. */
  1559. Color3.prototype.toArray = function (array, index) {
  1560. if (index === undefined) {
  1561. index = 0;
  1562. }
  1563. array[index] = this.r;
  1564. array[index + 1] = this.g;
  1565. array[index + 2] = this.b;
  1566. return this;
  1567. };
  1568. /**
  1569. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1570. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1571. * @returns a new {BABYLON.Color4} object
  1572. */
  1573. Color3.prototype.toColor4 = function (alpha) {
  1574. if (alpha === void 0) { alpha = 1; }
  1575. return new Color4(this.r, this.g, this.b, alpha);
  1576. };
  1577. /**
  1578. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1579. * @returns the new array
  1580. */
  1581. Color3.prototype.asArray = function () {
  1582. var result = new Array();
  1583. this.toArray(result, 0);
  1584. return result;
  1585. };
  1586. /**
  1587. * Returns the luminance value
  1588. * @returns a float value
  1589. */
  1590. Color3.prototype.toLuminance = function () {
  1591. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1592. };
  1593. /**
  1594. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3 object
  1597. */
  1598. Color3.prototype.multiply = function (otherColor) {
  1599. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1600. };
  1601. /**
  1602. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines the Color3 object where to store the result
  1605. * @returns the current Color3
  1606. */
  1607. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1608. result.r = this.r * otherColor.r;
  1609. result.g = this.g * otherColor.g;
  1610. result.b = this.b * otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Determines equality between Color3 objects
  1615. * @param otherColor defines the second operand
  1616. * @returns true if the rgb values are equal to the passed ones
  1617. */
  1618. Color3.prototype.equals = function (otherColor) {
  1619. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1620. };
  1621. /**
  1622. * Determines equality between the current Color3 object and a set of r,b,g values
  1623. * @param r defines the red component to check
  1624. * @param g defines the green component to check
  1625. * @param b defines the blue component to check
  1626. * @returns true if the rgb values are equal to the passed ones
  1627. */
  1628. Color3.prototype.equalsFloats = function (r, g, b) {
  1629. return this.r === r && this.g === g && this.b === b;
  1630. };
  1631. /**
  1632. * Multiplies in place each rgb value by scale
  1633. * @param scale defines the scaling factor
  1634. * @returns the updated Color3.
  1635. */
  1636. Color3.prototype.scale = function (scale) {
  1637. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1638. };
  1639. /**
  1640. * Multiplies the rgb values by scale and stores the result into "result"
  1641. * @param scale defines the scaling factor
  1642. * @param result defines the Color3 object where to store the result
  1643. * @returns the unmodified current Color3.
  1644. */
  1645. Color3.prototype.scaleToRef = function (scale, result) {
  1646. result.r = this.r * scale;
  1647. result.g = this.g * scale;
  1648. result.b = this.b * scale;
  1649. return this;
  1650. };
  1651. /**
  1652. * Clamps the rgb values by the min and max values and stores the result into "result"
  1653. * @param min defines minimum clamping value (default is 0)
  1654. * @param max defines maximum clamping value (default is 1)
  1655. * @param result defines color to store the result into
  1656. * @returns the original Color3
  1657. */
  1658. Color3.prototype.clampToRef = function (min, max, result) {
  1659. if (min === void 0) { min = 0; }
  1660. if (max === void 0) { max = 1; }
  1661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1664. return this;
  1665. };
  1666. /**
  1667. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1668. * @param otherColor defines the second operand
  1669. * @returns the new Color3
  1670. */
  1671. Color3.prototype.add = function (otherColor) {
  1672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1673. };
  1674. /**
  1675. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1676. * @param otherColor defines the second operand
  1677. * @param result defines Color3 object to store the result into
  1678. * @returns the unmodified current Color3
  1679. */
  1680. Color3.prototype.addToRef = function (otherColor, result) {
  1681. result.r = this.r + otherColor.r;
  1682. result.g = this.g + otherColor.g;
  1683. result.b = this.b + otherColor.b;
  1684. return this;
  1685. };
  1686. /**
  1687. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1688. * @param otherColor defines the second operand
  1689. * @returns the new Color3
  1690. */
  1691. Color3.prototype.subtract = function (otherColor) {
  1692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1693. };
  1694. /**
  1695. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1696. * @param otherColor defines the second operand
  1697. * @param result defines Color3 object to store the result into
  1698. * @returns the unmodified current Color3
  1699. */
  1700. Color3.prototype.subtractToRef = function (otherColor, result) {
  1701. result.r = this.r - otherColor.r;
  1702. result.g = this.g - otherColor.g;
  1703. result.b = this.b - otherColor.b;
  1704. return this;
  1705. };
  1706. /**
  1707. * Copy the current object
  1708. * @returns a new Color3 copied the current one
  1709. */
  1710. Color3.prototype.clone = function () {
  1711. return new Color3(this.r, this.g, this.b);
  1712. };
  1713. /**
  1714. * Copies the rgb values from the source in the current Color3
  1715. * @param source defines the source Color3 object
  1716. * @returns the updated Color3 object
  1717. */
  1718. Color3.prototype.copyFrom = function (source) {
  1719. this.r = source.r;
  1720. this.g = source.g;
  1721. this.b = source.b;
  1722. return this;
  1723. };
  1724. /**
  1725. * Updates the Color3 rgb values from the passed floats
  1726. * @param r defines the red component to read from
  1727. * @param g defines the green component to read from
  1728. * @param b defines the blue component to read from
  1729. * @returns the current Color3 object
  1730. */
  1731. Color3.prototype.copyFromFloats = function (r, g, b) {
  1732. this.r = r;
  1733. this.g = g;
  1734. this.b = b;
  1735. return this;
  1736. };
  1737. /**
  1738. * Updates the Color3 rgb values from the passed floats
  1739. * @param r defines the red component to read from
  1740. * @param g defines the green component to read from
  1741. * @param b defines the blue component to read from
  1742. * @returns the current Color3 object
  1743. */
  1744. Color3.prototype.set = function (r, g, b) {
  1745. return this.copyFromFloats(r, g, b);
  1746. };
  1747. /**
  1748. * Compute the Color3 hexadecimal code as a string
  1749. * @returns a string containing the hexadecimal representation of the Color3 object
  1750. */
  1751. Color3.prototype.toHexString = function () {
  1752. var intR = (this.r * 255) | 0;
  1753. var intG = (this.g * 255) | 0;
  1754. var intB = (this.b * 255) | 0;
  1755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1756. };
  1757. /**
  1758. * Computes a new Color3 converted from the current one to linear space
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.prototype.toLinearSpace = function () {
  1762. var convertedColor = new Color3();
  1763. this.toLinearSpaceToRef(convertedColor);
  1764. return convertedColor;
  1765. };
  1766. /**
  1767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1768. * @param convertedColor defines the Color3 object where to store the linear space version
  1769. * @returns the unmodified Color3
  1770. */
  1771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1775. return this;
  1776. };
  1777. /**
  1778. * Computes a new Color3 converted from the current one to gamma space
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.prototype.toGammaSpace = function () {
  1782. var convertedColor = new Color3();
  1783. this.toGammaSpaceToRef(convertedColor);
  1784. return convertedColor;
  1785. };
  1786. /**
  1787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1788. * @param convertedColor defines the Color3 object where to store the gamma space version
  1789. * @returns the unmodified Color3
  1790. */
  1791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1795. return this;
  1796. };
  1797. // Statics
  1798. /**
  1799. * Creates a new Color3 from the string containing valid hexadecimal values
  1800. * @param hex defines a string containing valid hexadecimal values
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.FromHexString = function (hex) {
  1804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1805. return new Color3(0, 0, 0);
  1806. }
  1807. var r = parseInt(hex.substring(1, 3), 16);
  1808. var g = parseInt(hex.substring(3, 5), 16);
  1809. var b = parseInt(hex.substring(5, 7), 16);
  1810. return Color3.FromInts(r, g, b);
  1811. };
  1812. /**
  1813. * Creates a new Vector3 from the starting index of the passed array
  1814. * @param array defines the source array
  1815. * @param offset defines an offset in the source array
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromArray = function (array, offset) {
  1819. if (offset === void 0) { offset = 0; }
  1820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1821. };
  1822. /**
  1823. * Creates a new Color3 from integer values (< 256)
  1824. * @param r defines the red component to read from (value between 0 and 255)
  1825. * @param g defines the green component to read from (value between 0 and 255)
  1826. * @param b defines the blue component to read from (value between 0 and 255)
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.FromInts = function (r, g, b) {
  1830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param start defines the start Color3 value
  1835. * @param end defines the end Color3 value
  1836. * @param amount defines the gradient value between start and end
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Lerp = function (start, end, amount) {
  1840. var r = start.r + ((end.r - start.r) * amount);
  1841. var g = start.g + ((end.g - start.g) * amount);
  1842. var b = start.b + ((end.b - start.b) * amount);
  1843. return new Color3(r, g, b);
  1844. };
  1845. /**
  1846. * Returns a Color3 value containing a red color
  1847. * @returns a new Color3 object
  1848. */
  1849. Color3.Red = function () { return new Color3(1, 0, 0); };
  1850. /**
  1851. * Returns a Color3 value containing a green color
  1852. * @returns a new Color3 object
  1853. */
  1854. Color3.Green = function () { return new Color3(0, 1, 0); };
  1855. /**
  1856. * Returns a Color3 value containing a blue color
  1857. * @returns a new Color3 object
  1858. */
  1859. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1860. /**
  1861. * Returns a Color3 value containing a black color
  1862. * @returns a new Color3 object
  1863. */
  1864. Color3.Black = function () { return new Color3(0, 0, 0); };
  1865. /**
  1866. * Returns a Color3 value containing a white color
  1867. * @returns a new Color3 object
  1868. */
  1869. Color3.White = function () { return new Color3(1, 1, 1); };
  1870. /**
  1871. * Returns a Color3 value containing a purple color
  1872. * @returns a new Color3 object
  1873. */
  1874. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1875. /**
  1876. * Returns a Color3 value containing a magenta color
  1877. * @returns a new Color3 object
  1878. */
  1879. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1880. /**
  1881. * Returns a Color3 value containing a yellow color
  1882. * @returns a new Color3 object
  1883. */
  1884. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1885. /**
  1886. * Returns a Color3 value containing a gray color
  1887. * @returns a new Color3 object
  1888. */
  1889. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1890. /**
  1891. * Returns a Color3 value containing a teal color
  1892. * @returns a new Color3 object
  1893. */
  1894. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1895. /**
  1896. * Returns a Color3 value containing a random color
  1897. * @returns a new Color3 object
  1898. */
  1899. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1900. return Color3;
  1901. }());
  1902. BABYLON.Color3 = Color3;
  1903. /**
  1904. * Class used to hold a RBGA color
  1905. */
  1906. var Color4 = /** @class */ (function () {
  1907. /**
  1908. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1909. * @param r defines the red component (between 0 and 1, default is 0)
  1910. * @param g defines the green component (between 0 and 1, default is 0)
  1911. * @param b defines the blue component (between 0 and 1, default is 0)
  1912. * @param a defines the alpha component (between 0 and 1, default is 1)
  1913. */
  1914. function Color4(
  1915. /**
  1916. * Defines the red component (between 0 and 1, default is 0)
  1917. */
  1918. r,
  1919. /**
  1920. * Defines the green component (between 0 and 1, default is 0)
  1921. */
  1922. g,
  1923. /**
  1924. * Defines the blue component (between 0 and 1, default is 0)
  1925. */
  1926. b,
  1927. /**
  1928. * Defines the alpha component (between 0 and 1, default is 1)
  1929. */
  1930. a) {
  1931. if (r === void 0) { r = 0; }
  1932. if (g === void 0) { g = 0; }
  1933. if (b === void 0) { b = 0; }
  1934. if (a === void 0) { a = 1; }
  1935. this.r = r;
  1936. this.g = g;
  1937. this.b = b;
  1938. this.a = a;
  1939. }
  1940. // Operators
  1941. /**
  1942. * Adds in place the passed Color4 values to the current Color4 object
  1943. * @param right defines the second operand
  1944. * @returns the current updated Color4 object
  1945. */
  1946. Color4.prototype.addInPlace = function (right) {
  1947. this.r += right.r;
  1948. this.g += right.g;
  1949. this.b += right.b;
  1950. this.a += right.a;
  1951. return this;
  1952. };
  1953. /**
  1954. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1955. * @returns the new array
  1956. */
  1957. Color4.prototype.asArray = function () {
  1958. var result = new Array();
  1959. this.toArray(result, 0);
  1960. return result;
  1961. };
  1962. /**
  1963. * Stores from the starting index in the passed array the Color4 successive values
  1964. * @param array defines the array where to store the r,g,b components
  1965. * @param index defines an optional index in the target array to define where to start storing values
  1966. * @returns the current Color4 object
  1967. */
  1968. Color4.prototype.toArray = function (array, index) {
  1969. if (index === undefined) {
  1970. index = 0;
  1971. }
  1972. array[index] = this.r;
  1973. array[index + 1] = this.g;
  1974. array[index + 2] = this.b;
  1975. array[index + 3] = this.a;
  1976. return this;
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.add = function (right) {
  1984. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1985. };
  1986. /**
  1987. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1988. * @param right defines the second operand
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.subtract = function (right) {
  1992. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1993. };
  1994. /**
  1995. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1996. * @param right defines the second operand
  1997. * @param result defines the Color4 object where to store the result
  1998. * @returns the current Color4 object
  1999. */
  2000. Color4.prototype.subtractToRef = function (right, result) {
  2001. result.r = this.r - right.r;
  2002. result.g = this.g - right.g;
  2003. result.b = this.b - right.b;
  2004. result.a = this.a - right.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Creates a new Color4 with the current Color4 values multiplied by scale
  2009. * @param scale defines the scaling factor to apply
  2010. * @returns a new Color4 object
  2011. */
  2012. Color4.prototype.scale = function (scale) {
  2013. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2014. };
  2015. /**
  2016. * Multiplies the current Color4 values by scale and stores the result in "result"
  2017. * @param scale defines the scaling factor to apply
  2018. * @param result defines the Color4 object where to store the result
  2019. * @returns the current Color4.
  2020. */
  2021. Color4.prototype.scaleToRef = function (scale, result) {
  2022. result.r = this.r * scale;
  2023. result.g = this.g * scale;
  2024. result.b = this.b * scale;
  2025. result.a = this.a * scale;
  2026. return this;
  2027. };
  2028. /**
  2029. * Clamps the rgb values by the min and max values and stores the result into "result"
  2030. * @param min defines minimum clamping value (default is 0)
  2031. * @param max defines maximum clamping value (default is 1)
  2032. * @param result defines color to store the result into.
  2033. * @returns the cuurent Color4
  2034. */
  2035. Color4.prototype.clampToRef = function (min, max, result) {
  2036. if (min === void 0) { min = 0; }
  2037. if (max === void 0) { max = 1; }
  2038. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2039. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2040. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2041. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2042. return this;
  2043. };
  2044. /**
  2045. * Multipy an Color4 value by another and return a new Color4 object
  2046. * @param color defines the Color4 value to multiply by
  2047. * @returns a new Color4 object
  2048. */
  2049. Color4.prototype.multiply = function (color) {
  2050. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2051. };
  2052. /**
  2053. * Multipy a Color4 value by another and push the result in a reference value
  2054. * @param color defines the Color4 value to multiply by
  2055. * @param result defines the Color4 to fill the result in
  2056. * @returns the result Color4
  2057. */
  2058. Color4.prototype.multiplyToRef = function (color, result) {
  2059. result.r = this.r * color.r;
  2060. result.g = this.g * color.g;
  2061. result.b = this.b * color.b;
  2062. result.a = this.a * color.a;
  2063. return result;
  2064. };
  2065. /**
  2066. * Creates a string with the Color4 current values
  2067. * @returns the string representation of the Color4 object
  2068. */
  2069. Color4.prototype.toString = function () {
  2070. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2071. };
  2072. /**
  2073. * Returns the string "Color4"
  2074. * @returns "Color4"
  2075. */
  2076. Color4.prototype.getClassName = function () {
  2077. return "Color4";
  2078. };
  2079. /**
  2080. * Compute the Color4 hash code
  2081. * @returns an unique number that can be used to hash Color4 objects
  2082. */
  2083. Color4.prototype.getHashCode = function () {
  2084. var hash = this.r || 0;
  2085. hash = (hash * 397) ^ (this.g || 0);
  2086. hash = (hash * 397) ^ (this.b || 0);
  2087. hash = (hash * 397) ^ (this.a || 0);
  2088. return hash;
  2089. };
  2090. /**
  2091. * Creates a new Color4 copied from the current one
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.clone = function () {
  2095. return new Color4(this.r, this.g, this.b, this.a);
  2096. };
  2097. /**
  2098. * Copies the passed Color4 values into the current one
  2099. * @param source defines the source Color4 object
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFrom = function (source) {
  2103. this.r = source.r;
  2104. this.g = source.g;
  2105. this.b = source.b;
  2106. this.a = source.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the passed float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2118. this.r = r;
  2119. this.g = g;
  2120. this.b = b;
  2121. this.a = a;
  2122. return this;
  2123. };
  2124. /**
  2125. * Copies the passed float values into the current one
  2126. * @param r defines the red component to read from
  2127. * @param g defines the green component to read from
  2128. * @param b defines the blue component to read from
  2129. * @param a defines the alpha component to read from
  2130. * @returns the current updated Color4 object
  2131. */
  2132. Color4.prototype.set = function (r, g, b, a) {
  2133. return this.copyFromFloats(r, g, b, a);
  2134. };
  2135. /**
  2136. * Compute the Color4 hexadecimal code as a string
  2137. * @returns a string containing the hexadecimal representation of the Color4 object
  2138. */
  2139. Color4.prototype.toHexString = function () {
  2140. var intR = (this.r * 255) | 0;
  2141. var intG = (this.g * 255) | 0;
  2142. var intB = (this.b * 255) | 0;
  2143. var intA = (this.a * 255) | 0;
  2144. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2145. };
  2146. /**
  2147. * Computes a new Color4 converted from the current one to linear space
  2148. * @returns a new Color4 object
  2149. */
  2150. Color4.prototype.toLinearSpace = function () {
  2151. var convertedColor = new Color4();
  2152. this.toLinearSpaceToRef(convertedColor);
  2153. return convertedColor;
  2154. };
  2155. /**
  2156. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2157. * @param convertedColor defines the Color4 object where to store the linear space version
  2158. * @returns the unmodified Color4
  2159. */
  2160. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2164. convertedColor.a = this.a;
  2165. return this;
  2166. };
  2167. /**
  2168. * Computes a new Color4 converted from the current one to gamma space
  2169. * @returns a new Color4 object
  2170. */
  2171. Color4.prototype.toGammaSpace = function () {
  2172. var convertedColor = new Color4();
  2173. this.toGammaSpaceToRef(convertedColor);
  2174. return convertedColor;
  2175. };
  2176. /**
  2177. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2178. * @param convertedColor defines the Color4 object where to store the gamma space version
  2179. * @returns the unmodified Color4
  2180. */
  2181. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2182. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2183. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2184. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2185. convertedColor.a = this.a;
  2186. return this;
  2187. };
  2188. // Statics
  2189. /**
  2190. * Creates a new Color4 from the string containing valid hexadecimal values
  2191. * @param hex defines a string containing valid hexadecimal values
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromHexString = function (hex) {
  2195. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2196. return new Color4(0.0, 0.0, 0.0, 0.0);
  2197. }
  2198. var r = parseInt(hex.substring(1, 3), 16);
  2199. var g = parseInt(hex.substring(3, 5), 16);
  2200. var b = parseInt(hex.substring(5, 7), 16);
  2201. var a = parseInt(hex.substring(7, 9), 16);
  2202. return Color4.FromInts(r, g, b, a);
  2203. };
  2204. /**
  2205. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2206. * @param left defines the start value
  2207. * @param right defines the end value
  2208. * @param amount defines the gradient factor
  2209. * @returns a new Color4 object
  2210. */
  2211. Color4.Lerp = function (left, right, amount) {
  2212. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2213. Color4.LerpToRef(left, right, amount, result);
  2214. return result;
  2215. };
  2216. /**
  2217. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @param result defines the Color4 object where to store data
  2222. */
  2223. Color4.LerpToRef = function (left, right, amount, result) {
  2224. result.r = left.r + (right.r - left.r) * amount;
  2225. result.g = left.g + (right.g - left.g) * amount;
  2226. result.b = left.b + (right.b - left.b) * amount;
  2227. result.a = left.a + (right.a - left.a) * amount;
  2228. };
  2229. /**
  2230. * Creates a new Color4 from the starting index element of the passed array
  2231. * @param array defines the source array to read from
  2232. * @param offset defines the offset in the source array
  2233. * @returns a new Color4 object
  2234. */
  2235. Color4.FromArray = function (array, offset) {
  2236. if (offset === void 0) { offset = 0; }
  2237. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2238. };
  2239. /**
  2240. * Creates a new Color3 from integer values (< 256)
  2241. * @param r defines the red component to read from (value between 0 and 255)
  2242. * @param g defines the green component to read from (value between 0 and 255)
  2243. * @param b defines the blue component to read from (value between 0 and 255)
  2244. * @param a defines the alpha component to read from (value between 0 and 255)
  2245. * @returns a new Color3 object
  2246. */
  2247. Color4.FromInts = function (r, g, b, a) {
  2248. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2249. };
  2250. /**
  2251. * Check the content of a given array and convert it to an array containing RGBA data
  2252. * If the original array was already containing count * 4 values then it is returned directly
  2253. * @param colors defines the array to check
  2254. * @param count defines the number of RGBA data to expect
  2255. * @returns an array containing count * 4 values (RGBA)
  2256. */
  2257. Color4.CheckColors4 = function (colors, count) {
  2258. // Check if color3 was used
  2259. if (colors.length === count * 3) {
  2260. var colors4 = [];
  2261. for (var index = 0; index < colors.length; index += 3) {
  2262. var newIndex = (index / 3) * 4;
  2263. colors4[newIndex] = colors[index];
  2264. colors4[newIndex + 1] = colors[index + 1];
  2265. colors4[newIndex + 2] = colors[index + 2];
  2266. colors4[newIndex + 3] = 1.0;
  2267. }
  2268. return colors4;
  2269. }
  2270. return colors;
  2271. };
  2272. return Color4;
  2273. }());
  2274. BABYLON.Color4 = Color4;
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the passed x and y coordinates.
  2278. */
  2279. function Vector2(x, y) {
  2280. this.x = x;
  2281. this.y = y;
  2282. }
  2283. /**
  2284. * Returns a string with the Vector2 coordinates.
  2285. */
  2286. Vector2.prototype.toString = function () {
  2287. return "{X: " + this.x + " Y:" + this.y + "}";
  2288. };
  2289. /**
  2290. * Returns the string "Vector2"
  2291. */
  2292. Vector2.prototype.getClassName = function () {
  2293. return "Vector2";
  2294. };
  2295. /**
  2296. * Returns the Vector2 hash code as a number.
  2297. */
  2298. Vector2.prototype.getHashCode = function () {
  2299. var hash = this.x || 0;
  2300. hash = (hash * 397) ^ (this.y || 0);
  2301. return hash;
  2302. };
  2303. // Operators
  2304. /**
  2305. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2306. * Returns the Vector2.
  2307. */
  2308. Vector2.prototype.toArray = function (array, index) {
  2309. if (index === void 0) { index = 0; }
  2310. array[index] = this.x;
  2311. array[index + 1] = this.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Returns a new array with 2 elements : the Vector2 coordinates.
  2316. */
  2317. Vector2.prototype.asArray = function () {
  2318. var result = new Array();
  2319. this.toArray(result, 0);
  2320. return result;
  2321. };
  2322. /**
  2323. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2324. * Returns the updated Vector2.
  2325. */
  2326. Vector2.prototype.copyFrom = function (source) {
  2327. this.x = source.x;
  2328. this.y = source.y;
  2329. return this;
  2330. };
  2331. /**
  2332. * Sets the Vector2 coordinates with the passed floats.
  2333. * Returns the updated Vector2.
  2334. */
  2335. Vector2.prototype.copyFromFloats = function (x, y) {
  2336. this.x = x;
  2337. this.y = y;
  2338. return this;
  2339. };
  2340. /**
  2341. * Sets the Vector2 coordinates with the passed floats.
  2342. * Returns the updated Vector2.
  2343. */
  2344. Vector2.prototype.set = function (x, y) {
  2345. return this.copyFromFloats(x, y);
  2346. };
  2347. /**
  2348. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2349. */
  2350. Vector2.prototype.add = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2355. * Returns the Vector2.
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2364. * Returns the updated Vector2.
  2365. */
  2366. Vector2.prototype.addInPlace = function (otherVector) {
  2367. this.x += otherVector.x;
  2368. this.y += otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2373. */
  2374. Vector2.prototype.addVector3 = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2379. */
  2380. Vector2.prototype.subtract = function (otherVector) {
  2381. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2382. };
  2383. /**
  2384. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2388. result.x = this.x - otherVector.x;
  2389. result.y = this.y - otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2394. * Returns the updated Vector2.
  2395. */
  2396. Vector2.prototype.subtractInPlace = function (otherVector) {
  2397. this.x -= otherVector.x;
  2398. this.y -= otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2406. this.x *= otherVector.x;
  2407. this.y *= otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2412. */
  2413. Vector2.prototype.multiply = function (otherVector) {
  2414. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2415. };
  2416. /**
  2417. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2418. * Returns the Vector2.
  2419. */
  2420. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2421. result.x = this.x * otherVector.x;
  2422. result.y = this.y * otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2427. */
  2428. Vector2.prototype.multiplyByFloats = function (x, y) {
  2429. return new Vector2(this.x * x, this.y * y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2433. */
  2434. Vector2.prototype.divide = function (otherVector) {
  2435. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2436. };
  2437. /**
  2438. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2439. * Returns the Vector2.
  2440. */
  2441. Vector2.prototype.divideToRef = function (otherVector, result) {
  2442. result.x = this.x / otherVector.x;
  2443. result.y = this.y / otherVector.y;
  2444. return this;
  2445. };
  2446. /**
  2447. * Divides the current Vector3 coordinates by the passed ones.
  2448. * Returns the updated Vector3.
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 with current Vector2 negated coordinates.
  2455. */
  2456. Vector2.prototype.negate = function () {
  2457. return new Vector2(-this.x, -this.y);
  2458. };
  2459. /**
  2460. * Multiply the Vector2 coordinates by scale.
  2461. * Returns the updated Vector2.
  2462. */
  2463. Vector2.prototype.scaleInPlace = function (scale) {
  2464. this.x *= scale;
  2465. this.y *= scale;
  2466. return this;
  2467. };
  2468. /**
  2469. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2470. */
  2471. Vector2.prototype.scale = function (scale) {
  2472. return new Vector2(this.x * scale, this.y * scale);
  2473. };
  2474. /**
  2475. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2476. */
  2477. Vector2.prototype.equals = function (otherVector) {
  2478. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2479. };
  2480. /**
  2481. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2482. */
  2483. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2484. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2485. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2486. };
  2487. // Properties
  2488. /**
  2489. * Returns the vector length (float).
  2490. */
  2491. Vector2.prototype.length = function () {
  2492. return Math.sqrt(this.x * this.x + this.y * this.y);
  2493. };
  2494. /**
  2495. * Returns the vector squared length (float);
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector.
  2503. * Returns the updated Vector2.
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 copied from the Vector2.
  2516. */
  2517. Vector2.prototype.clone = function () {
  2518. return new Vector2(this.x, this.y);
  2519. };
  2520. // Statics
  2521. /**
  2522. * Returns a new Vector2(0, 0)
  2523. */
  2524. Vector2.Zero = function () {
  2525. return new Vector2(0, 0);
  2526. };
  2527. /**
  2528. * Returns a new Vector2(1, 1)
  2529. */
  2530. Vector2.One = function () {
  2531. return new Vector2(1, 1);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 set from the passed index element of the passed array.
  2535. */
  2536. Vector2.FromArray = function (array, offset) {
  2537. if (offset === void 0) { offset = 0; }
  2538. return new Vector2(array[offset], array[offset + 1]);
  2539. };
  2540. /**
  2541. * Sets "result" from the passed index element of the passed array.
  2542. */
  2543. Vector2.FromArrayToRef = function (array, offset, result) {
  2544. result.x = array[offset];
  2545. result.y = array[offset + 1];
  2546. };
  2547. /**
  2548. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2549. */
  2550. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2551. var squared = amount * amount;
  2552. var cubed = amount * squared;
  2553. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2554. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2555. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2556. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2557. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2558. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2559. return new Vector2(x, y);
  2560. };
  2561. /**
  2562. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2563. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2564. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2565. */
  2566. Vector2.Clamp = function (value, min, max) {
  2567. var x = value.x;
  2568. x = (x > max.x) ? max.x : x;
  2569. x = (x < min.x) ? min.x : x;
  2570. var y = value.y;
  2571. y = (y > max.y) ? max.y : y;
  2572. y = (y < min.y) ? min.y : y;
  2573. return new Vector2(x, y);
  2574. };
  2575. /**
  2576. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2577. */
  2578. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2579. var squared = amount * amount;
  2580. var cubed = amount * squared;
  2581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2583. var part3 = (cubed - (2.0 * squared)) + amount;
  2584. var part4 = cubed - squared;
  2585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2587. return new Vector2(x, y);
  2588. };
  2589. /**
  2590. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2591. */
  2592. Vector2.Lerp = function (start, end, amount) {
  2593. var x = start.x + ((end.x - start.x) * amount);
  2594. var y = start.y + ((end.y - start.y) * amount);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns the dot product (float) of the vector "left" and the vector "right".
  2599. */
  2600. Vector2.Dot = function (left, right) {
  2601. return left.x * right.x + left.y * right.y;
  2602. };
  2603. /**
  2604. * Returns a new Vector2 equal to the normalized passed vector.
  2605. */
  2606. Vector2.Normalize = function (vector) {
  2607. var newVector = vector.clone();
  2608. newVector.normalize();
  2609. return newVector;
  2610. };
  2611. /**
  2612. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2613. */
  2614. Vector2.Minimize = function (left, right) {
  2615. var x = (left.x < right.x) ? left.x : right.x;
  2616. var y = (left.y < right.y) ? left.y : right.y;
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Maximize = function (left, right) {
  2623. var x = (left.x > right.x) ? left.x : right.x;
  2624. var y = (left.y > right.y) ? left.y : right.y;
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2629. */
  2630. Vector2.Transform = function (vector, transformation) {
  2631. var r = Vector2.Zero();
  2632. Vector2.TransformToRef(vector, transformation, r);
  2633. return r;
  2634. };
  2635. /**
  2636. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2637. */
  2638. Vector2.TransformToRef = function (vector, transformation, result) {
  2639. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2640. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2641. result.x = x;
  2642. result.y = y;
  2643. };
  2644. /**
  2645. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2646. */
  2647. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2648. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2649. var sign = a < 0 ? -1 : 1;
  2650. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2651. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2652. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2653. };
  2654. /**
  2655. * Returns the distance (float) between the vectors "value1" and "value2".
  2656. */
  2657. Vector2.Distance = function (value1, value2) {
  2658. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2659. };
  2660. /**
  2661. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2662. */
  2663. Vector2.DistanceSquared = function (value1, value2) {
  2664. var x = value1.x - value2.x;
  2665. var y = value1.y - value2.y;
  2666. return (x * x) + (y * y);
  2667. };
  2668. /**
  2669. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2670. */
  2671. Vector2.Center = function (value1, value2) {
  2672. var center = value1.add(value2);
  2673. center.scaleInPlace(0.5);
  2674. return center;
  2675. };
  2676. /**
  2677. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2678. */
  2679. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2680. var l2 = Vector2.DistanceSquared(segA, segB);
  2681. if (l2 === 0.0) {
  2682. return Vector2.Distance(p, segA);
  2683. }
  2684. var v = segB.subtract(segA);
  2685. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2686. var proj = segA.add(v.multiplyByFloats(t, t));
  2687. return Vector2.Distance(p, proj);
  2688. };
  2689. return Vector2;
  2690. }());
  2691. BABYLON.Vector2 = Vector2;
  2692. /**
  2693. * Classed used to store (x,y,z) vector representation
  2694. * A Vector3 is the main object used in 3D geometry
  2695. * It can represent etiher the coordinates of a point the space, either a direction
  2696. * Reminder: Babylon.js uses a left handed forward facing system
  2697. */
  2698. var Vector3 = /** @class */ (function () {
  2699. /**
  2700. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2701. * @param x defines the first coordinates (on X axis)
  2702. * @param y defines the second coordinates (on Y axis)
  2703. * @param z defines the third coordinates (on Z axis)
  2704. */
  2705. function Vector3(
  2706. /**
  2707. * Defines the first coordinates (on X axis)
  2708. */
  2709. x,
  2710. /**
  2711. * Defines the second coordinates (on Y axis)
  2712. */
  2713. y,
  2714. /**
  2715. * Defines the third coordinates (on Z axis)
  2716. */
  2717. z) {
  2718. this.x = x;
  2719. this.y = y;
  2720. this.z = z;
  2721. }
  2722. /**
  2723. * Creates a string representation of the Vector3
  2724. * @returns a string with the Vector3 coordinates.
  2725. */
  2726. Vector3.prototype.toString = function () {
  2727. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2728. };
  2729. /**
  2730. * Gets the class name
  2731. * @returns the string "Vector3"
  2732. */
  2733. Vector3.prototype.getClassName = function () {
  2734. return "Vector3";
  2735. };
  2736. /**
  2737. * Creates the Vector3 hash code
  2738. * @returns a number which tends to be unique between Vector3 instances
  2739. */
  2740. Vector3.prototype.getHashCode = function () {
  2741. var hash = this.x || 0;
  2742. hash = (hash * 397) ^ (this.y || 0);
  2743. hash = (hash * 397) ^ (this.z || 0);
  2744. return hash;
  2745. };
  2746. // Operators
  2747. /**
  2748. * Creates an array containing three elements : the coordinates of the Vector3
  2749. * @returns a new array of numbers
  2750. */
  2751. Vector3.prototype.asArray = function () {
  2752. var result = [];
  2753. this.toArray(result, 0);
  2754. return result;
  2755. };
  2756. /**
  2757. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2758. * @param array defines the destination array
  2759. * @param index defines the offset in the destination array
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.toArray = function (array, index) {
  2763. if (index === void 0) { index = 0; }
  2764. array[index] = this.x;
  2765. array[index + 1] = this.y;
  2766. array[index + 2] = this.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2771. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2772. */
  2773. Vector3.prototype.toQuaternion = function () {
  2774. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2775. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2776. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2777. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2778. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2779. var cosy = Math.cos(this.y * 0.5);
  2780. var siny = Math.sin(this.y * 0.5);
  2781. result.x = coszMinusx * siny;
  2782. result.y = -sinzMinusx * siny;
  2783. result.z = sinxPlusz * cosy;
  2784. result.w = cosxPlusz * cosy;
  2785. return result;
  2786. };
  2787. /**
  2788. * Adds the passed vector to the current Vector3
  2789. * @param otherVector defines the second operand
  2790. * @returns the current updated Vector3
  2791. */
  2792. Vector3.prototype.addInPlace = function (otherVector) {
  2793. this.x += otherVector.x;
  2794. this.y += otherVector.y;
  2795. this.z += otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2800. * @param otherVector defines the second operand
  2801. * @returns the resulting Vector3
  2802. */
  2803. Vector3.prototype.add = function (otherVector) {
  2804. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2805. };
  2806. /**
  2807. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2808. * @param otherVector defines the second operand
  2809. * @param result defines the Vector3 object where to store the result
  2810. * @returns the current Vector3
  2811. */
  2812. Vector3.prototype.addToRef = function (otherVector, result) {
  2813. result.x = this.x + otherVector.x;
  2814. result.y = this.y + otherVector.y;
  2815. result.z = this.z + otherVector.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Subtract the passed vector from the current Vector3
  2820. * @param otherVector defines the second operand
  2821. * @returns the current updated Vector3
  2822. */
  2823. Vector3.prototype.subtractInPlace = function (otherVector) {
  2824. this.x -= otherVector.x;
  2825. this.y -= otherVector.y;
  2826. this.z -= otherVector.z;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2831. * @param otherVector defines the second operand
  2832. * @returns the resulting Vector3
  2833. */
  2834. Vector3.prototype.subtract = function (otherVector) {
  2835. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2836. };
  2837. /**
  2838. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2839. * @param otherVector defines the second operand
  2840. * @param result defines the Vector3 object where to store the result
  2841. * @returns the current Vector3
  2842. */
  2843. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2844. result.x = this.x - otherVector.x;
  2845. result.y = this.y - otherVector.y;
  2846. result.z = this.z - otherVector.z;
  2847. return this;
  2848. };
  2849. /**
  2850. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2857. return new Vector3(this.x - x, this.y - y, this.z - z);
  2858. };
  2859. /**
  2860. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2861. * @param x defines the x coordinate of the operand
  2862. * @param y defines the y coordinate of the operand
  2863. * @param z defines the z coordinate of the operand
  2864. * @param result defines the Vector3 object where to store the result
  2865. * @returns the current Vector3
  2866. */
  2867. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2868. result.x = this.x - x;
  2869. result.y = this.y - y;
  2870. result.z = this.z - z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2875. * @returns a new Vector3
  2876. */
  2877. Vector3.prototype.negate = function () {
  2878. return new Vector3(-this.x, -this.y, -this.z);
  2879. };
  2880. /**
  2881. * Multiplies the Vector3 coordinates by the float "scale"
  2882. * @param scale defines the multiplier factor
  2883. * @returns the current updated Vector3
  2884. */
  2885. Vector3.prototype.scaleInPlace = function (scale) {
  2886. this.x *= scale;
  2887. this.y *= scale;
  2888. this.z *= scale;
  2889. return this;
  2890. };
  2891. /**
  2892. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2893. * @param scale defines the multiplier factor
  2894. * @returns a new Vector3
  2895. */
  2896. Vector3.prototype.scale = function (scale) {
  2897. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2898. };
  2899. /**
  2900. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2901. * @param scale defines the multiplier factor
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.scaleToRef = function (scale, result) {
  2906. result.x = this.x * scale;
  2907. result.y = this.y * scale;
  2908. result.z = this.z * scale;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2913. * @param otherVector defines the second operand
  2914. * @returns true if both vectors are equals
  2915. */
  2916. Vector3.prototype.equals = function (otherVector) {
  2917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2918. };
  2919. /**
  2920. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2921. * @param otherVector defines the second operand
  2922. * @param epsilon defines the minimal distance to define values as equals
  2923. * @returns true if both vectors are distant less than epsilon
  2924. */
  2925. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2928. };
  2929. /**
  2930. * Returns true if the current Vector3 coordinates equals the passed floats
  2931. * @param x defines the x coordinate of the operand
  2932. * @param y defines the y coordinate of the operand
  2933. * @param z defines the z coordinate of the operand
  2934. * @returns true if both vectors are equals
  2935. */
  2936. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2937. return this.x === x && this.y === y && this.z === z;
  2938. };
  2939. /**
  2940. * Multiplies the current Vector3 coordinates by the passed ones
  2941. * @param otherVector defines the second operand
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2945. this.x *= otherVector.x;
  2946. this.y *= otherVector.y;
  2947. this.z *= otherVector.z;
  2948. return this;
  2949. };
  2950. /**
  2951. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2952. * @param otherVector defines the second operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiply = function (otherVector) {
  2956. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2957. };
  2958. /**
  2959. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2960. * @param otherVector defines the second operand
  2961. * @param result defines the Vector3 object where to store the result
  2962. * @returns the current Vector3
  2963. */
  2964. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2965. result.x = this.x * otherVector.x;
  2966. result.y = this.y * otherVector.y;
  2967. result.z = this.z * otherVector.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the new Vector3
  2976. */
  2977. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2978. return new Vector3(this.x * x, this.y * y, this.z * z);
  2979. };
  2980. /**
  2981. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the new Vector3
  2984. */
  2985. Vector3.prototype.divide = function (otherVector) {
  2986. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2987. };
  2988. /**
  2989. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2990. * @param otherVector defines the second operand
  2991. * @param result defines the Vector3 object where to store the result
  2992. * @returns the current Vector3
  2993. */
  2994. Vector3.prototype.divideToRef = function (otherVector, result) {
  2995. result.x = this.x / otherVector.x;
  2996. result.y = this.y / otherVector.y;
  2997. result.z = this.z / otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Divides the current Vector3 coordinates by the passed ones.
  3002. * @param otherVector defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.divideInPlace = function (otherVector) {
  3006. return this.divideToRef(otherVector, this);
  3007. };
  3008. /**
  3009. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3010. * @param other defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.minimizeInPlace = function (other) {
  3014. if (other.x < this.x)
  3015. this.x = other.x;
  3016. if (other.y < this.y)
  3017. this.y = other.y;
  3018. if (other.z < this.z)
  3019. this.z = other.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3024. * @param other defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.maximizeInPlace = function (other) {
  3028. if (other.x > this.x)
  3029. this.x = other.x;
  3030. if (other.y > this.y)
  3031. this.y = other.y;
  3032. if (other.z > this.z)
  3033. this.z = other.z;
  3034. return this;
  3035. };
  3036. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3037. /**
  3038. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3039. */
  3040. get: function () {
  3041. var absX = Math.abs(this.x);
  3042. var absY = Math.abs(this.y);
  3043. if (absX !== absY) {
  3044. return true;
  3045. }
  3046. var absZ = Math.abs(this.z);
  3047. if (absX !== absZ) {
  3048. return true;
  3049. }
  3050. if (absY !== absZ) {
  3051. return true;
  3052. }
  3053. return false;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. // Properties
  3059. /**
  3060. * Gets the length of the Vector3
  3061. * @returns the length of the Vecto3
  3062. */
  3063. Vector3.prototype.length = function () {
  3064. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3065. };
  3066. /**
  3067. * Gets the squared length of the Vector3
  3068. * @returns squared length of the Vector3
  3069. */
  3070. Vector3.prototype.lengthSquared = function () {
  3071. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3072. };
  3073. /**
  3074. * Normalize the current Vector3.
  3075. * Please note that this is an in place operation.
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.normalize = function () {
  3079. var len = this.length();
  3080. if (len === 0 || len === 1.0)
  3081. return this;
  3082. var num = 1.0 / len;
  3083. this.x *= num;
  3084. this.y *= num;
  3085. this.z *= num;
  3086. return this;
  3087. };
  3088. /**
  3089. * Normalize the current Vector3 to a new vector
  3090. * @returns the new Vector3
  3091. */
  3092. Vector3.prototype.normalizeToNew = function () {
  3093. var normalized = new Vector3(0, 0, 0);
  3094. this.normalizeToRef(normalized);
  3095. return normalized;
  3096. };
  3097. /**
  3098. * Normalize the current Vector3 to the reference
  3099. * @param reference define the Vector3 to update
  3100. * @returns the updated Vector3
  3101. */
  3102. Vector3.prototype.normalizeToRef = function (reference) {
  3103. var len = this.length();
  3104. if (len === 0 || len === 1.0) {
  3105. reference.set(this.x, this.y, this.z);
  3106. return reference;
  3107. }
  3108. var scale = 1.0 / len;
  3109. this.scaleToRef(scale, reference);
  3110. return reference;
  3111. };
  3112. /**
  3113. * Creates a new Vector3 copied from the current Vector3
  3114. * @returns the new Vector3
  3115. */
  3116. Vector3.prototype.clone = function () {
  3117. return new Vector3(this.x, this.y, this.z);
  3118. };
  3119. /**
  3120. * Copies the passed vector coordinates to the current Vector3 ones
  3121. * @param source defines the source Vector3
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.copyFrom = function (source) {
  3125. this.x = source.x;
  3126. this.y = source.y;
  3127. this.z = source.z;
  3128. return this;
  3129. };
  3130. /**
  3131. * Copies the passed floats to the current Vector3 coordinates
  3132. * @param x defines the x coordinate of the operand
  3133. * @param y defines the y coordinate of the operand
  3134. * @param z defines the z coordinate of the operand
  3135. * @returns the current updated Vector3
  3136. */
  3137. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3138. this.x = x;
  3139. this.y = y;
  3140. this.z = z;
  3141. return this;
  3142. };
  3143. /**
  3144. * Copies the passed floats to the current Vector3 coordinates
  3145. * @param x defines the x coordinate of the operand
  3146. * @param y defines the y coordinate of the operand
  3147. * @param z defines the z coordinate of the operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.set = function (x, y, z) {
  3151. return this.copyFromFloats(x, y, z);
  3152. };
  3153. // Statics
  3154. /**
  3155. * Get the clip factor between two vectors
  3156. * @param vector0 defines the first operand
  3157. * @param vector1 defines the second operand
  3158. * @param axis defines the axis to use
  3159. * @param size defines the size along the axis
  3160. * @returns the clip factor
  3161. */
  3162. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3163. var d0 = Vector3.Dot(vector0, axis) - size;
  3164. var d1 = Vector3.Dot(vector1, axis) - size;
  3165. var s = d0 / (d0 - d1);
  3166. return s;
  3167. };
  3168. /**
  3169. * Get angle between two vectors
  3170. * @param vector0 angle between vector0 and vector1
  3171. * @param vector1 angle between vector0 and vector1
  3172. * @param normal direction of the normal
  3173. * @return the angle between vector0 and vector1
  3174. */
  3175. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3176. var v0 = vector0.clone().normalize();
  3177. var v1 = vector1.clone().normalize();
  3178. var dot = Vector3.Dot(v0, v1);
  3179. var n = Vector3.Cross(v0, v1);
  3180. if (Vector3.Dot(n, normal) > 0) {
  3181. return Math.acos(dot);
  3182. }
  3183. return -Math.acos(dot);
  3184. };
  3185. /**
  3186. * Returns a new Vector3 set from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @returns the new Vector3
  3190. */
  3191. Vector3.FromArray = function (array, offset) {
  3192. if (!offset) {
  3193. offset = 0;
  3194. }
  3195. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3199. * This function is deprecated. Use FromArray instead
  3200. * @param array defines the source array
  3201. * @param offset defines the offset in the source array
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.FromFloatArray = function (array, offset) {
  3205. return Vector3.FromArray(array, offset);
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3209. * @param array defines the source array
  3210. * @param offset defines the offset in the source array
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromArrayToRef = function (array, offset, result) {
  3214. result.x = array[offset];
  3215. result.y = array[offset + 1];
  3216. result.z = array[offset + 2];
  3217. };
  3218. /**
  3219. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3220. * This function is deprecated. Use FromArrayToRef instead.
  3221. * @param array defines the source array
  3222. * @param offset defines the offset in the source array
  3223. * @param result defines the Vector3 where to store the result
  3224. */
  3225. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3226. return Vector3.FromArrayToRef(array, offset, result);
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" with the passed floats.
  3230. * @param x defines the x coordinate of the source
  3231. * @param y defines the y coordinate of the source
  3232. * @param z defines the z coordinate of the source
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3236. result.x = x;
  3237. result.y = y;
  3238. result.z = z;
  3239. };
  3240. /**
  3241. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3242. * @returns a new empty Vector3
  3243. */
  3244. Vector3.Zero = function () {
  3245. return new Vector3(0.0, 0.0, 0.0);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3249. * @returns a new unit Vector3
  3250. */
  3251. Vector3.One = function () {
  3252. return new Vector3(1.0, 1.0, 1.0);
  3253. };
  3254. /**
  3255. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3256. * @returns a new up Vector3
  3257. */
  3258. Vector3.Up = function () {
  3259. return new Vector3(0.0, 1.0, 0.0);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3263. * @returns a new forward Vector3
  3264. */
  3265. Vector3.Forward = function () {
  3266. return new Vector3(0.0, 0.0, 1.0);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3270. * @returns a new right Vector3
  3271. */
  3272. Vector3.Right = function () {
  3273. return new Vector3(1.0, 0.0, 0.0);
  3274. };
  3275. /**
  3276. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3277. * @returns a new left Vector3
  3278. */
  3279. Vector3.Left = function () {
  3280. return new Vector3(-1.0, 0.0, 0.0);
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3284. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3285. * @param vector defines the Vector3 to transform
  3286. * @param transformation defines the transformation matrix
  3287. * @returns the transformed Vector3
  3288. */
  3289. Vector3.TransformCoordinates = function (vector, transformation) {
  3290. var result = Vector3.Zero();
  3291. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3296. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3297. * @param vector defines the Vector3 to transform
  3298. * @param transformation defines the transformation matrix
  3299. * @param result defines the Vector3 where to store the result
  3300. */
  3301. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3302. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3303. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3304. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3305. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3306. result.x = x / w;
  3307. result.y = y / w;
  3308. result.z = z / w;
  3309. };
  3310. /**
  3311. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3312. * This method computes tranformed coordinates only, not transformed direction vectors
  3313. * @param x define the x coordinate of the source vector
  3314. * @param y define the y coordinate of the source vector
  3315. * @param z define the z coordinate of the source vector
  3316. * @param transformation defines the transformation matrix
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3320. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3321. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3322. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3323. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3324. result.x = rx / rw;
  3325. result.y = ry / rw;
  3326. result.z = rz / rw;
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3330. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3331. * @param vector defines the Vector3 to transform
  3332. * @param transformation defines the transformation matrix
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.TransformNormal = function (vector, transformation) {
  3336. var result = Vector3.Zero();
  3337. Vector3.TransformNormalToRef(vector, transformation, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3342. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3343. * @param vector defines the Vector3 to transform
  3344. * @param transformation defines the transformation matrix
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3348. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3349. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3350. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3351. result.x = x;
  3352. result.y = y;
  3353. result.z = z;
  3354. };
  3355. /**
  3356. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3357. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3366. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3367. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3371. * @param value1 defines the first control point
  3372. * @param value2 defines the second control point
  3373. * @param value3 defines the third control point
  3374. * @param value4 defines the fourth control point
  3375. * @param amount defines the amount on the spline to use
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3382. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3383. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3384. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3385. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3386. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3387. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3388. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3389. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3390. return new Vector3(x, y, z);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3394. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3395. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3396. * @param value defines the current value
  3397. * @param min defines the lower range value
  3398. * @param max defines the upper range value
  3399. * @returns the new Vector3
  3400. */
  3401. Vector3.Clamp = function (value, min, max) {
  3402. var x = value.x;
  3403. x = (x > max.x) ? max.x : x;
  3404. x = (x < min.x) ? min.x : x;
  3405. var y = value.y;
  3406. y = (y > max.y) ? max.y : y;
  3407. y = (y < min.y) ? min.y : y;
  3408. var z = value.z;
  3409. z = (z > max.z) ? max.z : z;
  3410. z = (z < min.z) ? min.z : z;
  3411. return new Vector3(x, y, z);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3415. * @param value1 defines the first control point
  3416. * @param tangent1 defines the first tangent vector
  3417. * @param value2 defines the second control point
  3418. * @param tangent2 defines the second tangent vector
  3419. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3423. var squared = amount * amount;
  3424. var cubed = amount * squared;
  3425. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3426. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3427. var part3 = (cubed - (2.0 * squared)) + amount;
  3428. var part4 = cubed - squared;
  3429. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3430. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3431. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3436. * @param start defines the start value
  3437. * @param end defines the end value
  3438. * @param amount max defines amount between both (between 0 and 1)
  3439. * @returns the new Vector3
  3440. */
  3441. Vector3.Lerp = function (start, end, amount) {
  3442. var result = new Vector3(0, 0, 0);
  3443. Vector3.LerpToRef(start, end, amount, result);
  3444. return result;
  3445. };
  3446. /**
  3447. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3448. * @param start defines the start value
  3449. * @param end defines the end value
  3450. * @param amount max defines amount between both (between 0 and 1)
  3451. * @param result defines the Vector3 where to store the result
  3452. */
  3453. Vector3.LerpToRef = function (start, end, amount, result) {
  3454. result.x = start.x + ((end.x - start.x) * amount);
  3455. result.y = start.y + ((end.y - start.y) * amount);
  3456. result.z = start.z + ((end.z - start.z) * amount);
  3457. };
  3458. /**
  3459. * Returns the dot product (float) between the vectors "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @returns the dot product
  3463. */
  3464. Vector3.Dot = function (left, right) {
  3465. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3466. };
  3467. /**
  3468. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3469. * The cross product is then orthogonal to both "left" and "right"
  3470. * @param left defines the left operand
  3471. * @param right defines the right operand
  3472. * @returns the cross product
  3473. */
  3474. Vector3.Cross = function (left, right) {
  3475. var result = Vector3.Zero();
  3476. Vector3.CrossToRef(left, right, result);
  3477. return result;
  3478. };
  3479. /**
  3480. * Sets the passed vector "result" with the cross product of "left" and "right"
  3481. * The cross product is then orthogonal to both "left" and "right"
  3482. * @param left defines the left operand
  3483. * @param right defines the right operand
  3484. * @param result defines the Vector3 where to store the result
  3485. */
  3486. Vector3.CrossToRef = function (left, right, result) {
  3487. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3488. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3489. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3490. result.copyFrom(MathTmp.Vector3[0]);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 as the normalization of the passed vector
  3494. * @param vector defines the Vector3 to normalize
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Normalize = function (vector) {
  3498. var result = Vector3.Zero();
  3499. Vector3.NormalizeToRef(vector, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Sets the passed vector "result" with the normalization of the passed first vector
  3504. * @param vector defines the Vector3 to normalize
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.NormalizeToRef = function (vector, result) {
  3508. result.copyFrom(vector);
  3509. result.normalize();
  3510. };
  3511. /**
  3512. * Project a Vector3 onto screen space
  3513. * @param vector defines the Vector3 to project
  3514. * @param world defines the world matrix to use
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @param viewport defines the screen viewport to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Project = function (vector, world, transform, viewport) {
  3520. var cw = viewport.width;
  3521. var ch = viewport.height;
  3522. var cx = viewport.x;
  3523. var cy = viewport.y;
  3524. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3525. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3526. var matrix = MathTmp.Matrix[0];
  3527. world.multiplyToRef(transform, matrix);
  3528. matrix.multiplyToRef(viewportMatrix, matrix);
  3529. return Vector3.TransformCoordinates(vector, matrix);
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param transform defines the transform (view x projection) matrix to use
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3541. var matrix = MathTmp.Matrix[0];
  3542. world.multiplyToRef(transform, matrix);
  3543. matrix.invert();
  3544. source.x = source.x / viewportWidth * 2 - 1;
  3545. source.y = -(source.y / viewportHeight * 2 - 1);
  3546. var vector = Vector3.TransformCoordinates(source, matrix);
  3547. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3548. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3549. vector = vector.scale(1.0 / num);
  3550. }
  3551. return vector;
  3552. };
  3553. /**
  3554. * Unproject from screen space to object space
  3555. * @param source defines the screen space Vector3 to use
  3556. * @param viewportWidth defines the current width of the viewport
  3557. * @param viewportHeight defines the current height of the viewport
  3558. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3559. * @param view defines the view matrix to use
  3560. * @param projection defines the projection matrix to use
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3564. var result = Vector3.Zero();
  3565. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Unproject from screen space to object space
  3570. * @param source defines the screen space Vector3 to use
  3571. * @param viewportWidth defines the current width of the viewport
  3572. * @param viewportHeight defines the current height of the viewport
  3573. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3574. * @param view defines the view matrix to use
  3575. * @param projection defines the projection matrix to use
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3579. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3580. };
  3581. /**
  3582. * Unproject from screen space to object space
  3583. * @param sourceX defines the screen space x coordinate to use
  3584. * @param sourceY defines the screen space y coordinate to use
  3585. * @param sourceZ defines the screen space z coordinate to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param view defines the view matrix to use
  3590. * @param projection defines the projection matrix to use
  3591. * @param result defines the Vector3 where to store the result
  3592. */
  3593. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(view, matrix);
  3596. matrix.multiplyToRef(projection, matrix);
  3597. matrix.invert();
  3598. var screenSource = MathTmp.Vector3[0];
  3599. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3600. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3601. screenSource.z = 2 * sourceZ - 1.0;
  3602. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3603. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3604. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3605. result.scaleInPlace(1.0 / num);
  3606. }
  3607. };
  3608. /**
  3609. * Gets the minimal coordinate values between two Vector3
  3610. * @param left defines the first operand
  3611. * @param right defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Minimize = function (left, right) {
  3615. var min = left.clone();
  3616. min.minimizeInPlace(right);
  3617. return min;
  3618. };
  3619. /**
  3620. * Gets the maximal coordinate values between two Vector3
  3621. * @param left defines the first operand
  3622. * @param right defines the second operand
  3623. * @returns the new Vector3
  3624. */
  3625. Vector3.Maximize = function (left, right) {
  3626. var max = left.clone();
  3627. max.maximizeInPlace(right);
  3628. return max;
  3629. };
  3630. /**
  3631. * Returns the distance between the vectors "value1" and "value2"
  3632. * @param value1 defines the first operand
  3633. * @param value2 defines the second operand
  3634. * @returns the distance
  3635. */
  3636. Vector3.Distance = function (value1, value2) {
  3637. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3638. };
  3639. /**
  3640. * Returns the squared distance between the vectors "value1" and "value2"
  3641. * @param value1 defines the first operand
  3642. * @param value2 defines the second operand
  3643. * @returns the squared distance
  3644. */
  3645. Vector3.DistanceSquared = function (value1, value2) {
  3646. var x = value1.x - value2.x;
  3647. var y = value1.y - value2.y;
  3648. var z = value1.z - value2.z;
  3649. return (x * x) + (y * y) + (z * z);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 located at the center between "value1" and "value2"
  3653. * @param value1 defines the first operand
  3654. * @param value2 defines the second operand
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Center = function (value1, value2) {
  3658. var center = value1.add(value2);
  3659. center.scaleInPlace(0.5);
  3660. return center;
  3661. };
  3662. /**
  3663. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3664. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3665. * to something in order to rotate it from its local system to the given target system
  3666. * Note: axis1, axis2 and axis3 are normalized during this operation
  3667. * @param axis1 defines the first axis
  3668. * @param axis2 defines the second axis
  3669. * @param axis3 defines the third axis
  3670. * @returns a new Vector3
  3671. */
  3672. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3673. var rotation = Vector3.Zero();
  3674. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3675. return rotation;
  3676. };
  3677. /**
  3678. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3679. * @param axis1 defines the first axis
  3680. * @param axis2 defines the second axis
  3681. * @param axis3 defines the third axis
  3682. * @param ref defines the Vector3 where to store the result
  3683. */
  3684. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3685. var quat = MathTmp.Quaternion[0];
  3686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3687. quat.toEulerAnglesToRef(ref);
  3688. };
  3689. return Vector3;
  3690. }());
  3691. BABYLON.Vector3 = Vector3;
  3692. //Vector4 class created for EulerAngle class conversion to Quaternion
  3693. var Vector4 = /** @class */ (function () {
  3694. /**
  3695. * Creates a Vector4 object from the passed floats.
  3696. */
  3697. function Vector4(x, y, z, w) {
  3698. this.x = x;
  3699. this.y = y;
  3700. this.z = z;
  3701. this.w = w;
  3702. }
  3703. /**
  3704. * Returns the string with the Vector4 coordinates.
  3705. */
  3706. Vector4.prototype.toString = function () {
  3707. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3708. };
  3709. /**
  3710. * Returns the string "Vector4".
  3711. */
  3712. Vector4.prototype.getClassName = function () {
  3713. return "Vector4";
  3714. };
  3715. /**
  3716. * Returns the Vector4 hash code.
  3717. */
  3718. Vector4.prototype.getHashCode = function () {
  3719. var hash = this.x || 0;
  3720. hash = (hash * 397) ^ (this.y || 0);
  3721. hash = (hash * 397) ^ (this.z || 0);
  3722. hash = (hash * 397) ^ (this.w || 0);
  3723. return hash;
  3724. };
  3725. // Operators
  3726. /**
  3727. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.asArray = function () {
  3730. var result = new Array();
  3731. this.toArray(result, 0);
  3732. return result;
  3733. };
  3734. /**
  3735. * Populates the passed array from the passed index with the Vector4 coordinates.
  3736. * Returns the Vector4.
  3737. */
  3738. Vector4.prototype.toArray = function (array, index) {
  3739. if (index === undefined) {
  3740. index = 0;
  3741. }
  3742. array[index] = this.x;
  3743. array[index + 1] = this.y;
  3744. array[index + 2] = this.z;
  3745. array[index + 3] = this.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Adds the passed vector to the current Vector4.
  3750. * Returns the updated Vector4.
  3751. */
  3752. Vector4.prototype.addInPlace = function (otherVector) {
  3753. this.x += otherVector.x;
  3754. this.y += otherVector.y;
  3755. this.z += otherVector.z;
  3756. this.w += otherVector.w;
  3757. return this;
  3758. };
  3759. /**
  3760. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3761. */
  3762. Vector4.prototype.add = function (otherVector) {
  3763. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3764. };
  3765. /**
  3766. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3767. * Returns the current Vector4.
  3768. */
  3769. Vector4.prototype.addToRef = function (otherVector, result) {
  3770. result.x = this.x + otherVector.x;
  3771. result.y = this.y + otherVector.y;
  3772. result.z = this.z + otherVector.z;
  3773. result.w = this.w + otherVector.w;
  3774. return this;
  3775. };
  3776. /**
  3777. * Subtract in place the passed vector from the current Vector4.
  3778. * Returns the updated Vector4.
  3779. */
  3780. Vector4.prototype.subtractInPlace = function (otherVector) {
  3781. this.x -= otherVector.x;
  3782. this.y -= otherVector.y;
  3783. this.z -= otherVector.z;
  3784. this.w -= otherVector.w;
  3785. return this;
  3786. };
  3787. /**
  3788. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3789. */
  3790. Vector4.prototype.subtract = function (otherVector) {
  3791. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3792. };
  3793. /**
  3794. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3795. * Returns the current Vector4.
  3796. */
  3797. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3798. result.x = this.x - otherVector.x;
  3799. result.y = this.y - otherVector.y;
  3800. result.z = this.z - otherVector.z;
  3801. result.w = this.w - otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3806. */
  3807. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3808. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3809. };
  3810. /**
  3811. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3815. result.x = this.x - x;
  3816. result.y = this.y - y;
  3817. result.z = this.z - z;
  3818. result.w = this.w - w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3823. */
  3824. Vector4.prototype.negate = function () {
  3825. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3826. };
  3827. /**
  3828. * Multiplies the current Vector4 coordinates by scale (float).
  3829. * Returns the updated Vector4.
  3830. */
  3831. Vector4.prototype.scaleInPlace = function (scale) {
  3832. this.x *= scale;
  3833. this.y *= scale;
  3834. this.z *= scale;
  3835. this.w *= scale;
  3836. return this;
  3837. };
  3838. /**
  3839. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3840. */
  3841. Vector4.prototype.scale = function (scale) {
  3842. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3843. };
  3844. /**
  3845. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3846. * Returns the current Vector4.
  3847. */
  3848. Vector4.prototype.scaleToRef = function (scale, result) {
  3849. result.x = this.x * scale;
  3850. result.y = this.y * scale;
  3851. result.z = this.z * scale;
  3852. result.w = this.w * scale;
  3853. return this;
  3854. };
  3855. /**
  3856. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3857. */
  3858. Vector4.prototype.equals = function (otherVector) {
  3859. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3860. };
  3861. /**
  3862. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3863. */
  3864. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3865. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3866. return otherVector
  3867. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3868. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3869. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3870. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3871. };
  3872. /**
  3873. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3876. return this.x === x && this.y === y && this.z === z && this.w === w;
  3877. };
  3878. /**
  3879. * Multiplies in place the current Vector4 by the passed one.
  3880. * Returns the updated Vector4.
  3881. */
  3882. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3883. this.x *= otherVector.x;
  3884. this.y *= otherVector.y;
  3885. this.z *= otherVector.z;
  3886. this.w *= otherVector.w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3891. */
  3892. Vector4.prototype.multiply = function (otherVector) {
  3893. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3894. };
  3895. /**
  3896. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3897. * Returns the current Vector4.
  3898. */
  3899. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3900. result.x = this.x * otherVector.x;
  3901. result.y = this.y * otherVector.y;
  3902. result.z = this.z * otherVector.z;
  3903. result.w = this.w * otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3908. */
  3909. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3910. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3914. */
  3915. Vector4.prototype.divide = function (otherVector) {
  3916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3920. * Returns the current Vector4.
  3921. */
  3922. Vector4.prototype.divideToRef = function (otherVector, result) {
  3923. result.x = this.x / otherVector.x;
  3924. result.y = this.y / otherVector.y;
  3925. result.z = this.z / otherVector.z;
  3926. result.w = this.w / otherVector.w;
  3927. return this;
  3928. };
  3929. /**
  3930. * Divides the current Vector3 coordinates by the passed ones.
  3931. * @returns the updated Vector3.
  3932. */
  3933. Vector4.prototype.divideInPlace = function (otherVector) {
  3934. return this.divideToRef(otherVector, this);
  3935. };
  3936. /**
  3937. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3938. * @param other defines the second operand
  3939. * @returns the current updated Vector4
  3940. */
  3941. Vector4.prototype.minimizeInPlace = function (other) {
  3942. if (other.x < this.x)
  3943. this.x = other.x;
  3944. if (other.y < this.y)
  3945. this.y = other.y;
  3946. if (other.z < this.z)
  3947. this.z = other.z;
  3948. if (other.w < this.w)
  3949. this.w = other.w;
  3950. return this;
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.maximizeInPlace = function (other) {
  3958. if (other.x > this.x)
  3959. this.x = other.x;
  3960. if (other.y > this.y)
  3961. this.y = other.y;
  3962. if (other.z > this.z)
  3963. this.z = other.z;
  3964. if (other.w > this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. // Properties
  3969. /**
  3970. * Returns the Vector4 length (float).
  3971. */
  3972. Vector4.prototype.length = function () {
  3973. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3974. };
  3975. /**
  3976. * Returns the Vector4 squared length (float).
  3977. */
  3978. Vector4.prototype.lengthSquared = function () {
  3979. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3980. };
  3981. // Methods
  3982. /**
  3983. * Normalizes in place the Vector4.
  3984. * Returns the updated Vector4.
  3985. */
  3986. Vector4.prototype.normalize = function () {
  3987. var len = this.length();
  3988. if (len === 0)
  3989. return this;
  3990. var num = 1.0 / len;
  3991. this.x *= num;
  3992. this.y *= num;
  3993. this.z *= num;
  3994. this.w *= num;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3999. */
  4000. Vector4.prototype.toVector3 = function () {
  4001. return new Vector3(this.x, this.y, this.z);
  4002. };
  4003. /**
  4004. * Returns a new Vector4 copied from the current one.
  4005. */
  4006. Vector4.prototype.clone = function () {
  4007. return new Vector4(this.x, this.y, this.z, this.w);
  4008. };
  4009. /**
  4010. * Updates the current Vector4 with the passed one coordinates.
  4011. * Returns the updated Vector4.
  4012. */
  4013. Vector4.prototype.copyFrom = function (source) {
  4014. this.x = source.x;
  4015. this.y = source.y;
  4016. this.z = source.z;
  4017. this.w = source.w;
  4018. return this;
  4019. };
  4020. /**
  4021. * Updates the current Vector4 coordinates with the passed floats.
  4022. * Returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4025. this.x = x;
  4026. this.y = y;
  4027. this.z = z;
  4028. this.w = w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Updates the current Vector4 coordinates with the passed floats.
  4033. * Returns the updated Vector4.
  4034. */
  4035. Vector4.prototype.set = function (x, y, z, w) {
  4036. return this.copyFromFloats(x, y, z, w);
  4037. };
  4038. // Statics
  4039. /**
  4040. * Returns a new Vector4 set from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArray = function (array, offset) {
  4043. if (!offset) {
  4044. offset = 0;
  4045. }
  4046. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed array.
  4050. */
  4051. Vector4.FromArrayToRef = function (array, offset, result) {
  4052. result.x = array[offset];
  4053. result.y = array[offset + 1];
  4054. result.z = array[offset + 2];
  4055. result.w = array[offset + 3];
  4056. };
  4057. /**
  4058. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4059. */
  4060. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4061. Vector4.FromArrayToRef(array, offset, result);
  4062. };
  4063. /**
  4064. * Updates the passed vector "result" coordinates from the passed floats.
  4065. */
  4066. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4067. result.x = x;
  4068. result.y = y;
  4069. result.z = z;
  4070. result.w = w;
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4074. */
  4075. Vector4.Zero = function () {
  4076. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4080. */
  4081. Vector4.One = function () {
  4082. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4083. };
  4084. /**
  4085. * Returns a new normalized Vector4 from the passed one.
  4086. */
  4087. Vector4.Normalize = function (vector) {
  4088. var result = Vector4.Zero();
  4089. Vector4.NormalizeToRef(vector, result);
  4090. return result;
  4091. };
  4092. /**
  4093. * Updates the passed vector "result" from the normalization of the passed one.
  4094. */
  4095. Vector4.NormalizeToRef = function (vector, result) {
  4096. result.copyFrom(vector);
  4097. result.normalize();
  4098. };
  4099. Vector4.Minimize = function (left, right) {
  4100. var min = left.clone();
  4101. min.minimizeInPlace(right);
  4102. return min;
  4103. };
  4104. Vector4.Maximize = function (left, right) {
  4105. var max = left.clone();
  4106. max.maximizeInPlace(right);
  4107. return max;
  4108. };
  4109. /**
  4110. * Returns the distance (float) between the vectors "value1" and "value2".
  4111. */
  4112. Vector4.Distance = function (value1, value2) {
  4113. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4114. };
  4115. /**
  4116. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4117. */
  4118. Vector4.DistanceSquared = function (value1, value2) {
  4119. var x = value1.x - value2.x;
  4120. var y = value1.y - value2.y;
  4121. var z = value1.z - value2.z;
  4122. var w = value1.w - value2.w;
  4123. return (x * x) + (y * y) + (z * z) + (w * w);
  4124. };
  4125. /**
  4126. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Center = function (value1, value2) {
  4129. var center = value1.add(value2);
  4130. center.scaleInPlace(0.5);
  4131. return center;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormal = function (vector, transformation) {
  4138. var result = Vector4.Zero();
  4139. Vector4.TransformNormalToRef(vector, transformation, result);
  4140. return result;
  4141. };
  4142. /**
  4143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4144. * This methods computes transformed normalized direction vectors only.
  4145. */
  4146. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4147. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4148. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4149. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4150. result.x = x;
  4151. result.y = y;
  4152. result.z = z;
  4153. result.w = vector.w;
  4154. };
  4155. /**
  4156. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4157. * This methods computes transformed normalized direction vectors only.
  4158. */
  4159. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4160. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4161. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4162. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4163. result.w = w;
  4164. };
  4165. return Vector4;
  4166. }());
  4167. BABYLON.Vector4 = Vector4;
  4168. var Size = /** @class */ (function () {
  4169. /**
  4170. * Creates a Size object from the passed width and height (floats).
  4171. */
  4172. function Size(width, height) {
  4173. this.width = width;
  4174. this.height = height;
  4175. }
  4176. // Returns a string with the Size width and height.
  4177. Size.prototype.toString = function () {
  4178. return "{W: " + this.width + ", H: " + this.height + "}";
  4179. };
  4180. /**
  4181. * Returns the string "Size"
  4182. */
  4183. Size.prototype.getClassName = function () {
  4184. return "Size";
  4185. };
  4186. /**
  4187. * Returns the Size hash code.
  4188. */
  4189. Size.prototype.getHashCode = function () {
  4190. var hash = this.width || 0;
  4191. hash = (hash * 397) ^ (this.height || 0);
  4192. return hash;
  4193. };
  4194. /**
  4195. * Updates the current size from the passed one.
  4196. * Returns the updated Size.
  4197. */
  4198. Size.prototype.copyFrom = function (src) {
  4199. this.width = src.width;
  4200. this.height = src.height;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.copyFromFloats = function (width, height) {
  4207. this.width = width;
  4208. this.height = height;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates in place the current Size from the passed floats.
  4213. * Returns the updated Size.
  4214. */
  4215. Size.prototype.set = function (width, height) {
  4216. return this.copyFromFloats(width, height);
  4217. };
  4218. /**
  4219. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4220. */
  4221. Size.prototype.multiplyByFloats = function (w, h) {
  4222. return new Size(this.width * w, this.height * h);
  4223. };
  4224. /**
  4225. * Returns a new Size copied from the passed one.
  4226. */
  4227. Size.prototype.clone = function () {
  4228. return new Size(this.width, this.height);
  4229. };
  4230. /**
  4231. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4232. */
  4233. Size.prototype.equals = function (other) {
  4234. if (!other) {
  4235. return false;
  4236. }
  4237. return (this.width === other.width) && (this.height === other.height);
  4238. };
  4239. Object.defineProperty(Size.prototype, "surface", {
  4240. /**
  4241. * Returns the surface of the Size : width * height (float).
  4242. */
  4243. get: function () {
  4244. return this.width * this.height;
  4245. },
  4246. enumerable: true,
  4247. configurable: true
  4248. });
  4249. /**
  4250. * Returns a new Size set to (0.0, 0.0)
  4251. */
  4252. Size.Zero = function () {
  4253. return new Size(0.0, 0.0);
  4254. };
  4255. /**
  4256. * Returns a new Size set as the addition result of the current Size and the passed one.
  4257. */
  4258. Size.prototype.add = function (otherSize) {
  4259. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4260. return r;
  4261. };
  4262. /**
  4263. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4264. */
  4265. Size.prototype.subtract = function (otherSize) {
  4266. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4267. return r;
  4268. };
  4269. /**
  4270. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4271. */
  4272. Size.Lerp = function (start, end, amount) {
  4273. var w = start.width + ((end.width - start.width) * amount);
  4274. var h = start.height + ((end.height - start.height) * amount);
  4275. return new Size(w, h);
  4276. };
  4277. return Size;
  4278. }());
  4279. BABYLON.Size = Size;
  4280. var Quaternion = /** @class */ (function () {
  4281. /**
  4282. * Creates a new Quaternion from the passed floats.
  4283. */
  4284. function Quaternion(x, y, z, w) {
  4285. if (x === void 0) { x = 0.0; }
  4286. if (y === void 0) { y = 0.0; }
  4287. if (z === void 0) { z = 0.0; }
  4288. if (w === void 0) { w = 1.0; }
  4289. this.x = x;
  4290. this.y = y;
  4291. this.z = z;
  4292. this.w = w;
  4293. }
  4294. /**
  4295. * Returns a string with the Quaternion coordinates.
  4296. */
  4297. Quaternion.prototype.toString = function () {
  4298. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4299. };
  4300. /**
  4301. * Returns the string "Quaternion".
  4302. */
  4303. Quaternion.prototype.getClassName = function () {
  4304. return "Quaternion";
  4305. };
  4306. /**
  4307. * Returns the Quaternion hash code.
  4308. */
  4309. Quaternion.prototype.getHashCode = function () {
  4310. var hash = this.x || 0;
  4311. hash = (hash * 397) ^ (this.y || 0);
  4312. hash = (hash * 397) ^ (this.z || 0);
  4313. hash = (hash * 397) ^ (this.w || 0);
  4314. return hash;
  4315. };
  4316. /**
  4317. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4318. */
  4319. Quaternion.prototype.asArray = function () {
  4320. return [this.x, this.y, this.z, this.w];
  4321. };
  4322. /**
  4323. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4324. */
  4325. Quaternion.prototype.equals = function (otherQuaternion) {
  4326. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4327. };
  4328. /**
  4329. * Returns a new Quaternion copied from the current one.
  4330. */
  4331. Quaternion.prototype.clone = function () {
  4332. return new Quaternion(this.x, this.y, this.z, this.w);
  4333. };
  4334. /**
  4335. * Updates the current Quaternion from the passed one coordinates.
  4336. * Returns the updated Quaterion.
  4337. */
  4338. Quaternion.prototype.copyFrom = function (other) {
  4339. this.x = other.x;
  4340. this.y = other.y;
  4341. this.z = other.z;
  4342. this.w = other.w;
  4343. return this;
  4344. };
  4345. /**
  4346. * Updates the current Quaternion from the passed float coordinates.
  4347. * Returns the updated Quaterion.
  4348. */
  4349. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4350. this.x = x;
  4351. this.y = y;
  4352. this.z = z;
  4353. this.w = w;
  4354. return this;
  4355. };
  4356. /**
  4357. * Updates the current Quaternion from the passed float coordinates.
  4358. * Returns the updated Quaterion.
  4359. */
  4360. Quaternion.prototype.set = function (x, y, z, w) {
  4361. return this.copyFromFloats(x, y, z, w);
  4362. };
  4363. /**
  4364. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4365. */
  4366. Quaternion.prototype.add = function (other) {
  4367. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4368. };
  4369. /**
  4370. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4371. */
  4372. Quaternion.prototype.subtract = function (other) {
  4373. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4374. };
  4375. /**
  4376. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4377. */
  4378. Quaternion.prototype.scale = function (value) {
  4379. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4454. */
  4455. Quaternion.prototype.toEulerAngles = function (order) {
  4456. if (order === void 0) { order = "YZX"; }
  4457. var result = Vector3.Zero();
  4458. this.toEulerAnglesToRef(result, order);
  4459. return result;
  4460. };
  4461. /**
  4462. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4463. * Returns the current Quaternion.
  4464. */
  4465. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4466. if (order === void 0) { order = "YZX"; }
  4467. var qz = this.z;
  4468. var qx = this.x;
  4469. var qy = this.y;
  4470. var qw = this.w;
  4471. var sqw = qw * qw;
  4472. var sqz = qz * qz;
  4473. var sqx = qx * qx;
  4474. var sqy = qy * qy;
  4475. var zAxisY = qy * qz - qx * qw;
  4476. var limit = .4999999;
  4477. if (zAxisY < -limit) {
  4478. result.y = 2 * Math.atan2(qy, qw);
  4479. result.x = Math.PI / 2;
  4480. result.z = 0;
  4481. }
  4482. else if (zAxisY > limit) {
  4483. result.y = 2 * Math.atan2(qy, qw);
  4484. result.x = -Math.PI / 2;
  4485. result.z = 0;
  4486. }
  4487. else {
  4488. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4489. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4490. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4491. }
  4492. return this;
  4493. };
  4494. /**
  4495. * Updates the passed rotation matrix with the current Quaternion values.
  4496. * Returns the current Quaternion.
  4497. */
  4498. Quaternion.prototype.toRotationMatrix = function (result) {
  4499. var xx = this.x * this.x;
  4500. var yy = this.y * this.y;
  4501. var zz = this.z * this.z;
  4502. var xy = this.x * this.y;
  4503. var zw = this.z * this.w;
  4504. var zx = this.z * this.x;
  4505. var yw = this.y * this.w;
  4506. var yz = this.y * this.z;
  4507. var xw = this.x * this.w;
  4508. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4509. result.m[1] = 2.0 * (xy + zw);
  4510. result.m[2] = 2.0 * (zx - yw);
  4511. result.m[3] = 0;
  4512. result.m[4] = 2.0 * (xy - zw);
  4513. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4514. result.m[6] = 2.0 * (yz + xw);
  4515. result.m[7] = 0;
  4516. result.m[8] = 2.0 * (zx + yw);
  4517. result.m[9] = 2.0 * (yz - xw);
  4518. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4519. result.m[11] = 0;
  4520. result.m[12] = 0;
  4521. result.m[13] = 0;
  4522. result.m[14] = 0;
  4523. result.m[15] = 1.0;
  4524. result._markAsUpdated();
  4525. return this;
  4526. };
  4527. /**
  4528. * Updates the current Quaternion from the passed rotation matrix values.
  4529. * Returns the updated Quaternion.
  4530. */
  4531. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4532. Quaternion.FromRotationMatrixToRef(matrix, this);
  4533. return this;
  4534. };
  4535. // Statics
  4536. /**
  4537. * Returns a new Quaternion set from the passed rotation matrix values.
  4538. */
  4539. Quaternion.FromRotationMatrix = function (matrix) {
  4540. var result = new Quaternion();
  4541. Quaternion.FromRotationMatrixToRef(matrix, result);
  4542. return result;
  4543. };
  4544. /**
  4545. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4546. */
  4547. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4548. var data = matrix.m;
  4549. var m11 = data[0], m12 = data[4], m13 = data[8];
  4550. var m21 = data[1], m22 = data[5], m23 = data[9];
  4551. var m31 = data[2], m32 = data[6], m33 = data[10];
  4552. var trace = m11 + m22 + m33;
  4553. var s;
  4554. if (trace > 0) {
  4555. s = 0.5 / Math.sqrt(trace + 1.0);
  4556. result.w = 0.25 / s;
  4557. result.x = (m32 - m23) * s;
  4558. result.y = (m13 - m31) * s;
  4559. result.z = (m21 - m12) * s;
  4560. }
  4561. else if (m11 > m22 && m11 > m33) {
  4562. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4563. result.w = (m32 - m23) / s;
  4564. result.x = 0.25 * s;
  4565. result.y = (m12 + m21) / s;
  4566. result.z = (m13 + m31) / s;
  4567. }
  4568. else if (m22 > m33) {
  4569. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4570. result.w = (m13 - m31) / s;
  4571. result.x = (m12 + m21) / s;
  4572. result.y = 0.25 * s;
  4573. result.z = (m23 + m32) / s;
  4574. }
  4575. else {
  4576. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4577. result.w = (m21 - m12) / s;
  4578. result.x = (m13 + m31) / s;
  4579. result.y = (m23 + m32) / s;
  4580. result.z = 0.25 * s;
  4581. }
  4582. };
  4583. /**
  4584. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4585. */
  4586. Quaternion.Zero = function () {
  4587. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4588. };
  4589. /**
  4590. * Returns a new Quaternion as the inverted current Quaternion.
  4591. */
  4592. Quaternion.Inverse = function (q) {
  4593. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4594. };
  4595. /**
  4596. * Returns the identity Quaternion.
  4597. */
  4598. Quaternion.Identity = function () {
  4599. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4600. };
  4601. Quaternion.IsIdentity = function (quaternion) {
  4602. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4603. };
  4604. /**
  4605. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4606. */
  4607. Quaternion.RotationAxis = function (axis, angle) {
  4608. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4609. };
  4610. /**
  4611. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4612. */
  4613. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4614. var sin = Math.sin(angle / 2);
  4615. axis.normalize();
  4616. result.w = Math.cos(angle / 2);
  4617. result.x = axis.x * sin;
  4618. result.y = axis.y * sin;
  4619. result.z = axis.z * sin;
  4620. return result;
  4621. };
  4622. /**
  4623. * Retuns a new Quaternion set from the starting index of the passed array.
  4624. */
  4625. Quaternion.FromArray = function (array, offset) {
  4626. if (!offset) {
  4627. offset = 0;
  4628. }
  4629. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4630. };
  4631. /**
  4632. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4633. */
  4634. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4635. var q = new Quaternion();
  4636. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4637. return q;
  4638. };
  4639. /**
  4640. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4641. */
  4642. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4643. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4644. var halfRoll = roll * 0.5;
  4645. var halfPitch = pitch * 0.5;
  4646. var halfYaw = yaw * 0.5;
  4647. var sinRoll = Math.sin(halfRoll);
  4648. var cosRoll = Math.cos(halfRoll);
  4649. var sinPitch = Math.sin(halfPitch);
  4650. var cosPitch = Math.cos(halfPitch);
  4651. var sinYaw = Math.sin(halfYaw);
  4652. var cosYaw = Math.cos(halfYaw);
  4653. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4654. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4655. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4656. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4657. };
  4658. /**
  4659. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4660. */
  4661. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4662. var result = new Quaternion();
  4663. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4664. return result;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4668. */
  4669. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4670. // Produces a quaternion from Euler angles in the z-x-z orientation
  4671. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4672. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4673. var halfBeta = beta * 0.5;
  4674. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4675. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4676. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4677. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4678. };
  4679. /**
  4680. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4681. * cf to Vector3.RotationFromAxis() documentation.
  4682. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4683. */
  4684. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4685. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4687. return quat;
  4688. };
  4689. /**
  4690. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4691. * cf to Vector3.RotationFromAxis() documentation.
  4692. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4693. */
  4694. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4695. var rotMat = MathTmp.Matrix[0];
  4696. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4697. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4698. };
  4699. Quaternion.Slerp = function (left, right, amount) {
  4700. var result = Quaternion.Identity();
  4701. Quaternion.SlerpToRef(left, right, amount, result);
  4702. return result;
  4703. };
  4704. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4705. var num2;
  4706. var num3;
  4707. var num = amount;
  4708. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4709. var flag = false;
  4710. if (num4 < 0) {
  4711. flag = true;
  4712. num4 = -num4;
  4713. }
  4714. if (num4 > 0.999999) {
  4715. num3 = 1 - num;
  4716. num2 = flag ? -num : num;
  4717. }
  4718. else {
  4719. var num5 = Math.acos(num4);
  4720. var num6 = (1.0 / Math.sin(num5));
  4721. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4722. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4723. }
  4724. result.x = (num3 * left.x) + (num2 * right.x);
  4725. result.y = (num3 * left.y) + (num2 * right.y);
  4726. result.z = (num3 * left.z) + (num2 * right.z);
  4727. result.w = (num3 * left.w) + (num2 * right.w);
  4728. };
  4729. /**
  4730. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4731. */
  4732. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4733. var squared = amount * amount;
  4734. var cubed = amount * squared;
  4735. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4736. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4737. var part3 = (cubed - (2.0 * squared)) + amount;
  4738. var part4 = cubed - squared;
  4739. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4740. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4741. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4742. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4743. return new Quaternion(x, y, z, w);
  4744. };
  4745. return Quaternion;
  4746. }());
  4747. BABYLON.Quaternion = Quaternion;
  4748. var Matrix = /** @class */ (function () {
  4749. function Matrix() {
  4750. this._isIdentity = false;
  4751. this._isIdentityDirty = true;
  4752. this.m = new Float32Array(16);
  4753. this._markAsUpdated();
  4754. }
  4755. Matrix.prototype._markAsUpdated = function () {
  4756. this.updateFlag = Matrix._updateFlagSeed++;
  4757. this._isIdentityDirty = true;
  4758. };
  4759. // Properties
  4760. /**
  4761. * Boolean : True is the matrix is the identity matrix
  4762. */
  4763. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4764. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4765. if (this._isIdentityDirty) {
  4766. this._isIdentityDirty = false;
  4767. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4768. this._isIdentity = false;
  4769. }
  4770. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4771. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4772. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4773. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4774. this._isIdentity = false;
  4775. }
  4776. else {
  4777. this._isIdentity = true;
  4778. }
  4779. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4780. this._isIdentity = false;
  4781. }
  4782. }
  4783. return this._isIdentity;
  4784. };
  4785. /**
  4786. * Returns the matrix determinant (float).
  4787. */
  4788. Matrix.prototype.determinant = function () {
  4789. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4790. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4791. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4792. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4793. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4794. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4795. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4796. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4797. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4798. };
  4799. // Methods
  4800. /**
  4801. * Returns the matrix underlying array.
  4802. */
  4803. Matrix.prototype.toArray = function () {
  4804. return this.m;
  4805. };
  4806. /**
  4807. * Returns the matrix underlying array.
  4808. */
  4809. Matrix.prototype.asArray = function () {
  4810. return this.toArray();
  4811. };
  4812. /**
  4813. * Inverts in place the Matrix.
  4814. * Returns the Matrix inverted.
  4815. */
  4816. Matrix.prototype.invert = function () {
  4817. this.invertToRef(this);
  4818. return this;
  4819. };
  4820. /**
  4821. * Sets all the matrix elements to zero.
  4822. * Returns the Matrix.
  4823. */
  4824. Matrix.prototype.reset = function () {
  4825. for (var index = 0; index < 16; index++) {
  4826. this.m[index] = 0.0;
  4827. }
  4828. this._markAsUpdated();
  4829. return this;
  4830. };
  4831. /**
  4832. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4833. */
  4834. Matrix.prototype.add = function (other) {
  4835. var result = new Matrix();
  4836. this.addToRef(other, result);
  4837. return result;
  4838. };
  4839. /**
  4840. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4841. * Returns the Matrix.
  4842. */
  4843. Matrix.prototype.addToRef = function (other, result) {
  4844. for (var index = 0; index < 16; index++) {
  4845. result.m[index] = this.m[index] + other.m[index];
  4846. }
  4847. result._markAsUpdated();
  4848. return this;
  4849. };
  4850. /**
  4851. * Adds in place the passed matrix to the current Matrix.
  4852. * Returns the updated Matrix.
  4853. */
  4854. Matrix.prototype.addToSelf = function (other) {
  4855. for (var index = 0; index < 16; index++) {
  4856. this.m[index] += other.m[index];
  4857. }
  4858. this._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the passed matrix with the current inverted Matrix.
  4863. * Returns the unmodified current Matrix.
  4864. */
  4865. Matrix.prototype.invertToRef = function (other) {
  4866. var l1 = this.m[0];
  4867. var l2 = this.m[1];
  4868. var l3 = this.m[2];
  4869. var l4 = this.m[3];
  4870. var l5 = this.m[4];
  4871. var l6 = this.m[5];
  4872. var l7 = this.m[6];
  4873. var l8 = this.m[7];
  4874. var l9 = this.m[8];
  4875. var l10 = this.m[9];
  4876. var l11 = this.m[10];
  4877. var l12 = this.m[11];
  4878. var l13 = this.m[12];
  4879. var l14 = this.m[13];
  4880. var l15 = this.m[14];
  4881. var l16 = this.m[15];
  4882. var l17 = (l11 * l16) - (l12 * l15);
  4883. var l18 = (l10 * l16) - (l12 * l14);
  4884. var l19 = (l10 * l15) - (l11 * l14);
  4885. var l20 = (l9 * l16) - (l12 * l13);
  4886. var l21 = (l9 * l15) - (l11 * l13);
  4887. var l22 = (l9 * l14) - (l10 * l13);
  4888. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4889. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4890. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4891. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4892. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4893. var l28 = (l7 * l16) - (l8 * l15);
  4894. var l29 = (l6 * l16) - (l8 * l14);
  4895. var l30 = (l6 * l15) - (l7 * l14);
  4896. var l31 = (l5 * l16) - (l8 * l13);
  4897. var l32 = (l5 * l15) - (l7 * l13);
  4898. var l33 = (l5 * l14) - (l6 * l13);
  4899. var l34 = (l7 * l12) - (l8 * l11);
  4900. var l35 = (l6 * l12) - (l8 * l10);
  4901. var l36 = (l6 * l11) - (l7 * l10);
  4902. var l37 = (l5 * l12) - (l8 * l9);
  4903. var l38 = (l5 * l11) - (l7 * l9);
  4904. var l39 = (l5 * l10) - (l6 * l9);
  4905. other.m[0] = l23 * l27;
  4906. other.m[4] = l24 * l27;
  4907. other.m[8] = l25 * l27;
  4908. other.m[12] = l26 * l27;
  4909. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4910. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4911. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4912. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4913. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4914. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4915. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4916. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4917. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4918. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4919. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4920. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4921. other._markAsUpdated();
  4922. return this;
  4923. };
  4924. /**
  4925. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4926. * Returns the updated Matrix.
  4927. */
  4928. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4929. this.m[12] = x;
  4930. this.m[13] = y;
  4931. this.m[14] = z;
  4932. this._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Inserts the translation vector in the current Matrix.
  4937. * Returns the updated Matrix.
  4938. */
  4939. Matrix.prototype.setTranslation = function (vector3) {
  4940. this.m[12] = vector3.x;
  4941. this.m[13] = vector3.y;
  4942. this.m[14] = vector3.z;
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 as the extracted translation from the Matrix.
  4948. */
  4949. Matrix.prototype.getTranslation = function () {
  4950. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4951. };
  4952. /**
  4953. * Fill a Vector3 with the extracted translation from the Matrix.
  4954. */
  4955. Matrix.prototype.getTranslationToRef = function (result) {
  4956. result.x = this.m[12];
  4957. result.y = this.m[13];
  4958. result.z = this.m[14];
  4959. return this;
  4960. };
  4961. /**
  4962. * Remove rotation and scaling part from the Matrix.
  4963. * Returns the updated Matrix.
  4964. */
  4965. Matrix.prototype.removeRotationAndScaling = function () {
  4966. this.setRowFromFloats(0, 1, 0, 0, 0);
  4967. this.setRowFromFloats(1, 0, 1, 0, 0);
  4968. this.setRowFromFloats(2, 0, 0, 1, 0);
  4969. return this;
  4970. };
  4971. /**
  4972. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4973. */
  4974. Matrix.prototype.multiply = function (other) {
  4975. var result = new Matrix();
  4976. this.multiplyToRef(other, result);
  4977. return result;
  4978. };
  4979. /**
  4980. * Updates the current Matrix from the passed one values.
  4981. * Returns the updated Matrix.
  4982. */
  4983. Matrix.prototype.copyFrom = function (other) {
  4984. for (var index = 0; index < 16; index++) {
  4985. this.m[index] = other.m[index];
  4986. }
  4987. this._markAsUpdated();
  4988. return this;
  4989. };
  4990. /**
  4991. * Populates the passed array from the starting index with the Matrix values.
  4992. * Returns the Matrix.
  4993. */
  4994. Matrix.prototype.copyToArray = function (array, offset) {
  4995. if (offset === void 0) { offset = 0; }
  4996. for (var index = 0; index < 16; index++) {
  4997. array[offset + index] = this.m[index];
  4998. }
  4999. return this;
  5000. };
  5001. /**
  5002. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5003. */
  5004. Matrix.prototype.multiplyToRef = function (other, result) {
  5005. this.multiplyToArray(other, result.m, 0);
  5006. result._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5011. */
  5012. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5013. var tm0 = this.m[0];
  5014. var tm1 = this.m[1];
  5015. var tm2 = this.m[2];
  5016. var tm3 = this.m[3];
  5017. var tm4 = this.m[4];
  5018. var tm5 = this.m[5];
  5019. var tm6 = this.m[6];
  5020. var tm7 = this.m[7];
  5021. var tm8 = this.m[8];
  5022. var tm9 = this.m[9];
  5023. var tm10 = this.m[10];
  5024. var tm11 = this.m[11];
  5025. var tm12 = this.m[12];
  5026. var tm13 = this.m[13];
  5027. var tm14 = this.m[14];
  5028. var tm15 = this.m[15];
  5029. var om0 = other.m[0];
  5030. var om1 = other.m[1];
  5031. var om2 = other.m[2];
  5032. var om3 = other.m[3];
  5033. var om4 = other.m[4];
  5034. var om5 = other.m[5];
  5035. var om6 = other.m[6];
  5036. var om7 = other.m[7];
  5037. var om8 = other.m[8];
  5038. var om9 = other.m[9];
  5039. var om10 = other.m[10];
  5040. var om11 = other.m[11];
  5041. var om12 = other.m[12];
  5042. var om13 = other.m[13];
  5043. var om14 = other.m[14];
  5044. var om15 = other.m[15];
  5045. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5046. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5047. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5048. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5049. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5050. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5051. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5052. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5053. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5054. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5055. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5056. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5057. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5058. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5059. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5060. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5061. return this;
  5062. };
  5063. /**
  5064. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5065. */
  5066. Matrix.prototype.equals = function (value) {
  5067. return value &&
  5068. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5069. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5070. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5071. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5072. };
  5073. /**
  5074. * Returns a new Matrix from the current Matrix.
  5075. */
  5076. Matrix.prototype.clone = function () {
  5077. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5078. };
  5079. /**
  5080. * Returns the string "Matrix"
  5081. */
  5082. Matrix.prototype.getClassName = function () {
  5083. return "Matrix";
  5084. };
  5085. /**
  5086. * Returns the Matrix hash code.
  5087. */
  5088. Matrix.prototype.getHashCode = function () {
  5089. var hash = this.m[0] || 0;
  5090. for (var i = 1; i < 16; i++) {
  5091. hash = (hash * 397) ^ (this.m[i] || 0);
  5092. }
  5093. return hash;
  5094. };
  5095. /**
  5096. * Decomposes the current Matrix into :
  5097. * - a scale vector3 passed as a reference to update,
  5098. * - a rotation quaternion passed as a reference to update,
  5099. * - a translation vector3 passed as a reference to update.
  5100. * Returns the true if operation was successful.
  5101. */
  5102. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5103. translation.x = this.m[12];
  5104. translation.y = this.m[13];
  5105. translation.z = this.m[14];
  5106. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5107. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5108. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5109. if (this.determinant() <= 0) {
  5110. scale.y *= -1;
  5111. }
  5112. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5113. rotation.x = 0;
  5114. rotation.y = 0;
  5115. rotation.z = 0;
  5116. rotation.w = 1;
  5117. return false;
  5118. }
  5119. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5120. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5121. return true;
  5122. };
  5123. /**
  5124. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5125. * @param ref matrix to store the result
  5126. */
  5127. Matrix.prototype.toNormalMatrix = function (ref) {
  5128. this.invertToRef(ref);
  5129. ref.transpose();
  5130. var m = ref.m;
  5131. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5132. };
  5133. /**
  5134. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5135. */
  5136. Matrix.prototype.getRotationMatrix = function () {
  5137. var result = Matrix.Identity();
  5138. this.getRotationMatrixToRef(result);
  5139. return result;
  5140. };
  5141. /**
  5142. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5143. * Returns the current Matrix.
  5144. */
  5145. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5146. var m = this.m;
  5147. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5148. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5149. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5150. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5151. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5152. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5153. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5154. return this;
  5155. };
  5156. // Statics
  5157. /**
  5158. * Returns a new Matrix set from the starting index of the passed array.
  5159. */
  5160. Matrix.FromArray = function (array, offset) {
  5161. var result = new Matrix();
  5162. if (!offset) {
  5163. offset = 0;
  5164. }
  5165. Matrix.FromArrayToRef(array, offset, result);
  5166. return result;
  5167. };
  5168. /**
  5169. * Sets the passed "result" matrix from the starting index of the passed array.
  5170. */
  5171. Matrix.FromArrayToRef = function (array, offset, result) {
  5172. for (var index = 0; index < 16; index++) {
  5173. result.m[index] = array[index + offset];
  5174. }
  5175. result._markAsUpdated();
  5176. };
  5177. /**
  5178. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5179. */
  5180. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5181. for (var index = 0; index < 16; index++) {
  5182. result.m[index] = array[index + offset] * scale;
  5183. }
  5184. result._markAsUpdated();
  5185. };
  5186. /**
  5187. * Sets the passed matrix "result" with the 16 passed floats.
  5188. */
  5189. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5190. result.m[0] = initialM11;
  5191. result.m[1] = initialM12;
  5192. result.m[2] = initialM13;
  5193. result.m[3] = initialM14;
  5194. result.m[4] = initialM21;
  5195. result.m[5] = initialM22;
  5196. result.m[6] = initialM23;
  5197. result.m[7] = initialM24;
  5198. result.m[8] = initialM31;
  5199. result.m[9] = initialM32;
  5200. result.m[10] = initialM33;
  5201. result.m[11] = initialM34;
  5202. result.m[12] = initialM41;
  5203. result.m[13] = initialM42;
  5204. result.m[14] = initialM43;
  5205. result.m[15] = initialM44;
  5206. result._markAsUpdated();
  5207. };
  5208. /**
  5209. * Returns the index-th row of the current matrix as a new Vector4.
  5210. */
  5211. Matrix.prototype.getRow = function (index) {
  5212. if (index < 0 || index > 3) {
  5213. return null;
  5214. }
  5215. var i = index * 4;
  5216. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5217. };
  5218. /**
  5219. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5220. * Returns the updated Matrix.
  5221. */
  5222. Matrix.prototype.setRow = function (index, row) {
  5223. if (index < 0 || index > 3) {
  5224. return this;
  5225. }
  5226. var i = index * 4;
  5227. this.m[i + 0] = row.x;
  5228. this.m[i + 1] = row.y;
  5229. this.m[i + 2] = row.z;
  5230. this.m[i + 3] = row.w;
  5231. this._markAsUpdated();
  5232. return this;
  5233. };
  5234. /**
  5235. * Compute the transpose of the matrix.
  5236. * Returns a new Matrix.
  5237. */
  5238. Matrix.prototype.transpose = function () {
  5239. return Matrix.Transpose(this);
  5240. };
  5241. /**
  5242. * Compute the transpose of the matrix.
  5243. * Returns the current matrix.
  5244. */
  5245. Matrix.prototype.transposeToRef = function (result) {
  5246. Matrix.TransposeToRef(this, result);
  5247. return this;
  5248. };
  5249. /**
  5250. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5251. * Returns the updated Matrix.
  5252. */
  5253. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5254. if (index < 0 || index > 3) {
  5255. return this;
  5256. }
  5257. var i = index * 4;
  5258. this.m[i + 0] = x;
  5259. this.m[i + 1] = y;
  5260. this.m[i + 2] = z;
  5261. this.m[i + 3] = w;
  5262. this._markAsUpdated();
  5263. return this;
  5264. };
  5265. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5266. /**
  5267. * Static identity matrix to be used as readonly matrix
  5268. * Must not be updated.
  5269. */
  5270. get: function () {
  5271. return Matrix._identityReadOnly;
  5272. },
  5273. enumerable: true,
  5274. configurable: true
  5275. });
  5276. /**
  5277. * Returns a new Matrix set from the 16 passed floats.
  5278. */
  5279. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5280. var result = new Matrix();
  5281. result.m[0] = initialM11;
  5282. result.m[1] = initialM12;
  5283. result.m[2] = initialM13;
  5284. result.m[3] = initialM14;
  5285. result.m[4] = initialM21;
  5286. result.m[5] = initialM22;
  5287. result.m[6] = initialM23;
  5288. result.m[7] = initialM24;
  5289. result.m[8] = initialM31;
  5290. result.m[9] = initialM32;
  5291. result.m[10] = initialM33;
  5292. result.m[11] = initialM34;
  5293. result.m[12] = initialM41;
  5294. result.m[13] = initialM42;
  5295. result.m[14] = initialM43;
  5296. result.m[15] = initialM44;
  5297. return result;
  5298. };
  5299. /**
  5300. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5301. */
  5302. Matrix.Compose = function (scale, rotation, translation) {
  5303. var result = Matrix.Identity();
  5304. Matrix.ComposeToRef(scale, rotation, translation, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5309. */
  5310. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5311. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5312. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5313. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5314. result.setTranslation(translation);
  5315. };
  5316. /**
  5317. * Returns a new indentity Matrix.
  5318. */
  5319. Matrix.Identity = function () {
  5320. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5321. };
  5322. /**
  5323. * Sets the passed "result" as an identity matrix.
  5324. */
  5325. Matrix.IdentityToRef = function (result) {
  5326. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5327. };
  5328. /**
  5329. * Returns a new zero Matrix.
  5330. */
  5331. Matrix.Zero = function () {
  5332. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5333. };
  5334. /**
  5335. * Returns a new rotation matrix for "angle" radians around the X axis.
  5336. */
  5337. Matrix.RotationX = function (angle) {
  5338. var result = new Matrix();
  5339. Matrix.RotationXToRef(angle, result);
  5340. return result;
  5341. };
  5342. /**
  5343. * Returns a new Matrix as the passed inverted one.
  5344. */
  5345. Matrix.Invert = function (source) {
  5346. var result = new Matrix();
  5347. source.invertToRef(result);
  5348. return result;
  5349. };
  5350. /**
  5351. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5352. */
  5353. Matrix.RotationXToRef = function (angle, result) {
  5354. var s = Math.sin(angle);
  5355. var c = Math.cos(angle);
  5356. result.m[0] = 1.0;
  5357. result.m[15] = 1.0;
  5358. result.m[5] = c;
  5359. result.m[10] = c;
  5360. result.m[9] = -s;
  5361. result.m[6] = s;
  5362. result.m[1] = 0.0;
  5363. result.m[2] = 0.0;
  5364. result.m[3] = 0.0;
  5365. result.m[4] = 0.0;
  5366. result.m[7] = 0.0;
  5367. result.m[8] = 0.0;
  5368. result.m[11] = 0.0;
  5369. result.m[12] = 0.0;
  5370. result.m[13] = 0.0;
  5371. result.m[14] = 0.0;
  5372. result._markAsUpdated();
  5373. };
  5374. /**
  5375. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5376. */
  5377. Matrix.RotationY = function (angle) {
  5378. var result = new Matrix();
  5379. Matrix.RotationYToRef(angle, result);
  5380. return result;
  5381. };
  5382. /**
  5383. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5384. */
  5385. Matrix.RotationYToRef = function (angle, result) {
  5386. var s = Math.sin(angle);
  5387. var c = Math.cos(angle);
  5388. result.m[5] = 1.0;
  5389. result.m[15] = 1.0;
  5390. result.m[0] = c;
  5391. result.m[2] = -s;
  5392. result.m[8] = s;
  5393. result.m[10] = c;
  5394. result.m[1] = 0.0;
  5395. result.m[3] = 0.0;
  5396. result.m[4] = 0.0;
  5397. result.m[6] = 0.0;
  5398. result.m[7] = 0.0;
  5399. result.m[9] = 0.0;
  5400. result.m[11] = 0.0;
  5401. result.m[12] = 0.0;
  5402. result.m[13] = 0.0;
  5403. result.m[14] = 0.0;
  5404. result._markAsUpdated();
  5405. };
  5406. /**
  5407. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5408. */
  5409. Matrix.RotationZ = function (angle) {
  5410. var result = new Matrix();
  5411. Matrix.RotationZToRef(angle, result);
  5412. return result;
  5413. };
  5414. /**
  5415. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5416. */
  5417. Matrix.RotationZToRef = function (angle, result) {
  5418. var s = Math.sin(angle);
  5419. var c = Math.cos(angle);
  5420. result.m[10] = 1.0;
  5421. result.m[15] = 1.0;
  5422. result.m[0] = c;
  5423. result.m[1] = s;
  5424. result.m[4] = -s;
  5425. result.m[5] = c;
  5426. result.m[2] = 0.0;
  5427. result.m[3] = 0.0;
  5428. result.m[6] = 0.0;
  5429. result.m[7] = 0.0;
  5430. result.m[8] = 0.0;
  5431. result.m[9] = 0.0;
  5432. result.m[11] = 0.0;
  5433. result.m[12] = 0.0;
  5434. result.m[13] = 0.0;
  5435. result.m[14] = 0.0;
  5436. result._markAsUpdated();
  5437. };
  5438. /**
  5439. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5440. */
  5441. Matrix.RotationAxis = function (axis, angle) {
  5442. var result = Matrix.Zero();
  5443. Matrix.RotationAxisToRef(axis, angle, result);
  5444. return result;
  5445. };
  5446. /**
  5447. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5448. */
  5449. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5450. var s = Math.sin(-angle);
  5451. var c = Math.cos(-angle);
  5452. var c1 = 1 - c;
  5453. axis.normalize();
  5454. result.m[0] = (axis.x * axis.x) * c1 + c;
  5455. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5456. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5457. result.m[3] = 0.0;
  5458. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5459. result.m[5] = (axis.y * axis.y) * c1 + c;
  5460. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5461. result.m[7] = 0.0;
  5462. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5463. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5464. result.m[10] = (axis.z * axis.z) * c1 + c;
  5465. result.m[11] = 0.0;
  5466. result.m[15] = 1.0;
  5467. result._markAsUpdated();
  5468. };
  5469. /**
  5470. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5471. */
  5472. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5473. var result = new Matrix();
  5474. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5475. return result;
  5476. };
  5477. /**
  5478. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5479. */
  5480. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5481. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5482. this._tempQuaternion.toRotationMatrix(result);
  5483. };
  5484. /**
  5485. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5486. */
  5487. Matrix.Scaling = function (x, y, z) {
  5488. var result = Matrix.Zero();
  5489. Matrix.ScalingToRef(x, y, z, result);
  5490. return result;
  5491. };
  5492. /**
  5493. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5494. */
  5495. Matrix.ScalingToRef = function (x, y, z, result) {
  5496. result.m[0] = x;
  5497. result.m[1] = 0.0;
  5498. result.m[2] = 0.0;
  5499. result.m[3] = 0.0;
  5500. result.m[4] = 0.0;
  5501. result.m[5] = y;
  5502. result.m[6] = 0.0;
  5503. result.m[7] = 0.0;
  5504. result.m[8] = 0.0;
  5505. result.m[9] = 0.0;
  5506. result.m[10] = z;
  5507. result.m[11] = 0.0;
  5508. result.m[12] = 0.0;
  5509. result.m[13] = 0.0;
  5510. result.m[14] = 0.0;
  5511. result.m[15] = 1.0;
  5512. result._markAsUpdated();
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5516. */
  5517. Matrix.Translation = function (x, y, z) {
  5518. var result = Matrix.Identity();
  5519. Matrix.TranslationToRef(x, y, z, result);
  5520. return result;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5524. */
  5525. Matrix.TranslationToRef = function (x, y, z, result) {
  5526. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5527. };
  5528. /**
  5529. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5530. * @param startValue defines the start value
  5531. * @param endValue defines the end value
  5532. * @param gradient defines the gradient factor
  5533. * @returns the new matrix
  5534. */
  5535. Matrix.Lerp = function (startValue, endValue, gradient) {
  5536. var result = Matrix.Zero();
  5537. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5542. * @param startValue defines the start value
  5543. * @param endValue defines the end value
  5544. * @param gradient defines the gradient factor
  5545. * @param result defines the Matrix object where to store data
  5546. */
  5547. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5548. for (var index = 0; index < 16; index++) {
  5549. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5550. }
  5551. result._markAsUpdated();
  5552. };
  5553. /**
  5554. * Returns a new Matrix whose values are computed by :
  5555. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5556. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5557. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5558. */
  5559. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5560. var startScale = new Vector3(0, 0, 0);
  5561. var startRotation = new Quaternion();
  5562. var startTranslation = new Vector3(0, 0, 0);
  5563. startValue.decompose(startScale, startRotation, startTranslation);
  5564. var endScale = new Vector3(0, 0, 0);
  5565. var endRotation = new Quaternion();
  5566. var endTranslation = new Vector3(0, 0, 0);
  5567. endValue.decompose(endScale, endRotation, endTranslation);
  5568. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5569. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5570. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5571. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5572. };
  5573. /**
  5574. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5575. * This methods works for a Left-Handed system.
  5576. */
  5577. Matrix.LookAtLH = function (eye, target, up) {
  5578. var result = Matrix.Zero();
  5579. Matrix.LookAtLHToRef(eye, target, up, result);
  5580. return result;
  5581. };
  5582. /**
  5583. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5584. * This methods works for a Left-Handed system.
  5585. */
  5586. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5587. // Z axis
  5588. target.subtractToRef(eye, this._zAxis);
  5589. this._zAxis.normalize();
  5590. // X axis
  5591. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5592. if (this._xAxis.lengthSquared() === 0) {
  5593. this._xAxis.x = 1.0;
  5594. }
  5595. else {
  5596. this._xAxis.normalize();
  5597. }
  5598. // Y axis
  5599. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5600. this._yAxis.normalize();
  5601. // Eye angles
  5602. var ex = -Vector3.Dot(this._xAxis, eye);
  5603. var ey = -Vector3.Dot(this._yAxis, eye);
  5604. var ez = -Vector3.Dot(this._zAxis, eye);
  5605. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5606. };
  5607. /**
  5608. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5609. * This methods works for a Right-Handed system.
  5610. */
  5611. Matrix.LookAtRH = function (eye, target, up) {
  5612. var result = Matrix.Zero();
  5613. Matrix.LookAtRHToRef(eye, target, up, result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5618. * This methods works for a Left-Handed system.
  5619. */
  5620. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5621. // Z axis
  5622. eye.subtractToRef(target, this._zAxis);
  5623. this._zAxis.normalize();
  5624. // X axis
  5625. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5626. if (this._xAxis.lengthSquared() === 0) {
  5627. this._xAxis.x = 1.0;
  5628. }
  5629. else {
  5630. this._xAxis.normalize();
  5631. }
  5632. // Y axis
  5633. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5634. this._yAxis.normalize();
  5635. // Eye angles
  5636. var ex = -Vector3.Dot(this._xAxis, eye);
  5637. var ey = -Vector3.Dot(this._yAxis, eye);
  5638. var ez = -Vector3.Dot(this._zAxis, eye);
  5639. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5640. };
  5641. /**
  5642. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5643. */
  5644. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5645. var matrix = Matrix.Zero();
  5646. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5647. return matrix;
  5648. };
  5649. /**
  5650. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5651. */
  5652. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5653. var n = znear;
  5654. var f = zfar;
  5655. var a = 2.0 / width;
  5656. var b = 2.0 / height;
  5657. var c = 2.0 / (f - n);
  5658. var d = -(f + n) / (f - n);
  5659. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5660. };
  5661. /**
  5662. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5663. */
  5664. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5665. var matrix = Matrix.Zero();
  5666. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5667. return matrix;
  5668. };
  5669. /**
  5670. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5671. */
  5672. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5673. var n = znear;
  5674. var f = zfar;
  5675. var a = 2.0 / (right - left);
  5676. var b = 2.0 / (top - bottom);
  5677. var c = 2.0 / (f - n);
  5678. var d = -(f + n) / (f - n);
  5679. var i0 = (left + right) / (left - right);
  5680. var i1 = (top + bottom) / (bottom - top);
  5681. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5682. };
  5683. /**
  5684. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5685. */
  5686. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5687. var matrix = Matrix.Zero();
  5688. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5689. return matrix;
  5690. };
  5691. /**
  5692. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5693. */
  5694. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5695. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5696. result.m[10] *= -1.0;
  5697. };
  5698. /**
  5699. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5700. */
  5701. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5702. var matrix = Matrix.Zero();
  5703. var n = znear;
  5704. var f = zfar;
  5705. var a = 2.0 * n / width;
  5706. var b = 2.0 * n / height;
  5707. var c = (f + n) / (f - n);
  5708. var d = -2.0 * f * n / (f - n);
  5709. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5710. return matrix;
  5711. };
  5712. /**
  5713. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5714. */
  5715. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5716. var matrix = Matrix.Zero();
  5717. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5718. return matrix;
  5719. };
  5720. /**
  5721. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5722. */
  5723. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5724. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5725. var n = znear;
  5726. var f = zfar;
  5727. var t = 1.0 / (Math.tan(fov * 0.5));
  5728. var a = isVerticalFovFixed ? (t / aspect) : t;
  5729. var b = isVerticalFovFixed ? t : (t * aspect);
  5730. var c = (f + n) / (f - n);
  5731. var d = -2.0 * f * n / (f - n);
  5732. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5733. };
  5734. /**
  5735. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5736. */
  5737. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5738. var matrix = Matrix.Zero();
  5739. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5740. return matrix;
  5741. };
  5742. /**
  5743. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5744. */
  5745. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5746. //alternatively this could be expressed as:
  5747. // m = PerspectiveFovLHToRef
  5748. // m[10] *= -1.0;
  5749. // m[11] *= -1.0;
  5750. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5751. var n = znear;
  5752. var f = zfar;
  5753. var t = 1.0 / (Math.tan(fov * 0.5));
  5754. var a = isVerticalFovFixed ? (t / aspect) : t;
  5755. var b = isVerticalFovFixed ? t : (t * aspect);
  5756. var c = -(f + n) / (f - n);
  5757. var d = -2 * f * n / (f - n);
  5758. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5759. };
  5760. /**
  5761. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5762. */
  5763. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5764. if (rightHanded === void 0) { rightHanded = false; }
  5765. var rightHandedFactor = rightHanded ? -1 : 1;
  5766. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5767. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5768. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5769. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5770. var xScale = 2.0 / (leftTan + rightTan);
  5771. var yScale = 2.0 / (upTan + downTan);
  5772. result.m[0] = xScale;
  5773. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5774. result.m[5] = yScale;
  5775. result.m[6] = result.m[7] = 0.0;
  5776. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5777. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5778. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5779. result.m[10] = -zfar / (znear - zfar);
  5780. result.m[11] = 1.0 * rightHandedFactor;
  5781. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5782. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5783. // result.m[14] = (znear * zfar) / (znear - zfar);
  5784. result._markAsUpdated();
  5785. };
  5786. /**
  5787. * Returns the final transformation matrix : world * view * projection * viewport
  5788. */
  5789. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5790. var cw = viewport.width;
  5791. var ch = viewport.height;
  5792. var cx = viewport.x;
  5793. var cy = viewport.y;
  5794. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5795. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5796. };
  5797. /**
  5798. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5799. */
  5800. Matrix.GetAsMatrix2x2 = function (matrix) {
  5801. return new Float32Array([
  5802. matrix.m[0], matrix.m[1],
  5803. matrix.m[4], matrix.m[5]
  5804. ]);
  5805. };
  5806. /**
  5807. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5808. */
  5809. Matrix.GetAsMatrix3x3 = function (matrix) {
  5810. return new Float32Array([
  5811. matrix.m[0], matrix.m[1], matrix.m[2],
  5812. matrix.m[4], matrix.m[5], matrix.m[6],
  5813. matrix.m[8], matrix.m[9], matrix.m[10]
  5814. ]);
  5815. };
  5816. /**
  5817. * Compute the transpose of the passed Matrix.
  5818. * Returns a new Matrix.
  5819. */
  5820. Matrix.Transpose = function (matrix) {
  5821. var result = new Matrix();
  5822. Matrix.TransposeToRef(matrix, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5827. */
  5828. Matrix.TransposeToRef = function (matrix, result) {
  5829. result.m[0] = matrix.m[0];
  5830. result.m[1] = matrix.m[4];
  5831. result.m[2] = matrix.m[8];
  5832. result.m[3] = matrix.m[12];
  5833. result.m[4] = matrix.m[1];
  5834. result.m[5] = matrix.m[5];
  5835. result.m[6] = matrix.m[9];
  5836. result.m[7] = matrix.m[13];
  5837. result.m[8] = matrix.m[2];
  5838. result.m[9] = matrix.m[6];
  5839. result.m[10] = matrix.m[10];
  5840. result.m[11] = matrix.m[14];
  5841. result.m[12] = matrix.m[3];
  5842. result.m[13] = matrix.m[7];
  5843. result.m[14] = matrix.m[11];
  5844. result.m[15] = matrix.m[15];
  5845. };
  5846. /**
  5847. * Returns a new Matrix as the reflection matrix across the passed plane.
  5848. */
  5849. Matrix.Reflection = function (plane) {
  5850. var matrix = new Matrix();
  5851. Matrix.ReflectionToRef(plane, matrix);
  5852. return matrix;
  5853. };
  5854. /**
  5855. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5856. */
  5857. Matrix.ReflectionToRef = function (plane, result) {
  5858. plane.normalize();
  5859. var x = plane.normal.x;
  5860. var y = plane.normal.y;
  5861. var z = plane.normal.z;
  5862. var temp = -2 * x;
  5863. var temp2 = -2 * y;
  5864. var temp3 = -2 * z;
  5865. result.m[0] = (temp * x) + 1;
  5866. result.m[1] = temp2 * x;
  5867. result.m[2] = temp3 * x;
  5868. result.m[3] = 0.0;
  5869. result.m[4] = temp * y;
  5870. result.m[5] = (temp2 * y) + 1;
  5871. result.m[6] = temp3 * y;
  5872. result.m[7] = 0.0;
  5873. result.m[8] = temp * z;
  5874. result.m[9] = temp2 * z;
  5875. result.m[10] = (temp3 * z) + 1;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = temp * plane.d;
  5878. result.m[13] = temp2 * plane.d;
  5879. result.m[14] = temp3 * plane.d;
  5880. result.m[15] = 1.0;
  5881. result._markAsUpdated();
  5882. };
  5883. /**
  5884. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5885. */
  5886. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5887. result.m[0] = xaxis.x;
  5888. result.m[1] = xaxis.y;
  5889. result.m[2] = xaxis.z;
  5890. result.m[3] = 0.0;
  5891. result.m[4] = yaxis.x;
  5892. result.m[5] = yaxis.y;
  5893. result.m[6] = yaxis.z;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = zaxis.x;
  5896. result.m[9] = zaxis.y;
  5897. result.m[10] = zaxis.z;
  5898. result.m[11] = 0.0;
  5899. result.m[12] = 0.0;
  5900. result.m[13] = 0.0;
  5901. result.m[14] = 0.0;
  5902. result.m[15] = 1.0;
  5903. result._markAsUpdated();
  5904. };
  5905. /**
  5906. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5907. */
  5908. Matrix.FromQuaternionToRef = function (quat, result) {
  5909. var xx = quat.x * quat.x;
  5910. var yy = quat.y * quat.y;
  5911. var zz = quat.z * quat.z;
  5912. var xy = quat.x * quat.y;
  5913. var zw = quat.z * quat.w;
  5914. var zx = quat.z * quat.x;
  5915. var yw = quat.y * quat.w;
  5916. var yz = quat.y * quat.z;
  5917. var xw = quat.x * quat.w;
  5918. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5919. result.m[1] = 2.0 * (xy + zw);
  5920. result.m[2] = 2.0 * (zx - yw);
  5921. result.m[3] = 0.0;
  5922. result.m[4] = 2.0 * (xy - zw);
  5923. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5924. result.m[6] = 2.0 * (yz + xw);
  5925. result.m[7] = 0.0;
  5926. result.m[8] = 2.0 * (zx + yw);
  5927. result.m[9] = 2.0 * (yz - xw);
  5928. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5929. result.m[11] = 0.0;
  5930. result.m[12] = 0.0;
  5931. result.m[13] = 0.0;
  5932. result.m[14] = 0.0;
  5933. result.m[15] = 1.0;
  5934. result._markAsUpdated();
  5935. };
  5936. Matrix._tempQuaternion = new Quaternion();
  5937. Matrix._xAxis = Vector3.Zero();
  5938. Matrix._yAxis = Vector3.Zero();
  5939. Matrix._zAxis = Vector3.Zero();
  5940. Matrix._updateFlagSeed = 0;
  5941. Matrix._identityReadOnly = Matrix.Identity();
  5942. return Matrix;
  5943. }());
  5944. BABYLON.Matrix = Matrix;
  5945. var Plane = /** @class */ (function () {
  5946. /**
  5947. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5948. */
  5949. function Plane(a, b, c, d) {
  5950. this.normal = new Vector3(a, b, c);
  5951. this.d = d;
  5952. }
  5953. /**
  5954. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5955. */
  5956. Plane.prototype.asArray = function () {
  5957. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5958. };
  5959. // Methods
  5960. /**
  5961. * Returns a new plane copied from the current Plane.
  5962. */
  5963. Plane.prototype.clone = function () {
  5964. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5965. };
  5966. /**
  5967. * Returns the string "Plane".
  5968. */
  5969. Plane.prototype.getClassName = function () {
  5970. return "Plane";
  5971. };
  5972. /**
  5973. * Returns the Plane hash code.
  5974. */
  5975. Plane.prototype.getHashCode = function () {
  5976. var hash = this.normal.getHashCode();
  5977. hash = (hash * 397) ^ (this.d || 0);
  5978. return hash;
  5979. };
  5980. /**
  5981. * Normalize the current Plane in place.
  5982. * Returns the updated Plane.
  5983. */
  5984. Plane.prototype.normalize = function () {
  5985. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5986. var magnitude = 0.0;
  5987. if (norm !== 0) {
  5988. magnitude = 1.0 / norm;
  5989. }
  5990. this.normal.x *= magnitude;
  5991. this.normal.y *= magnitude;
  5992. this.normal.z *= magnitude;
  5993. this.d *= magnitude;
  5994. return this;
  5995. };
  5996. /**
  5997. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5998. */
  5999. Plane.prototype.transform = function (transformation) {
  6000. var transposedMatrix = Matrix.Transpose(transformation);
  6001. var x = this.normal.x;
  6002. var y = this.normal.y;
  6003. var z = this.normal.z;
  6004. var d = this.d;
  6005. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6006. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6007. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6008. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6009. return new Plane(normalX, normalY, normalZ, finalD);
  6010. };
  6011. /**
  6012. * Returns the dot product (float) of the point coordinates and the plane normal.
  6013. */
  6014. Plane.prototype.dotCoordinate = function (point) {
  6015. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6016. };
  6017. /**
  6018. * Updates the current Plane from the plane defined by the three passed points.
  6019. * Returns the updated Plane.
  6020. */
  6021. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6022. var x1 = point2.x - point1.x;
  6023. var y1 = point2.y - point1.y;
  6024. var z1 = point2.z - point1.z;
  6025. var x2 = point3.x - point1.x;
  6026. var y2 = point3.y - point1.y;
  6027. var z2 = point3.z - point1.z;
  6028. var yz = (y1 * z2) - (z1 * y2);
  6029. var xz = (z1 * x2) - (x1 * z2);
  6030. var xy = (x1 * y2) - (y1 * x2);
  6031. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6032. var invPyth;
  6033. if (pyth !== 0) {
  6034. invPyth = 1.0 / pyth;
  6035. }
  6036. else {
  6037. invPyth = 0.0;
  6038. }
  6039. this.normal.x = yz * invPyth;
  6040. this.normal.y = xz * invPyth;
  6041. this.normal.z = xy * invPyth;
  6042. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6043. return this;
  6044. };
  6045. /**
  6046. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6047. */
  6048. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6049. var dot = Vector3.Dot(this.normal, direction);
  6050. return (dot <= epsilon);
  6051. };
  6052. /**
  6053. * Returns the signed distance (float) from the passed point to the Plane.
  6054. */
  6055. Plane.prototype.signedDistanceTo = function (point) {
  6056. return Vector3.Dot(point, this.normal) + this.d;
  6057. };
  6058. // Statics
  6059. /**
  6060. * Returns a new Plane from the passed array.
  6061. */
  6062. Plane.FromArray = function (array) {
  6063. return new Plane(array[0], array[1], array[2], array[3]);
  6064. };
  6065. /**
  6066. * Returns a new Plane defined by the three passed points.
  6067. */
  6068. Plane.FromPoints = function (point1, point2, point3) {
  6069. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6070. result.copyFromPoints(point1, point2, point3);
  6071. return result;
  6072. };
  6073. /**
  6074. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6075. * Note : the vector "normal" is updated because normalized.
  6076. */
  6077. Plane.FromPositionAndNormal = function (origin, normal) {
  6078. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6079. normal.normalize();
  6080. result.normal = normal;
  6081. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6082. return result;
  6083. };
  6084. /**
  6085. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6086. */
  6087. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6088. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6089. return Vector3.Dot(point, normal) + d;
  6090. };
  6091. return Plane;
  6092. }());
  6093. BABYLON.Plane = Plane;
  6094. var Viewport = /** @class */ (function () {
  6095. /**
  6096. * Creates a Viewport object located at (x, y) and sized (width, height).
  6097. */
  6098. function Viewport(x, y, width, height) {
  6099. this.x = x;
  6100. this.y = y;
  6101. this.width = width;
  6102. this.height = height;
  6103. }
  6104. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6105. if (renderWidthOrEngine.getRenderWidth) {
  6106. var engine = renderWidthOrEngine;
  6107. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6108. }
  6109. var renderWidth = renderWidthOrEngine;
  6110. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6111. };
  6112. /**
  6113. * Returns a new Viewport copied from the current one.
  6114. */
  6115. Viewport.prototype.clone = function () {
  6116. return new Viewport(this.x, this.y, this.width, this.height);
  6117. };
  6118. return Viewport;
  6119. }());
  6120. BABYLON.Viewport = Viewport;
  6121. var Frustum = /** @class */ (function () {
  6122. function Frustum() {
  6123. }
  6124. /**
  6125. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6126. */
  6127. Frustum.GetPlanes = function (transform) {
  6128. var frustumPlanes = [];
  6129. for (var index = 0; index < 6; index++) {
  6130. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6131. }
  6132. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6133. return frustumPlanes;
  6134. };
  6135. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6136. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6137. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6138. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6139. frustumPlane.d = transform.m[15] + transform.m[14];
  6140. frustumPlane.normalize();
  6141. };
  6142. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6143. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6144. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6145. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6146. frustumPlane.d = transform.m[15] - transform.m[14];
  6147. frustumPlane.normalize();
  6148. };
  6149. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6150. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6151. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6152. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6153. frustumPlane.d = transform.m[15] + transform.m[12];
  6154. frustumPlane.normalize();
  6155. };
  6156. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6157. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6158. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6159. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6160. frustumPlane.d = transform.m[15] - transform.m[12];
  6161. frustumPlane.normalize();
  6162. };
  6163. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6164. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6165. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6166. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6167. frustumPlane.d = transform.m[15] - transform.m[13];
  6168. frustumPlane.normalize();
  6169. };
  6170. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6171. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6172. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6173. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6174. frustumPlane.d = transform.m[15] + transform.m[13];
  6175. frustumPlane.normalize();
  6176. };
  6177. /**
  6178. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6179. */
  6180. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6181. // Near
  6182. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6183. // Far
  6184. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6185. // Left
  6186. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6187. // Right
  6188. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6189. // Top
  6190. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6191. // Bottom
  6192. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6193. };
  6194. return Frustum;
  6195. }());
  6196. BABYLON.Frustum = Frustum;
  6197. var Space;
  6198. (function (Space) {
  6199. Space[Space["LOCAL"] = 0] = "LOCAL";
  6200. Space[Space["WORLD"] = 1] = "WORLD";
  6201. Space[Space["BONE"] = 2] = "BONE";
  6202. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6203. var Axis = /** @class */ (function () {
  6204. function Axis() {
  6205. }
  6206. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6207. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6208. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6209. return Axis;
  6210. }());
  6211. BABYLON.Axis = Axis;
  6212. ;
  6213. var BezierCurve = /** @class */ (function () {
  6214. function BezierCurve() {
  6215. }
  6216. /**
  6217. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6218. */
  6219. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6220. // Extract X (which is equal to time here)
  6221. var f0 = 1 - 3 * x2 + 3 * x1;
  6222. var f1 = 3 * x2 - 6 * x1;
  6223. var f2 = 3 * x1;
  6224. var refinedT = t;
  6225. for (var i = 0; i < 5; i++) {
  6226. var refinedT2 = refinedT * refinedT;
  6227. var refinedT3 = refinedT2 * refinedT;
  6228. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6229. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6230. refinedT -= (x - t) * slope;
  6231. refinedT = Math.min(1, Math.max(0, refinedT));
  6232. }
  6233. // Resolve cubic bezier for the given x
  6234. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6235. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6236. Math.pow(refinedT, 3);
  6237. };
  6238. return BezierCurve;
  6239. }());
  6240. BABYLON.BezierCurve = BezierCurve;
  6241. var Orientation;
  6242. (function (Orientation) {
  6243. Orientation[Orientation["CW"] = 0] = "CW";
  6244. Orientation[Orientation["CCW"] = 1] = "CCW";
  6245. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6246. var Angle = /** @class */ (function () {
  6247. /**
  6248. * Creates an Angle object of "radians" radians (float).
  6249. */
  6250. function Angle(radians) {
  6251. var _this = this;
  6252. /**
  6253. * Returns the Angle value in degrees (float).
  6254. */
  6255. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6256. /**
  6257. * Returns the Angle value in radians (float).
  6258. */
  6259. this.radians = function () { return _this._radians; };
  6260. this._radians = radians;
  6261. if (this._radians < 0.0)
  6262. this._radians += (2.0 * Math.PI);
  6263. }
  6264. /**
  6265. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6266. */
  6267. Angle.BetweenTwoPoints = function (a, b) {
  6268. var delta = b.subtract(a);
  6269. var theta = Math.atan2(delta.y, delta.x);
  6270. return new Angle(theta);
  6271. };
  6272. /**
  6273. * Returns a new Angle object from the passed float in radians.
  6274. */
  6275. Angle.FromRadians = function (radians) {
  6276. return new Angle(radians);
  6277. };
  6278. /**
  6279. * Returns a new Angle object from the passed float in degrees.
  6280. */
  6281. Angle.FromDegrees = function (degrees) {
  6282. return new Angle(degrees * Math.PI / 180.0);
  6283. };
  6284. return Angle;
  6285. }());
  6286. BABYLON.Angle = Angle;
  6287. var Arc2 = /** @class */ (function () {
  6288. /**
  6289. * Creates an Arc object from the three passed points : start, middle and end.
  6290. */
  6291. function Arc2(startPoint, midPoint, endPoint) {
  6292. this.startPoint = startPoint;
  6293. this.midPoint = midPoint;
  6294. this.endPoint = endPoint;
  6295. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6296. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6297. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6298. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6299. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6300. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6301. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6302. var a1 = this.startAngle.degrees();
  6303. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6304. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6305. // angles correction
  6306. if (a2 - a1 > +180.0)
  6307. a2 -= 360.0;
  6308. if (a2 - a1 < -180.0)
  6309. a2 += 360.0;
  6310. if (a3 - a2 > +180.0)
  6311. a3 -= 360.0;
  6312. if (a3 - a2 < -180.0)
  6313. a3 += 360.0;
  6314. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6315. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6316. }
  6317. return Arc2;
  6318. }());
  6319. BABYLON.Arc2 = Arc2;
  6320. var Path2 = /** @class */ (function () {
  6321. /**
  6322. * Creates a Path2 object from the starting 2D coordinates x and y.
  6323. */
  6324. function Path2(x, y) {
  6325. this._points = new Array();
  6326. this._length = 0.0;
  6327. this.closed = false;
  6328. this._points.push(new Vector2(x, y));
  6329. }
  6330. /**
  6331. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6332. * Returns the updated Path2.
  6333. */
  6334. Path2.prototype.addLineTo = function (x, y) {
  6335. if (this.closed) {
  6336. return this;
  6337. }
  6338. var newPoint = new Vector2(x, y);
  6339. var previousPoint = this._points[this._points.length - 1];
  6340. this._points.push(newPoint);
  6341. this._length += newPoint.subtract(previousPoint).length();
  6342. return this;
  6343. };
  6344. /**
  6345. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6346. * Returns the updated Path2.
  6347. */
  6348. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6349. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6350. if (this.closed) {
  6351. return this;
  6352. }
  6353. var startPoint = this._points[this._points.length - 1];
  6354. var midPoint = new Vector2(midX, midY);
  6355. var endPoint = new Vector2(endX, endY);
  6356. var arc = new Arc2(startPoint, midPoint, endPoint);
  6357. var increment = arc.angle.radians() / numberOfSegments;
  6358. if (arc.orientation === Orientation.CW)
  6359. increment *= -1;
  6360. var currentAngle = arc.startAngle.radians() + increment;
  6361. for (var i = 0; i < numberOfSegments; i++) {
  6362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6364. this.addLineTo(x, y);
  6365. currentAngle += increment;
  6366. }
  6367. return this;
  6368. };
  6369. /**
  6370. * Closes the Path2.
  6371. * Returns the Path2.
  6372. */
  6373. Path2.prototype.close = function () {
  6374. this.closed = true;
  6375. return this;
  6376. };
  6377. /**
  6378. * Returns the Path2 total length (float).
  6379. */
  6380. Path2.prototype.length = function () {
  6381. var result = this._length;
  6382. if (!this.closed) {
  6383. var lastPoint = this._points[this._points.length - 1];
  6384. var firstPoint = this._points[0];
  6385. result += (firstPoint.subtract(lastPoint).length());
  6386. }
  6387. return result;
  6388. };
  6389. /**
  6390. * Returns the Path2 internal array of points.
  6391. */
  6392. Path2.prototype.getPoints = function () {
  6393. return this._points;
  6394. };
  6395. /**
  6396. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6397. */
  6398. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6399. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6400. return Vector2.Zero();
  6401. }
  6402. var lengthPosition = normalizedLengthPosition * this.length();
  6403. var previousOffset = 0;
  6404. for (var i = 0; i < this._points.length; i++) {
  6405. var j = (i + 1) % this._points.length;
  6406. var a = this._points[i];
  6407. var b = this._points[j];
  6408. var bToA = b.subtract(a);
  6409. var nextOffset = (bToA.length() + previousOffset);
  6410. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6411. var dir = bToA.normalize();
  6412. var localOffset = lengthPosition - previousOffset;
  6413. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6414. }
  6415. previousOffset = nextOffset;
  6416. }
  6417. return Vector2.Zero();
  6418. };
  6419. /**
  6420. * Returns a new Path2 starting at the coordinates (x, y).
  6421. */
  6422. Path2.StartingAt = function (x, y) {
  6423. return new Path2(x, y);
  6424. };
  6425. return Path2;
  6426. }());
  6427. BABYLON.Path2 = Path2;
  6428. var Path3D = /** @class */ (function () {
  6429. /**
  6430. * new Path3D(path, normal, raw)
  6431. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6432. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6433. * path : an array of Vector3, the curve axis of the Path3D
  6434. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6435. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6436. */
  6437. function Path3D(path, firstNormal, raw) {
  6438. if (firstNormal === void 0) { firstNormal = null; }
  6439. this.path = path;
  6440. this._curve = new Array();
  6441. this._distances = new Array();
  6442. this._tangents = new Array();
  6443. this._normals = new Array();
  6444. this._binormals = new Array();
  6445. for (var p = 0; p < path.length; p++) {
  6446. this._curve[p] = path[p].clone(); // hard copy
  6447. }
  6448. this._raw = raw || false;
  6449. this._compute(firstNormal);
  6450. }
  6451. /**
  6452. * Returns the Path3D array of successive Vector3 designing its curve.
  6453. */
  6454. Path3D.prototype.getCurve = function () {
  6455. return this._curve;
  6456. };
  6457. /**
  6458. * Returns an array populated with tangent vectors on each Path3D curve point.
  6459. */
  6460. Path3D.prototype.getTangents = function () {
  6461. return this._tangents;
  6462. };
  6463. /**
  6464. * Returns an array populated with normal vectors on each Path3D curve point.
  6465. */
  6466. Path3D.prototype.getNormals = function () {
  6467. return this._normals;
  6468. };
  6469. /**
  6470. * Returns an array populated with binormal vectors on each Path3D curve point.
  6471. */
  6472. Path3D.prototype.getBinormals = function () {
  6473. return this._binormals;
  6474. };
  6475. /**
  6476. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6477. */
  6478. Path3D.prototype.getDistances = function () {
  6479. return this._distances;
  6480. };
  6481. /**
  6482. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6483. * Returns the same object updated.
  6484. */
  6485. Path3D.prototype.update = function (path, firstNormal) {
  6486. if (firstNormal === void 0) { firstNormal = null; }
  6487. for (var p = 0; p < path.length; p++) {
  6488. this._curve[p].x = path[p].x;
  6489. this._curve[p].y = path[p].y;
  6490. this._curve[p].z = path[p].z;
  6491. }
  6492. this._compute(firstNormal);
  6493. return this;
  6494. };
  6495. // private function compute() : computes tangents, normals and binormals
  6496. Path3D.prototype._compute = function (firstNormal) {
  6497. var l = this._curve.length;
  6498. // first and last tangents
  6499. this._tangents[0] = this._getFirstNonNullVector(0);
  6500. if (!this._raw) {
  6501. this._tangents[0].normalize();
  6502. }
  6503. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6504. if (!this._raw) {
  6505. this._tangents[l - 1].normalize();
  6506. }
  6507. // normals and binormals at first point : arbitrary vector with _normalVector()
  6508. var tg0 = this._tangents[0];
  6509. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6510. this._normals[0] = pp0;
  6511. if (!this._raw) {
  6512. this._normals[0].normalize();
  6513. }
  6514. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6515. if (!this._raw) {
  6516. this._binormals[0].normalize();
  6517. }
  6518. this._distances[0] = 0.0;
  6519. // normals and binormals : next points
  6520. var prev; // previous vector (segment)
  6521. var cur; // current vector (segment)
  6522. var curTang; // current tangent
  6523. // previous normal
  6524. var prevBinor; // previous binormal
  6525. for (var i = 1; i < l; i++) {
  6526. // tangents
  6527. prev = this._getLastNonNullVector(i);
  6528. if (i < l - 1) {
  6529. cur = this._getFirstNonNullVector(i);
  6530. this._tangents[i] = prev.add(cur);
  6531. this._tangents[i].normalize();
  6532. }
  6533. this._distances[i] = this._distances[i - 1] + prev.length();
  6534. // normals and binormals
  6535. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6536. curTang = this._tangents[i];
  6537. prevBinor = this._binormals[i - 1];
  6538. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6539. if (!this._raw) {
  6540. this._normals[i].normalize();
  6541. }
  6542. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6543. if (!this._raw) {
  6544. this._binormals[i].normalize();
  6545. }
  6546. }
  6547. };
  6548. // private function getFirstNonNullVector(index)
  6549. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6550. Path3D.prototype._getFirstNonNullVector = function (index) {
  6551. var i = 1;
  6552. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6553. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6554. i++;
  6555. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6556. }
  6557. return nNVector;
  6558. };
  6559. // private function getLastNonNullVector(index)
  6560. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6561. Path3D.prototype._getLastNonNullVector = function (index) {
  6562. var i = 1;
  6563. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6564. while (nLVector.length() === 0 && index > i + 1) {
  6565. i++;
  6566. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6567. }
  6568. return nLVector;
  6569. };
  6570. // private function normalVector(v0, vt, va) :
  6571. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6572. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6573. Path3D.prototype._normalVector = function (v0, vt, va) {
  6574. var normal0;
  6575. var tgl = vt.length();
  6576. if (tgl === 0.0) {
  6577. tgl = 1.0;
  6578. }
  6579. if (va === undefined || va === null) {
  6580. var point;
  6581. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6582. point = new Vector3(0.0, -1.0, 0.0);
  6583. }
  6584. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6585. point = new Vector3(1.0, 0.0, 0.0);
  6586. }
  6587. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6588. point = new Vector3(0.0, 0.0, 1.0);
  6589. }
  6590. else {
  6591. point = Vector3.Zero();
  6592. }
  6593. normal0 = Vector3.Cross(vt, point);
  6594. }
  6595. else {
  6596. normal0 = Vector3.Cross(vt, va);
  6597. Vector3.CrossToRef(normal0, vt, normal0);
  6598. }
  6599. normal0.normalize();
  6600. return normal0;
  6601. };
  6602. return Path3D;
  6603. }());
  6604. BABYLON.Path3D = Path3D;
  6605. var Curve3 = /** @class */ (function () {
  6606. /**
  6607. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6608. * A Curve3 is designed from a series of successive Vector3.
  6609. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6610. */
  6611. function Curve3(points) {
  6612. this._length = 0.0;
  6613. this._points = points;
  6614. this._length = this._computeLength(points);
  6615. }
  6616. /**
  6617. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6618. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6619. * @param v1 (Vector3) the control point
  6620. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6621. * @param nbPoints (integer) the wanted number of points in the curve
  6622. */
  6623. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6624. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6625. var bez = new Array();
  6626. var equation = function (t, val0, val1, val2) {
  6627. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6628. return res;
  6629. };
  6630. for (var i = 0; i <= nbPoints; i++) {
  6631. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6632. }
  6633. return new Curve3(bez);
  6634. };
  6635. /**
  6636. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6637. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6638. * @param v1 (Vector3) the first control point
  6639. * @param v2 (Vector3) the second control point
  6640. * @param v3 (Vector3) the end point of the Cubic Bezier
  6641. * @param nbPoints (integer) the wanted number of points in the curve
  6642. */
  6643. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6644. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6645. var bez = new Array();
  6646. var equation = function (t, val0, val1, val2, val3) {
  6647. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6648. return res;
  6649. };
  6650. for (var i = 0; i <= nbPoints; i++) {
  6651. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6652. }
  6653. return new Curve3(bez);
  6654. };
  6655. /**
  6656. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6657. * @param p1 (Vector3) the origin point of the Hermite Spline
  6658. * @param t1 (Vector3) the tangent vector at the origin point
  6659. * @param p2 (Vector3) the end point of the Hermite Spline
  6660. * @param t2 (Vector3) the tangent vector at the end point
  6661. * @param nbPoints (integer) the wanted number of points in the curve
  6662. */
  6663. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6664. var hermite = new Array();
  6665. var step = 1.0 / nbPoints;
  6666. for (var i = 0; i <= nbPoints; i++) {
  6667. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6668. }
  6669. return new Curve3(hermite);
  6670. };
  6671. /**
  6672. * Returns a Curve3 object along a CatmullRom Spline curve :
  6673. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6674. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6675. */
  6676. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6677. var totalPoints = new Array();
  6678. totalPoints.push(points[0].clone());
  6679. Array.prototype.push.apply(totalPoints, points);
  6680. totalPoints.push(points[points.length - 1].clone());
  6681. var catmullRom = new Array();
  6682. var step = 1.0 / nbPoints;
  6683. var amount = 0.0;
  6684. for (var i = 0; i < totalPoints.length - 3; i++) {
  6685. amount = 0;
  6686. for (var c = 0; c < nbPoints; c++) {
  6687. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6688. amount += step;
  6689. }
  6690. }
  6691. i--;
  6692. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6693. return new Curve3(catmullRom);
  6694. };
  6695. /**
  6696. * Returns the Curve3 stored array of successive Vector3
  6697. */
  6698. Curve3.prototype.getPoints = function () {
  6699. return this._points;
  6700. };
  6701. /**
  6702. * Returns the computed length (float) of the curve.
  6703. */
  6704. Curve3.prototype.length = function () {
  6705. return this._length;
  6706. };
  6707. /**
  6708. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6709. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6710. * curveA and curveB keep unchanged.
  6711. */
  6712. Curve3.prototype.continue = function (curve) {
  6713. var lastPoint = this._points[this._points.length - 1];
  6714. var continuedPoints = this._points.slice();
  6715. var curvePoints = curve.getPoints();
  6716. for (var i = 1; i < curvePoints.length; i++) {
  6717. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6718. }
  6719. var continuedCurve = new Curve3(continuedPoints);
  6720. return continuedCurve;
  6721. };
  6722. Curve3.prototype._computeLength = function (path) {
  6723. var l = 0;
  6724. for (var i = 1; i < path.length; i++) {
  6725. l += (path[i].subtract(path[i - 1])).length();
  6726. }
  6727. return l;
  6728. };
  6729. return Curve3;
  6730. }());
  6731. BABYLON.Curve3 = Curve3;
  6732. // Vertex formats
  6733. var PositionNormalVertex = /** @class */ (function () {
  6734. function PositionNormalVertex(position, normal) {
  6735. if (position === void 0) { position = Vector3.Zero(); }
  6736. if (normal === void 0) { normal = Vector3.Up(); }
  6737. this.position = position;
  6738. this.normal = normal;
  6739. }
  6740. PositionNormalVertex.prototype.clone = function () {
  6741. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6742. };
  6743. return PositionNormalVertex;
  6744. }());
  6745. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6746. var PositionNormalTextureVertex = /** @class */ (function () {
  6747. function PositionNormalTextureVertex(position, normal, uv) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. if (uv === void 0) { uv = Vector2.Zero(); }
  6751. this.position = position;
  6752. this.normal = normal;
  6753. this.uv = uv;
  6754. }
  6755. PositionNormalTextureVertex.prototype.clone = function () {
  6756. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6757. };
  6758. return PositionNormalTextureVertex;
  6759. }());
  6760. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6761. // Temporary pre-allocated objects for engine internal use
  6762. // usage in any internal function :
  6763. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6764. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6765. var Tmp = /** @class */ (function () {
  6766. function Tmp() {
  6767. }
  6768. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6769. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6770. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6771. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6772. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6773. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6774. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6775. Matrix.Zero(), Matrix.Zero(),
  6776. Matrix.Zero(), Matrix.Zero(),
  6777. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6778. return Tmp;
  6779. }());
  6780. BABYLON.Tmp = Tmp;
  6781. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6782. var MathTmp = /** @class */ (function () {
  6783. function MathTmp() {
  6784. }
  6785. MathTmp.Vector3 = [Vector3.Zero()];
  6786. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6787. MathTmp.Quaternion = [Quaternion.Zero()];
  6788. return MathTmp;
  6789. }());
  6790. })(BABYLON || (BABYLON = {}));
  6791. //# sourceMappingURL=babylon.math.js.map
  6792. var BABYLON;
  6793. (function (BABYLON) {
  6794. var Scalar = /** @class */ (function () {
  6795. function Scalar() {
  6796. }
  6797. /**
  6798. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6799. */
  6800. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6801. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6802. var num = a - b;
  6803. return -epsilon <= num && num <= epsilon;
  6804. };
  6805. /**
  6806. * Returns a string : the upper case translation of the number i to hexadecimal.
  6807. */
  6808. Scalar.ToHex = function (i) {
  6809. var str = i.toString(16);
  6810. if (i <= 15) {
  6811. return ("0" + str).toUpperCase();
  6812. }
  6813. return str.toUpperCase();
  6814. };
  6815. /**
  6816. * Returns -1 if value is negative and +1 is value is positive.
  6817. * Returns the value itself if it's equal to zero.
  6818. */
  6819. Scalar.Sign = function (value) {
  6820. value = +value; // convert to a number
  6821. if (value === 0 || isNaN(value))
  6822. return value;
  6823. return value > 0 ? 1 : -1;
  6824. };
  6825. /**
  6826. * Returns the value itself if it's between min and max.
  6827. * Returns min if the value is lower than min.
  6828. * Returns max if the value is greater than max.
  6829. */
  6830. Scalar.Clamp = function (value, min, max) {
  6831. if (min === void 0) { min = 0; }
  6832. if (max === void 0) { max = 1; }
  6833. return Math.min(max, Math.max(min, value));
  6834. };
  6835. /**
  6836. * Returns the log2 of value.
  6837. */
  6838. Scalar.Log2 = function (value) {
  6839. return Math.log(value) * Math.LOG2E;
  6840. };
  6841. /**
  6842. * Loops the value, so that it is never larger than length and never smaller than 0.
  6843. *
  6844. * This is similar to the modulo operator but it works with floating point numbers.
  6845. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6846. * With t = 5 and length = 2.5, the result would be 0.0.
  6847. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6848. */
  6849. Scalar.Repeat = function (value, length) {
  6850. return value - Math.floor(value / length) * length;
  6851. };
  6852. /**
  6853. * Normalize the value between 0.0 and 1.0 using min and max values
  6854. */
  6855. Scalar.Normalize = function (value, min, max) {
  6856. return (value - min) / (max - min);
  6857. };
  6858. /**
  6859. * Denormalize the value from 0.0 and 1.0 using min and max values
  6860. */
  6861. Scalar.Denormalize = function (normalized, min, max) {
  6862. return (normalized * (max - min) + min);
  6863. };
  6864. /**
  6865. * Calculates the shortest difference between two given angles given in degrees.
  6866. */
  6867. Scalar.DeltaAngle = function (current, target) {
  6868. var num = Scalar.Repeat(target - current, 360.0);
  6869. if (num > 180.0) {
  6870. num -= 360.0;
  6871. }
  6872. return num;
  6873. };
  6874. /**
  6875. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6876. *
  6877. * The returned value will move back and forth between 0 and length
  6878. */
  6879. Scalar.PingPong = function (tx, length) {
  6880. var t = Scalar.Repeat(tx, length * 2.0);
  6881. return length - Math.abs(t - length);
  6882. };
  6883. /**
  6884. * Interpolates between min and max with smoothing at the limits.
  6885. *
  6886. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6887. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6888. */
  6889. Scalar.SmoothStep = function (from, to, tx) {
  6890. var t = Scalar.Clamp(tx);
  6891. t = -2.0 * t * t * t + 3.0 * t * t;
  6892. return to * t + from * (1.0 - t);
  6893. };
  6894. /**
  6895. * Moves a value current towards target.
  6896. *
  6897. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6898. * Negative values of maxDelta pushes the value away from target.
  6899. */
  6900. Scalar.MoveTowards = function (current, target, maxDelta) {
  6901. var result = 0;
  6902. if (Math.abs(target - current) <= maxDelta) {
  6903. result = target;
  6904. }
  6905. else {
  6906. result = current + Scalar.Sign(target - current) * maxDelta;
  6907. }
  6908. return result;
  6909. };
  6910. /**
  6911. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6912. *
  6913. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6914. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6915. */
  6916. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6917. var num = Scalar.DeltaAngle(current, target);
  6918. var result = 0;
  6919. if (-maxDelta < num && num < maxDelta) {
  6920. result = target;
  6921. }
  6922. else {
  6923. target = current + num;
  6924. result = Scalar.MoveTowards(current, target, maxDelta);
  6925. }
  6926. return result;
  6927. };
  6928. /**
  6929. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6930. */
  6931. Scalar.Lerp = function (start, end, amount) {
  6932. return start + ((end - start) * amount);
  6933. };
  6934. /**
  6935. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6936. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6937. */
  6938. Scalar.LerpAngle = function (start, end, amount) {
  6939. var num = Scalar.Repeat(end - start, 360.0);
  6940. if (num > 180.0) {
  6941. num -= 360.0;
  6942. }
  6943. return start + num * Scalar.Clamp(amount);
  6944. };
  6945. /**
  6946. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6947. */
  6948. Scalar.InverseLerp = function (a, b, value) {
  6949. var result = 0;
  6950. if (a != b) {
  6951. result = Scalar.Clamp((value - a) / (b - a));
  6952. }
  6953. else {
  6954. result = 0.0;
  6955. }
  6956. return result;
  6957. };
  6958. /**
  6959. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6960. */
  6961. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6962. var squared = amount * amount;
  6963. var cubed = amount * squared;
  6964. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6965. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6966. var part3 = (cubed - (2.0 * squared)) + amount;
  6967. var part4 = cubed - squared;
  6968. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6969. };
  6970. /**
  6971. * Returns a random float number between and min and max values
  6972. */
  6973. Scalar.RandomRange = function (min, max) {
  6974. if (min === max)
  6975. return min;
  6976. return ((Math.random() * (max - min)) + min);
  6977. };
  6978. /**
  6979. * This function returns percentage of a number in a given range.
  6980. *
  6981. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6982. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6983. */
  6984. Scalar.RangeToPercent = function (number, min, max) {
  6985. return ((number - min) / (max - min));
  6986. };
  6987. /**
  6988. * This function returns number that corresponds to the percentage in a given range.
  6989. *
  6990. * PercentToRange(0.34,0,100) will return 34.
  6991. */
  6992. Scalar.PercentToRange = function (percent, min, max) {
  6993. return ((max - min) * percent + min);
  6994. };
  6995. /**
  6996. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6997. * @param angle The angle to normalize in radian.
  6998. * @return The converted angle.
  6999. */
  7000. Scalar.NormalizeRadians = function (angle) {
  7001. // More precise but slower version kept for reference.
  7002. // angle = angle % Tools.TwoPi;
  7003. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7004. //if (angle > Math.PI) {
  7005. // angle -= Tools.TwoPi;
  7006. //}
  7007. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7008. return angle;
  7009. };
  7010. /**
  7011. * Two pi constants convenient for computation.
  7012. */
  7013. Scalar.TwoPi = Math.PI * 2;
  7014. return Scalar;
  7015. }());
  7016. BABYLON.Scalar = Scalar;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.math.scalar.js.map
  7019. //# sourceMappingURL=babylon.mixins.js.map
  7020. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7021. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7022. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7023. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7024. //# sourceMappingURL=babylon.webgl2.js.map
  7025. var BABYLON;
  7026. (function (BABYLON) {
  7027. var __decoratorInitialStore = {};
  7028. var __mergedStore = {};
  7029. var _copySource = function (creationFunction, source, instanciate) {
  7030. var destination = creationFunction();
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7034. }
  7035. var classStore = getMergedStore(destination);
  7036. // Properties
  7037. for (var property in classStore) {
  7038. var propertyDescriptor = classStore[property];
  7039. var sourceProperty = source[property];
  7040. var propertyType = propertyDescriptor.type;
  7041. if (sourceProperty !== undefined && sourceProperty !== null) {
  7042. switch (propertyType) {
  7043. case 0: // Value
  7044. case 6:// Mesh reference
  7045. destination[property] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7049. break;
  7050. case 2: // Color3
  7051. case 3: // FresnelParameters
  7052. case 4: // Vector2
  7053. case 5: // Vector3
  7054. case 7: // Color Curves
  7055. case 10:// Quaternion
  7056. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7057. break;
  7058. }
  7059. }
  7060. }
  7061. return destination;
  7062. };
  7063. function getDirectStore(target) {
  7064. var classKey = target.getClassName();
  7065. if (!__decoratorInitialStore[classKey]) {
  7066. __decoratorInitialStore[classKey] = {};
  7067. }
  7068. return __decoratorInitialStore[classKey];
  7069. }
  7070. /**
  7071. * Return the list of properties flagged as serializable
  7072. * @param target: host object
  7073. */
  7074. function getMergedStore(target) {
  7075. var classKey = target.getClassName();
  7076. if (__mergedStore[classKey]) {
  7077. return __mergedStore[classKey];
  7078. }
  7079. __mergedStore[classKey] = {};
  7080. var store = __mergedStore[classKey];
  7081. var currentTarget = target;
  7082. var currentKey = classKey;
  7083. while (currentKey) {
  7084. var initialStore = __decoratorInitialStore[currentKey];
  7085. for (var property in initialStore) {
  7086. store[property] = initialStore[property];
  7087. }
  7088. var parent_1 = void 0;
  7089. var done = false;
  7090. do {
  7091. parent_1 = Object.getPrototypeOf(currentTarget);
  7092. if (!parent_1.getClassName) {
  7093. done = true;
  7094. break;
  7095. }
  7096. if (parent_1.getClassName() !== currentKey) {
  7097. break;
  7098. }
  7099. currentTarget = parent_1;
  7100. } while (parent_1);
  7101. if (done) {
  7102. break;
  7103. }
  7104. currentKey = parent_1.getClassName();
  7105. currentTarget = parent_1;
  7106. }
  7107. return store;
  7108. }
  7109. function generateSerializableMember(type, sourceName) {
  7110. return function (target, propertyKey) {
  7111. var classStore = getDirectStore(target);
  7112. if (!classStore[propertyKey]) {
  7113. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7114. }
  7115. };
  7116. }
  7117. function generateExpandMember(setCallback, targetKey) {
  7118. if (targetKey === void 0) { targetKey = null; }
  7119. return function (target, propertyKey) {
  7120. var key = targetKey || ("_" + propertyKey);
  7121. Object.defineProperty(target, propertyKey, {
  7122. get: function () {
  7123. return this[key];
  7124. },
  7125. set: function (value) {
  7126. if (this[key] === value) {
  7127. return;
  7128. }
  7129. this[key] = value;
  7130. target[setCallback].apply(this);
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. };
  7136. }
  7137. function expandToProperty(callback, targetKey) {
  7138. if (targetKey === void 0) { targetKey = null; }
  7139. return generateExpandMember(callback, targetKey);
  7140. }
  7141. BABYLON.expandToProperty = expandToProperty;
  7142. function serialize(sourceName) {
  7143. return generateSerializableMember(0, sourceName); // value member
  7144. }
  7145. BABYLON.serialize = serialize;
  7146. function serializeAsTexture(sourceName) {
  7147. return generateSerializableMember(1, sourceName); // texture member
  7148. }
  7149. BABYLON.serializeAsTexture = serializeAsTexture;
  7150. function serializeAsColor3(sourceName) {
  7151. return generateSerializableMember(2, sourceName); // color3 member
  7152. }
  7153. BABYLON.serializeAsColor3 = serializeAsColor3;
  7154. function serializeAsFresnelParameters(sourceName) {
  7155. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7156. }
  7157. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7158. function serializeAsVector2(sourceName) {
  7159. return generateSerializableMember(4, sourceName); // vector2 member
  7160. }
  7161. BABYLON.serializeAsVector2 = serializeAsVector2;
  7162. function serializeAsVector3(sourceName) {
  7163. return generateSerializableMember(5, sourceName); // vector3 member
  7164. }
  7165. BABYLON.serializeAsVector3 = serializeAsVector3;
  7166. function serializeAsMeshReference(sourceName) {
  7167. return generateSerializableMember(6, sourceName); // mesh reference member
  7168. }
  7169. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7170. function serializeAsColorCurves(sourceName) {
  7171. return generateSerializableMember(7, sourceName); // color curves
  7172. }
  7173. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7174. function serializeAsColor4(sourceName) {
  7175. return generateSerializableMember(8, sourceName); // color 4
  7176. }
  7177. BABYLON.serializeAsColor4 = serializeAsColor4;
  7178. function serializeAsImageProcessingConfiguration(sourceName) {
  7179. return generateSerializableMember(9, sourceName); // image processing
  7180. }
  7181. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7182. function serializeAsQuaternion(sourceName) {
  7183. return generateSerializableMember(10, sourceName); // quaternion member
  7184. }
  7185. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7186. var SerializationHelper = /** @class */ (function () {
  7187. function SerializationHelper() {
  7188. }
  7189. SerializationHelper.Serialize = function (entity, serializationObject) {
  7190. if (!serializationObject) {
  7191. serializationObject = {};
  7192. }
  7193. // Tags
  7194. if (BABYLON.Tags) {
  7195. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7196. }
  7197. var serializedProperties = getMergedStore(entity);
  7198. // Properties
  7199. for (var property in serializedProperties) {
  7200. var propertyDescriptor = serializedProperties[property];
  7201. var targetPropertyName = propertyDescriptor.sourceName || property;
  7202. var propertyType = propertyDescriptor.type;
  7203. var sourceProperty = entity[property];
  7204. if (sourceProperty !== undefined && sourceProperty !== null) {
  7205. switch (propertyType) {
  7206. case 0:// Value
  7207. serializationObject[targetPropertyName] = sourceProperty;
  7208. break;
  7209. case 1:// Texture
  7210. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7211. break;
  7212. case 2:// Color3
  7213. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7214. break;
  7215. case 3:// FresnelParameters
  7216. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7217. break;
  7218. case 4:// Vector2
  7219. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7220. break;
  7221. case 5:// Vector3
  7222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7223. break;
  7224. case 6:// Mesh reference
  7225. serializationObject[targetPropertyName] = sourceProperty.id;
  7226. break;
  7227. case 7:// Color Curves
  7228. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7229. break;
  7230. case 8:// Color 4
  7231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7232. break;
  7233. case 9:// Image Processing
  7234. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7235. break;
  7236. }
  7237. }
  7238. }
  7239. return serializationObject;
  7240. };
  7241. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7242. if (rootUrl === void 0) { rootUrl = null; }
  7243. var destination = creationFunction();
  7244. if (!rootUrl) {
  7245. rootUrl = "";
  7246. }
  7247. // Tags
  7248. if (BABYLON.Tags) {
  7249. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7250. }
  7251. var classStore = getMergedStore(destination);
  7252. // Properties
  7253. for (var property in classStore) {
  7254. var propertyDescriptor = classStore[property];
  7255. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7256. var propertyType = propertyDescriptor.type;
  7257. if (sourceProperty !== undefined && sourceProperty !== null) {
  7258. var dest = destination;
  7259. switch (propertyType) {
  7260. case 0:// Value
  7261. dest[property] = sourceProperty;
  7262. break;
  7263. case 1:// Texture
  7264. if (scene) {
  7265. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7266. }
  7267. break;
  7268. case 2:// Color3
  7269. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7270. break;
  7271. case 3:// FresnelParameters
  7272. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7273. break;
  7274. case 4:// Vector2
  7275. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7276. break;
  7277. case 5:// Vector3
  7278. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7279. break;
  7280. case 6:// Mesh reference
  7281. if (scene) {
  7282. dest[property] = scene.getLastMeshByID(sourceProperty);
  7283. }
  7284. break;
  7285. case 7:// Color Curves
  7286. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7287. break;
  7288. case 8:// Color 4
  7289. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7290. break;
  7291. case 9:// Image Processing
  7292. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7293. break;
  7294. }
  7295. }
  7296. }
  7297. return destination;
  7298. };
  7299. SerializationHelper.Clone = function (creationFunction, source) {
  7300. return _copySource(creationFunction, source, false);
  7301. };
  7302. SerializationHelper.Instanciate = function (creationFunction, source) {
  7303. return _copySource(creationFunction, source, true);
  7304. };
  7305. return SerializationHelper;
  7306. }());
  7307. BABYLON.SerializationHelper = SerializationHelper;
  7308. })(BABYLON || (BABYLON = {}));
  7309. //# sourceMappingURL=babylon.decorators.js.map
  7310. var BABYLON;
  7311. (function (BABYLON) {
  7312. /**
  7313. * Wrapper class for promise with external resolve and reject.
  7314. */
  7315. var Deferred = /** @class */ (function () {
  7316. /**
  7317. * Constructor for this deferred object.
  7318. */
  7319. function Deferred() {
  7320. var _this = this;
  7321. this.promise = new Promise(function (resolve, reject) {
  7322. _this._resolve = resolve;
  7323. _this._reject = reject;
  7324. });
  7325. }
  7326. Object.defineProperty(Deferred.prototype, "resolve", {
  7327. /**
  7328. * The resolve method of the promise associated with this deferred object.
  7329. */
  7330. get: function () {
  7331. return this._resolve;
  7332. },
  7333. enumerable: true,
  7334. configurable: true
  7335. });
  7336. Object.defineProperty(Deferred.prototype, "reject", {
  7337. /**
  7338. * The reject method of the promise associated with this deferred object.
  7339. */
  7340. get: function () {
  7341. return this._reject;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. return Deferred;
  7347. }());
  7348. BABYLON.Deferred = Deferred;
  7349. })(BABYLON || (BABYLON = {}));
  7350. //# sourceMappingURL=babylon.deferred.js.map
  7351. var BABYLON;
  7352. (function (BABYLON) {
  7353. /**
  7354. * A class serves as a medium between the observable and its observers
  7355. */
  7356. var EventState = /** @class */ (function () {
  7357. /**
  7358. * Create a new EventState
  7359. * @param mask defines the mask associated with this state
  7360. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7361. * @param target defines the original target of the state
  7362. * @param currentTarget defines the current target of the state
  7363. */
  7364. function EventState(mask, skipNextObservers, target, currentTarget) {
  7365. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7366. this.initalize(mask, skipNextObservers, target, currentTarget);
  7367. }
  7368. /**
  7369. * Initialize the current event state
  7370. * @param mask defines the mask associated with this state
  7371. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7372. * @param target defines the original target of the state
  7373. * @param currentTarget defines the current target of the state
  7374. * @returns the current event state
  7375. */
  7376. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7377. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7378. this.mask = mask;
  7379. this.skipNextObservers = skipNextObservers;
  7380. this.target = target;
  7381. this.currentTarget = currentTarget;
  7382. return this;
  7383. };
  7384. return EventState;
  7385. }());
  7386. BABYLON.EventState = EventState;
  7387. /**
  7388. * Represent an Observer registered to a given Observable object.
  7389. */
  7390. var Observer = /** @class */ (function () {
  7391. /**
  7392. * Creates a new observer
  7393. * @param callback defines the callback to call when the observer is notified
  7394. * @param mask defines the mask of the observer (used to filter notifications)
  7395. * @param scope defines the current scope used to restore the JS context
  7396. */
  7397. function Observer(
  7398. /**
  7399. * Defines the callback to call when the observer is notified
  7400. */
  7401. callback,
  7402. /**
  7403. * Defines the mask of the observer (used to filter notifications)
  7404. */
  7405. mask,
  7406. /**
  7407. * Defines the current scope used to restore the JS context
  7408. */
  7409. scope) {
  7410. if (scope === void 0) { scope = null; }
  7411. this.callback = callback;
  7412. this.mask = mask;
  7413. this.scope = scope;
  7414. /** @ignore */
  7415. this._willBeUnregistered = false;
  7416. /**
  7417. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7418. */
  7419. this.unregisterOnNextCall = false;
  7420. }
  7421. return Observer;
  7422. }());
  7423. BABYLON.Observer = Observer;
  7424. /**
  7425. * Represent a list of observers registered to multiple Observables object.
  7426. */
  7427. var MultiObserver = /** @class */ (function () {
  7428. function MultiObserver() {
  7429. }
  7430. /**
  7431. * Release associated resources
  7432. */
  7433. MultiObserver.prototype.dispose = function () {
  7434. if (this._observers && this._observables) {
  7435. for (var index = 0; index < this._observers.length; index++) {
  7436. this._observables[index].remove(this._observers[index]);
  7437. }
  7438. }
  7439. this._observers = null;
  7440. this._observables = null;
  7441. };
  7442. /**
  7443. * Raise a callback when one of the observable will notify
  7444. * @param observables defines a list of observables to watch
  7445. * @param callback defines the callback to call on notification
  7446. * @param mask defines the mask used to filter notifications
  7447. * @param scope defines the current scope used to restore the JS context
  7448. * @returns the new MultiObserver
  7449. */
  7450. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7451. if (mask === void 0) { mask = -1; }
  7452. if (scope === void 0) { scope = null; }
  7453. var result = new MultiObserver();
  7454. result._observers = new Array();
  7455. result._observables = observables;
  7456. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7457. var observable = observables_1[_i];
  7458. var observer = observable.add(callback, mask, false, scope);
  7459. if (observer) {
  7460. result._observers.push(observer);
  7461. }
  7462. }
  7463. return result;
  7464. };
  7465. return MultiObserver;
  7466. }());
  7467. BABYLON.MultiObserver = MultiObserver;
  7468. /**
  7469. * The Observable class is a simple implementation of the Observable pattern.
  7470. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7471. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7472. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7473. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7474. */
  7475. var Observable = /** @class */ (function () {
  7476. /**
  7477. * Creates a new observable
  7478. * @param onObserverAdded defines a callback to call when a new observer is added
  7479. */
  7480. function Observable(onObserverAdded) {
  7481. this._observers = new Array();
  7482. this._eventState = new EventState(0);
  7483. if (onObserverAdded) {
  7484. this._onObserverAdded = onObserverAdded;
  7485. }
  7486. }
  7487. /**
  7488. * Create a new Observer with the specified callback
  7489. * @param callback the callback that will be executed for that Observer
  7490. * @param mask the mask used to filter observers
  7491. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7492. * @param scope optional scope for the callback to be called from
  7493. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7494. * @returns the new observer created for the callback
  7495. */
  7496. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7497. if (mask === void 0) { mask = -1; }
  7498. if (insertFirst === void 0) { insertFirst = false; }
  7499. if (scope === void 0) { scope = null; }
  7500. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7501. if (!callback) {
  7502. return null;
  7503. }
  7504. var observer = new Observer(callback, mask, scope);
  7505. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7506. if (insertFirst) {
  7507. this._observers.unshift(observer);
  7508. }
  7509. else {
  7510. this._observers.push(observer);
  7511. }
  7512. if (this._onObserverAdded) {
  7513. this._onObserverAdded(observer);
  7514. }
  7515. return observer;
  7516. };
  7517. /**
  7518. * Remove an Observer from the Observable object
  7519. * @param observer the instance of the Observer to remove
  7520. * @returns false if it doesn't belong to this Observable
  7521. */
  7522. Observable.prototype.remove = function (observer) {
  7523. if (!observer) {
  7524. return false;
  7525. }
  7526. var index = this._observers.indexOf(observer);
  7527. if (index !== -1) {
  7528. this._observers.splice(index, 1);
  7529. return true;
  7530. }
  7531. return false;
  7532. };
  7533. /**
  7534. * Remove a callback from the Observable object
  7535. * @param callback the callback to remove
  7536. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7537. * @returns false if it doesn't belong to this Observable
  7538. */
  7539. Observable.prototype.removeCallback = function (callback, scope) {
  7540. for (var index = 0; index < this._observers.length; index++) {
  7541. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7542. this._observers.splice(index, 1);
  7543. return true;
  7544. }
  7545. }
  7546. return false;
  7547. };
  7548. Observable.prototype._deferUnregister = function (observer) {
  7549. var _this = this;
  7550. observer.unregisterOnNextCall = false;
  7551. observer._willBeUnregistered = true;
  7552. BABYLON.Tools.SetImmediate(function () {
  7553. _this.remove(observer);
  7554. });
  7555. };
  7556. /**
  7557. * Notify all Observers by calling their respective callback with the given data
  7558. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7559. * @param eventData defines the data to send to all observers
  7560. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7561. * @param target defines the original target of the state
  7562. * @param currentTarget defines the current target of the state
  7563. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7564. */
  7565. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7566. if (mask === void 0) { mask = -1; }
  7567. if (!this._observers.length) {
  7568. return true;
  7569. }
  7570. var state = this._eventState;
  7571. state.mask = mask;
  7572. state.target = target;
  7573. state.currentTarget = currentTarget;
  7574. state.skipNextObservers = false;
  7575. state.lastReturnValue = eventData;
  7576. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7577. var obs = _a[_i];
  7578. if (obs._willBeUnregistered) {
  7579. continue;
  7580. }
  7581. if (obs.mask & mask) {
  7582. if (obs.scope) {
  7583. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7584. }
  7585. else {
  7586. state.lastReturnValue = obs.callback(eventData, state);
  7587. }
  7588. if (obs.unregisterOnNextCall) {
  7589. this._deferUnregister(obs);
  7590. }
  7591. }
  7592. if (state.skipNextObservers) {
  7593. return false;
  7594. }
  7595. }
  7596. return true;
  7597. };
  7598. /**
  7599. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7600. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7601. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7602. * and it is crucial that all callbacks will be executed.
  7603. * The order of the callbacks is kept, callbacks are not executed parallel.
  7604. *
  7605. * @param eventData The data to be sent to each callback
  7606. * @param mask is used to filter observers defaults to -1
  7607. * @param target defines the callback target (see EventState)
  7608. * @param currentTarget defines he current object in the bubbling phase
  7609. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7610. */
  7611. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7612. var _this = this;
  7613. if (mask === void 0) { mask = -1; }
  7614. // create an empty promise
  7615. var p = Promise.resolve(eventData);
  7616. // no observers? return this promise.
  7617. if (!this._observers.length) {
  7618. return p;
  7619. }
  7620. var state = this._eventState;
  7621. state.mask = mask;
  7622. state.target = target;
  7623. state.currentTarget = currentTarget;
  7624. state.skipNextObservers = false;
  7625. // execute one callback after another (not using Promise.all, the order is important)
  7626. this._observers.forEach(function (obs) {
  7627. if (state.skipNextObservers) {
  7628. return;
  7629. }
  7630. if (obs._willBeUnregistered) {
  7631. return;
  7632. }
  7633. if (obs.mask & mask) {
  7634. if (obs.scope) {
  7635. p = p.then(function (lastReturnedValue) {
  7636. state.lastReturnValue = lastReturnedValue;
  7637. return obs.callback.apply(obs.scope, [eventData, state]);
  7638. });
  7639. }
  7640. else {
  7641. p = p.then(function (lastReturnedValue) {
  7642. state.lastReturnValue = lastReturnedValue;
  7643. return obs.callback(eventData, state);
  7644. });
  7645. }
  7646. if (obs.unregisterOnNextCall) {
  7647. _this._deferUnregister(obs);
  7648. }
  7649. }
  7650. });
  7651. // return the eventData
  7652. return p.then(function () { return eventData; });
  7653. };
  7654. /**
  7655. * Notify a specific observer
  7656. * @param observer defines the observer to notify
  7657. * @param eventData defines the data to be sent to each callback
  7658. * @param mask is used to filter observers defaults to -1
  7659. */
  7660. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7661. if (mask === void 0) { mask = -1; }
  7662. var state = this._eventState;
  7663. state.mask = mask;
  7664. state.skipNextObservers = false;
  7665. observer.callback(eventData, state);
  7666. };
  7667. /**
  7668. * Gets a boolean indicating if the observable has at least one observer
  7669. * @returns true is the Observable has at least one Observer registered
  7670. */
  7671. Observable.prototype.hasObservers = function () {
  7672. return this._observers.length > 0;
  7673. };
  7674. /**
  7675. * Clear the list of observers
  7676. */
  7677. Observable.prototype.clear = function () {
  7678. this._observers = new Array();
  7679. this._onObserverAdded = null;
  7680. };
  7681. /**
  7682. * Clone the current observable
  7683. * @returns a new observable
  7684. */
  7685. Observable.prototype.clone = function () {
  7686. var result = new Observable();
  7687. result._observers = this._observers.slice(0);
  7688. return result;
  7689. };
  7690. /**
  7691. * Does this observable handles observer registered with a given mask
  7692. * @param mask defines the mask to be tested
  7693. * @return whether or not one observer registered with the given mask is handeled
  7694. **/
  7695. Observable.prototype.hasSpecificMask = function (mask) {
  7696. if (mask === void 0) { mask = -1; }
  7697. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7698. var obs = _a[_i];
  7699. if (obs.mask & mask || obs.mask === mask) {
  7700. return true;
  7701. }
  7702. }
  7703. return false;
  7704. };
  7705. return Observable;
  7706. }());
  7707. BABYLON.Observable = Observable;
  7708. })(BABYLON || (BABYLON = {}));
  7709. //# sourceMappingURL=babylon.observable.js.map
  7710. var BABYLON;
  7711. (function (BABYLON) {
  7712. var SmartArray = /** @class */ (function () {
  7713. function SmartArray(capacity) {
  7714. this.length = 0;
  7715. this.data = new Array(capacity);
  7716. this._id = SmartArray._GlobalId++;
  7717. }
  7718. SmartArray.prototype.push = function (value) {
  7719. this.data[this.length++] = value;
  7720. if (this.length > this.data.length) {
  7721. this.data.length *= 2;
  7722. }
  7723. };
  7724. SmartArray.prototype.forEach = function (func) {
  7725. for (var index = 0; index < this.length; index++) {
  7726. func(this.data[index]);
  7727. }
  7728. };
  7729. SmartArray.prototype.sort = function (compareFn) {
  7730. this.data.sort(compareFn);
  7731. };
  7732. SmartArray.prototype.reset = function () {
  7733. this.length = 0;
  7734. };
  7735. SmartArray.prototype.dispose = function () {
  7736. this.reset();
  7737. if (this.data) {
  7738. this.data.length = 0;
  7739. this.data = [];
  7740. }
  7741. };
  7742. SmartArray.prototype.concat = function (array) {
  7743. if (array.length === 0) {
  7744. return;
  7745. }
  7746. if (this.length + array.length > this.data.length) {
  7747. this.data.length = (this.length + array.length) * 2;
  7748. }
  7749. for (var index = 0; index < array.length; index++) {
  7750. this.data[this.length++] = (array.data || array)[index];
  7751. }
  7752. };
  7753. SmartArray.prototype.indexOf = function (value) {
  7754. var position = this.data.indexOf(value);
  7755. if (position >= this.length) {
  7756. return -1;
  7757. }
  7758. return position;
  7759. };
  7760. SmartArray.prototype.contains = function (value) {
  7761. return this.data.indexOf(value) !== -1;
  7762. };
  7763. // Statics
  7764. SmartArray._GlobalId = 0;
  7765. return SmartArray;
  7766. }());
  7767. BABYLON.SmartArray = SmartArray;
  7768. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7769. __extends(SmartArrayNoDuplicate, _super);
  7770. function SmartArrayNoDuplicate() {
  7771. var _this = _super !== null && _super.apply(this, arguments) || this;
  7772. _this._duplicateId = 0;
  7773. return _this;
  7774. }
  7775. SmartArrayNoDuplicate.prototype.push = function (value) {
  7776. _super.prototype.push.call(this, value);
  7777. if (!value.__smartArrayFlags) {
  7778. value.__smartArrayFlags = {};
  7779. }
  7780. value.__smartArrayFlags[this._id] = this._duplicateId;
  7781. };
  7782. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7783. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7784. return false;
  7785. }
  7786. this.push(value);
  7787. return true;
  7788. };
  7789. SmartArrayNoDuplicate.prototype.reset = function () {
  7790. _super.prototype.reset.call(this);
  7791. this._duplicateId++;
  7792. };
  7793. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7794. if (array.length === 0) {
  7795. return;
  7796. }
  7797. if (this.length + array.length > this.data.length) {
  7798. this.data.length = (this.length + array.length) * 2;
  7799. }
  7800. for (var index = 0; index < array.length; index++) {
  7801. var item = (array.data || array)[index];
  7802. this.pushNoDuplicate(item);
  7803. }
  7804. };
  7805. return SmartArrayNoDuplicate;
  7806. }(SmartArray));
  7807. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7808. })(BABYLON || (BABYLON = {}));
  7809. //# sourceMappingURL=babylon.smartArray.js.map
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7813. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7814. var LoadFileError = /** @class */ (function (_super) {
  7815. __extends(LoadFileError, _super);
  7816. function LoadFileError(message, request) {
  7817. var _this = _super.call(this, message) || this;
  7818. _this.request = request;
  7819. _this.name = "LoadFileError";
  7820. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7821. return _this;
  7822. }
  7823. // Polyfill for Object.setPrototypeOf if necessary.
  7824. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7825. return LoadFileError;
  7826. }(Error));
  7827. BABYLON.LoadFileError = LoadFileError;
  7828. var RetryStrategy = /** @class */ (function () {
  7829. function RetryStrategy() {
  7830. }
  7831. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7832. if (maxRetries === void 0) { maxRetries = 3; }
  7833. if (baseInterval === void 0) { baseInterval = 500; }
  7834. return function (url, request, retryIndex) {
  7835. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7836. return -1;
  7837. }
  7838. return Math.pow(2, retryIndex) * baseInterval;
  7839. };
  7840. };
  7841. return RetryStrategy;
  7842. }());
  7843. BABYLON.RetryStrategy = RetryStrategy;
  7844. // Screenshots
  7845. var screenshotCanvas;
  7846. var cloneValue = function (source, destinationObject) {
  7847. if (!source)
  7848. return null;
  7849. if (source instanceof BABYLON.Mesh) {
  7850. return null;
  7851. }
  7852. if (source instanceof BABYLON.SubMesh) {
  7853. return source.clone(destinationObject);
  7854. }
  7855. else if (source.clone) {
  7856. return source.clone();
  7857. }
  7858. return null;
  7859. };
  7860. var Tools = /** @class */ (function () {
  7861. function Tools() {
  7862. }
  7863. /**
  7864. * Interpolates between a and b via alpha
  7865. * @param a The lower value (returned when alpha = 0)
  7866. * @param b The upper value (returned when alpha = 1)
  7867. * @param alpha The interpolation-factor
  7868. * @return The mixed value
  7869. */
  7870. Tools.Mix = function (a, b, alpha) {
  7871. return a * (1 - alpha) + b * alpha;
  7872. };
  7873. Tools.Instantiate = function (className) {
  7874. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7875. return Tools.RegisteredExternalClasses[className];
  7876. }
  7877. var arr = className.split(".");
  7878. var fn = (window || this);
  7879. for (var i = 0, len = arr.length; i < len; i++) {
  7880. fn = fn[arr[i]];
  7881. }
  7882. if (typeof fn !== "function") {
  7883. return null;
  7884. }
  7885. return fn;
  7886. };
  7887. /**
  7888. * Provides a slice function that will work even on IE
  7889. * @param data defines the array to slice
  7890. * @returns the new sliced array
  7891. */
  7892. Tools.Slice = function (data) {
  7893. if (data.slice) {
  7894. return data.slice();
  7895. }
  7896. return Array.prototype.slice.call(data);
  7897. };
  7898. Tools.SetImmediate = function (action) {
  7899. if (window.setImmediate) {
  7900. window.setImmediate(action);
  7901. }
  7902. else {
  7903. setTimeout(action, 1);
  7904. }
  7905. };
  7906. Tools.IsExponentOfTwo = function (value) {
  7907. var count = 1;
  7908. do {
  7909. count *= 2;
  7910. } while (count < value);
  7911. return count === value;
  7912. };
  7913. /**
  7914. * Find the next highest power of two.
  7915. * @param x Number to start search from.
  7916. * @return Next highest power of two.
  7917. */
  7918. Tools.CeilingPOT = function (x) {
  7919. x--;
  7920. x |= x >> 1;
  7921. x |= x >> 2;
  7922. x |= x >> 4;
  7923. x |= x >> 8;
  7924. x |= x >> 16;
  7925. x++;
  7926. return x;
  7927. };
  7928. /**
  7929. * Find the next lowest power of two.
  7930. * @param x Number to start search from.
  7931. * @return Next lowest power of two.
  7932. */
  7933. Tools.FloorPOT = function (x) {
  7934. x = x | (x >> 1);
  7935. x = x | (x >> 2);
  7936. x = x | (x >> 4);
  7937. x = x | (x >> 8);
  7938. x = x | (x >> 16);
  7939. return x - (x >> 1);
  7940. };
  7941. /**
  7942. * Find the nearest power of two.
  7943. * @param x Number to start search from.
  7944. * @return Next nearest power of two.
  7945. */
  7946. Tools.NearestPOT = function (x) {
  7947. var c = Tools.CeilingPOT(x);
  7948. var f = Tools.FloorPOT(x);
  7949. return (c - x) > (x - f) ? f : c;
  7950. };
  7951. Tools.GetExponentOfTwo = function (value, max, mode) {
  7952. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7953. var pot;
  7954. switch (mode) {
  7955. case BABYLON.Engine.SCALEMODE_FLOOR:
  7956. pot = Tools.FloorPOT(value);
  7957. break;
  7958. case BABYLON.Engine.SCALEMODE_NEAREST:
  7959. pot = Tools.NearestPOT(value);
  7960. break;
  7961. case BABYLON.Engine.SCALEMODE_CEILING:
  7962. default:
  7963. pot = Tools.CeilingPOT(value);
  7964. break;
  7965. }
  7966. return Math.min(pot, max);
  7967. };
  7968. Tools.GetFilename = function (path) {
  7969. var index = path.lastIndexOf("/");
  7970. if (index < 0)
  7971. return path;
  7972. return path.substring(index + 1);
  7973. };
  7974. /**
  7975. * Extracts the "folder" part of a path (everything before the filename).
  7976. * @param uri The URI to extract the info from
  7977. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7978. * @returns The "folder" part of the path
  7979. */
  7980. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7981. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7982. var index = uri.lastIndexOf("/");
  7983. if (index < 0) {
  7984. if (returnUnchangedIfNoSlash) {
  7985. return uri;
  7986. }
  7987. return "";
  7988. }
  7989. return uri.substring(0, index + 1);
  7990. };
  7991. Tools.GetDOMTextContent = function (element) {
  7992. var result = "";
  7993. var child = element.firstChild;
  7994. while (child) {
  7995. if (child.nodeType === 3) {
  7996. result += child.textContent;
  7997. }
  7998. child = child.nextSibling;
  7999. }
  8000. return result;
  8001. };
  8002. Tools.ToDegrees = function (angle) {
  8003. return angle * 180 / Math.PI;
  8004. };
  8005. Tools.ToRadians = function (angle) {
  8006. return angle * Math.PI / 180;
  8007. };
  8008. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8009. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8010. var output = "";
  8011. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8012. var i = 0;
  8013. var bytes = new Uint8Array(buffer);
  8014. while (i < bytes.length) {
  8015. chr1 = bytes[i++];
  8016. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8017. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8018. enc1 = chr1 >> 2;
  8019. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8020. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8021. enc4 = chr3 & 63;
  8022. if (isNaN(chr2)) {
  8023. enc3 = enc4 = 64;
  8024. }
  8025. else if (isNaN(chr3)) {
  8026. enc4 = 64;
  8027. }
  8028. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8029. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8030. }
  8031. return "data:image/png;base64," + output;
  8032. };
  8033. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8034. if (bias === void 0) { bias = null; }
  8035. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8036. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8037. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8038. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8039. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8040. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8041. }
  8042. if (bias) {
  8043. minimum.x -= minimum.x * bias.x + bias.y;
  8044. minimum.y -= minimum.y * bias.x + bias.y;
  8045. minimum.z -= minimum.z * bias.x + bias.y;
  8046. maximum.x += maximum.x * bias.x + bias.y;
  8047. maximum.y += maximum.y * bias.x + bias.y;
  8048. maximum.z += maximum.z * bias.x + bias.y;
  8049. }
  8050. return {
  8051. minimum: minimum,
  8052. maximum: maximum
  8053. };
  8054. };
  8055. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. if (!stride) {
  8060. stride = 3;
  8061. }
  8062. for (var index = start; index < start + count; index++) {
  8063. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8064. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8065. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8066. }
  8067. if (bias) {
  8068. minimum.x -= minimum.x * bias.x + bias.y;
  8069. minimum.y -= minimum.y * bias.x + bias.y;
  8070. minimum.z -= minimum.z * bias.x + bias.y;
  8071. maximum.x += maximum.x * bias.x + bias.y;
  8072. maximum.y += maximum.y * bias.x + bias.y;
  8073. maximum.z += maximum.z * bias.x + bias.y;
  8074. }
  8075. return {
  8076. minimum: minimum,
  8077. maximum: maximum
  8078. };
  8079. };
  8080. Tools.Vector2ArrayFeeder = function (array) {
  8081. return function (index) {
  8082. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8083. var length = isFloatArray ? array.length / 2 : array.length;
  8084. if (index >= length) {
  8085. return null;
  8086. }
  8087. if (isFloatArray) {
  8088. var fa = array;
  8089. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8090. }
  8091. var a = array;
  8092. return a[index];
  8093. };
  8094. };
  8095. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8096. if (bias === void 0) { bias = null; }
  8097. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8098. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8099. var i = 0;
  8100. var cur = feeder(i++);
  8101. while (cur) {
  8102. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8103. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8104. cur = feeder(i++);
  8105. }
  8106. if (bias) {
  8107. minimum.x -= minimum.x * bias.x + bias.y;
  8108. minimum.y -= minimum.y * bias.x + bias.y;
  8109. maximum.x += maximum.x * bias.x + bias.y;
  8110. maximum.y += maximum.y * bias.x + bias.y;
  8111. }
  8112. return {
  8113. minimum: minimum,
  8114. maximum: maximum
  8115. };
  8116. };
  8117. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8118. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8119. return null;
  8120. return Array.isArray(obj) ? obj : [obj];
  8121. };
  8122. // Misc.
  8123. Tools.GetPointerPrefix = function () {
  8124. var eventPrefix = "pointer";
  8125. // Check if pointer events are supported
  8126. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8127. eventPrefix = "mouse";
  8128. }
  8129. return eventPrefix;
  8130. };
  8131. /**
  8132. * @param func - the function to be called
  8133. * @param requester - the object that will request the next frame. Falls back to window.
  8134. */
  8135. Tools.QueueNewFrame = function (func, requester) {
  8136. if (!Tools.IsWindowObjectExist()) {
  8137. return setTimeout(func, 16);
  8138. }
  8139. if (!requester) {
  8140. requester = window;
  8141. }
  8142. if (requester.requestAnimationFrame) {
  8143. return requester.requestAnimationFrame(func);
  8144. }
  8145. else if (requester.msRequestAnimationFrame) {
  8146. return requester.msRequestAnimationFrame(func);
  8147. }
  8148. else if (requester.webkitRequestAnimationFrame) {
  8149. return requester.webkitRequestAnimationFrame(func);
  8150. }
  8151. else if (requester.mozRequestAnimationFrame) {
  8152. return requester.mozRequestAnimationFrame(func);
  8153. }
  8154. else if (requester.oRequestAnimationFrame) {
  8155. return requester.oRequestAnimationFrame(func);
  8156. }
  8157. else {
  8158. return window.setTimeout(func, 16);
  8159. }
  8160. };
  8161. Tools.RequestFullscreen = function (element) {
  8162. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8163. if (!requestFunction)
  8164. return;
  8165. requestFunction.call(element);
  8166. };
  8167. Tools.ExitFullscreen = function () {
  8168. if (document.exitFullscreen) {
  8169. document.exitFullscreen();
  8170. }
  8171. else if (document.mozCancelFullScreen) {
  8172. document.mozCancelFullScreen();
  8173. }
  8174. else if (document.webkitCancelFullScreen) {
  8175. document.webkitCancelFullScreen();
  8176. }
  8177. else if (document.msCancelFullScreen) {
  8178. document.msCancelFullScreen();
  8179. }
  8180. };
  8181. Tools.SetCorsBehavior = function (url, element) {
  8182. if (url && url.indexOf("data:") === 0) {
  8183. return;
  8184. }
  8185. if (Tools.CorsBehavior) {
  8186. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8187. element.crossOrigin = Tools.CorsBehavior;
  8188. }
  8189. else {
  8190. var result = Tools.CorsBehavior(url);
  8191. if (result) {
  8192. element.crossOrigin = result;
  8193. }
  8194. }
  8195. }
  8196. };
  8197. // External files
  8198. Tools.CleanUrl = function (url) {
  8199. url = url.replace(/#/mg, "%23");
  8200. return url;
  8201. };
  8202. Tools.LoadImage = function (url, onLoad, onError, database) {
  8203. if (url instanceof ArrayBuffer) {
  8204. url = Tools.EncodeArrayBufferTobase64(url);
  8205. }
  8206. url = Tools.CleanUrl(url);
  8207. url = Tools.PreprocessUrl(url);
  8208. var img = new Image();
  8209. Tools.SetCorsBehavior(url, img);
  8210. var loadHandler = function () {
  8211. img.removeEventListener("load", loadHandler);
  8212. img.removeEventListener("error", errorHandler);
  8213. onLoad(img);
  8214. };
  8215. var errorHandler = function (err) {
  8216. img.removeEventListener("load", loadHandler);
  8217. img.removeEventListener("error", errorHandler);
  8218. Tools.Error("Error while trying to load image: " + url);
  8219. if (onError) {
  8220. onError("Error while trying to load image: " + url, err);
  8221. }
  8222. };
  8223. img.addEventListener("load", loadHandler);
  8224. img.addEventListener("error", errorHandler);
  8225. var noIndexedDB = function () {
  8226. img.src = url;
  8227. };
  8228. var loadFromIndexedDB = function () {
  8229. if (database) {
  8230. database.loadImageFromDB(url, img);
  8231. }
  8232. };
  8233. //ANY database to do!
  8234. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8235. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8236. }
  8237. else {
  8238. if (url.indexOf("file:") !== -1) {
  8239. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8240. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8241. try {
  8242. var blobURL;
  8243. try {
  8244. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8245. }
  8246. catch (ex) {
  8247. // Chrome doesn't support oneTimeOnly parameter
  8248. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8249. }
  8250. img.src = blobURL;
  8251. }
  8252. catch (e) {
  8253. img.src = "";
  8254. }
  8255. return img;
  8256. }
  8257. }
  8258. noIndexedDB();
  8259. }
  8260. return img;
  8261. };
  8262. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8263. url = Tools.CleanUrl(url);
  8264. url = Tools.PreprocessUrl(url);
  8265. // If file and file input are set
  8266. if (url.indexOf("file:") !== -1) {
  8267. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8268. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8269. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8270. }
  8271. }
  8272. var loadUrl = Tools.BaseUrl + url;
  8273. var aborted = false;
  8274. var fileRequest = {
  8275. onCompleteObservable: new BABYLON.Observable(),
  8276. abort: function () { return aborted = true; },
  8277. };
  8278. var requestFile = function () {
  8279. var request = new XMLHttpRequest();
  8280. var retryHandle = null;
  8281. fileRequest.abort = function () {
  8282. aborted = true;
  8283. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8284. request.abort();
  8285. }
  8286. if (retryHandle !== null) {
  8287. clearTimeout(retryHandle);
  8288. retryHandle = null;
  8289. }
  8290. };
  8291. var retryLoop = function (retryIndex) {
  8292. request.open('GET', loadUrl, true);
  8293. if (useArrayBuffer) {
  8294. request.responseType = "arraybuffer";
  8295. }
  8296. if (onProgress) {
  8297. request.addEventListener("progress", onProgress);
  8298. }
  8299. var onLoadEnd = function () {
  8300. request.removeEventListener("loadend", onLoadEnd);
  8301. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8302. fileRequest.onCompleteObservable.clear();
  8303. };
  8304. request.addEventListener("loadend", onLoadEnd);
  8305. var onReadyStateChange = function () {
  8306. if (aborted) {
  8307. return;
  8308. }
  8309. // In case of undefined state in some browsers.
  8310. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8311. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8312. request.removeEventListener("readystatechange", onReadyStateChange);
  8313. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8314. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8315. return;
  8316. }
  8317. var retryStrategy = Tools.DefaultRetryStrategy;
  8318. if (retryStrategy) {
  8319. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8320. if (waitTime !== -1) {
  8321. // Prevent the request from completing for retry.
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. request = new XMLHttpRequest();
  8324. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8325. return;
  8326. }
  8327. }
  8328. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8329. if (onError) {
  8330. onError(request, e);
  8331. }
  8332. else {
  8333. throw e;
  8334. }
  8335. }
  8336. };
  8337. request.addEventListener("readystatechange", onReadyStateChange);
  8338. request.send();
  8339. };
  8340. retryLoop(0);
  8341. };
  8342. // Caching all files
  8343. if (database && database.enableSceneOffline) {
  8344. var noIndexedDB_1 = function () {
  8345. if (!aborted) {
  8346. requestFile();
  8347. }
  8348. };
  8349. var loadFromIndexedDB = function () {
  8350. // TODO: database needs to support aborting and should return a IFileRequest
  8351. if (aborted) {
  8352. return;
  8353. }
  8354. if (database) {
  8355. database.loadFileFromDB(url, function (data) {
  8356. if (!aborted) {
  8357. onSuccess(data);
  8358. }
  8359. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8360. }, onProgress ? function (event) {
  8361. if (!aborted) {
  8362. onProgress(event);
  8363. }
  8364. } : undefined, noIndexedDB_1, useArrayBuffer);
  8365. }
  8366. };
  8367. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8368. }
  8369. else {
  8370. requestFile();
  8371. }
  8372. return fileRequest;
  8373. };
  8374. /**
  8375. * Load a script (identified by an url). When the url returns, the
  8376. * content of this file is added into a new script element, attached to the DOM (body element)
  8377. */
  8378. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8379. var head = document.getElementsByTagName('head')[0];
  8380. var script = document.createElement('script');
  8381. script.type = 'text/javascript';
  8382. script.src = scriptUrl;
  8383. script.onload = function () {
  8384. if (onSuccess) {
  8385. onSuccess();
  8386. }
  8387. };
  8388. script.onerror = function (e) {
  8389. if (onError) {
  8390. onError("Unable to load script", e);
  8391. }
  8392. };
  8393. head.appendChild(script);
  8394. };
  8395. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8396. var reader = new FileReader();
  8397. var request = {
  8398. onCompleteObservable: new BABYLON.Observable(),
  8399. abort: function () { return reader.abort(); },
  8400. };
  8401. reader.onloadend = function (e) {
  8402. request.onCompleteObservable.notifyObservers(request);
  8403. };
  8404. reader.onload = function (e) {
  8405. //target doesn't have result from ts 1.3
  8406. callback(e.target['result']);
  8407. };
  8408. reader.onprogress = progressCallback;
  8409. reader.readAsDataURL(fileToLoad);
  8410. return request;
  8411. };
  8412. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8413. var reader = new FileReader();
  8414. var request = {
  8415. onCompleteObservable: new BABYLON.Observable(),
  8416. abort: function () { return reader.abort(); },
  8417. };
  8418. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8419. reader.onerror = function (e) {
  8420. Tools.Log("Error while reading file: " + fileToLoad.name);
  8421. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8422. };
  8423. reader.onload = function (e) {
  8424. //target doesn't have result from ts 1.3
  8425. callback(e.target['result']);
  8426. };
  8427. if (progressCallBack) {
  8428. reader.onprogress = progressCallBack;
  8429. }
  8430. if (!useArrayBuffer) {
  8431. // Asynchronous read
  8432. reader.readAsText(fileToLoad);
  8433. }
  8434. else {
  8435. reader.readAsArrayBuffer(fileToLoad);
  8436. }
  8437. return request;
  8438. };
  8439. //returns a downloadable url to a file content.
  8440. Tools.FileAsURL = function (content) {
  8441. var fileBlob = new Blob([content]);
  8442. var url = window.URL || window.webkitURL;
  8443. var link = url.createObjectURL(fileBlob);
  8444. return link;
  8445. };
  8446. // Misc.
  8447. Tools.Format = function (value, decimals) {
  8448. if (decimals === void 0) { decimals = 2; }
  8449. return value.toFixed(decimals);
  8450. };
  8451. Tools.CheckExtends = function (v, min, max) {
  8452. if (v.x < min.x)
  8453. min.x = v.x;
  8454. if (v.y < min.y)
  8455. min.y = v.y;
  8456. if (v.z < min.z)
  8457. min.z = v.z;
  8458. if (v.x > max.x)
  8459. max.x = v.x;
  8460. if (v.y > max.y)
  8461. max.y = v.y;
  8462. if (v.z > max.z)
  8463. max.z = v.z;
  8464. };
  8465. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8466. for (var prop in source) {
  8467. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8468. continue;
  8469. }
  8470. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8471. continue;
  8472. }
  8473. var sourceValue = source[prop];
  8474. var typeOfSourceValue = typeof sourceValue;
  8475. if (typeOfSourceValue === "function") {
  8476. continue;
  8477. }
  8478. if (typeOfSourceValue === "object") {
  8479. if (sourceValue instanceof Array) {
  8480. destination[prop] = [];
  8481. if (sourceValue.length > 0) {
  8482. if (typeof sourceValue[0] == "object") {
  8483. for (var index = 0; index < sourceValue.length; index++) {
  8484. var clonedValue = cloneValue(sourceValue[index], destination);
  8485. if (destination[prop].indexOf(clonedValue) === -1) {
  8486. destination[prop].push(clonedValue);
  8487. }
  8488. }
  8489. }
  8490. else {
  8491. destination[prop] = sourceValue.slice(0);
  8492. }
  8493. }
  8494. }
  8495. else {
  8496. destination[prop] = cloneValue(sourceValue, destination);
  8497. }
  8498. }
  8499. else {
  8500. destination[prop] = sourceValue;
  8501. }
  8502. }
  8503. };
  8504. Tools.IsEmpty = function (obj) {
  8505. for (var i in obj) {
  8506. if (obj.hasOwnProperty(i)) {
  8507. return false;
  8508. }
  8509. }
  8510. return true;
  8511. };
  8512. Tools.RegisterTopRootEvents = function (events) {
  8513. for (var index = 0; index < events.length; index++) {
  8514. var event = events[index];
  8515. window.addEventListener(event.name, event.handler, false);
  8516. try {
  8517. if (window.parent) {
  8518. window.parent.addEventListener(event.name, event.handler, false);
  8519. }
  8520. }
  8521. catch (e) {
  8522. // Silently fails...
  8523. }
  8524. }
  8525. };
  8526. Tools.UnregisterTopRootEvents = function (events) {
  8527. for (var index = 0; index < events.length; index++) {
  8528. var event = events[index];
  8529. window.removeEventListener(event.name, event.handler);
  8530. try {
  8531. if (window.parent) {
  8532. window.parent.removeEventListener(event.name, event.handler);
  8533. }
  8534. }
  8535. catch (e) {
  8536. // Silently fails...
  8537. }
  8538. }
  8539. };
  8540. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. // Read the contents of the framebuffer
  8543. var numberOfChannelsByLine = width * 4;
  8544. var halfHeight = height / 2;
  8545. //Reading datas from WebGL
  8546. var data = engine.readPixels(0, 0, width, height);
  8547. //To flip image on Y axis.
  8548. for (var i = 0; i < halfHeight; i++) {
  8549. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8550. var currentCell = j + i * numberOfChannelsByLine;
  8551. var targetLine = height - i - 1;
  8552. var targetCell = j + targetLine * numberOfChannelsByLine;
  8553. var temp = data[currentCell];
  8554. data[currentCell] = data[targetCell];
  8555. data[targetCell] = temp;
  8556. }
  8557. }
  8558. // Create a 2D canvas to store the result
  8559. if (!screenshotCanvas) {
  8560. screenshotCanvas = document.createElement('canvas');
  8561. }
  8562. screenshotCanvas.width = width;
  8563. screenshotCanvas.height = height;
  8564. var context = screenshotCanvas.getContext('2d');
  8565. if (context) {
  8566. // Copy the pixels to a 2D canvas
  8567. var imageData = context.createImageData(width, height);
  8568. var castData = (imageData.data);
  8569. castData.set(data);
  8570. context.putImageData(imageData, 0, 0);
  8571. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8572. }
  8573. };
  8574. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8575. if (mimeType === void 0) { mimeType = "image/png"; }
  8576. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8577. if (successCallback) {
  8578. successCallback(base64Image);
  8579. }
  8580. else {
  8581. // We need HTMLCanvasElement.toBlob for HD screenshots
  8582. if (!screenshotCanvas.toBlob) {
  8583. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8584. screenshotCanvas.toBlob = function (callback, type, quality) {
  8585. var _this = this;
  8586. setTimeout(function () {
  8587. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8588. for (var i = 0; i < len; i++) {
  8589. arr[i] = binStr.charCodeAt(i);
  8590. }
  8591. callback(new Blob([arr], { type: type || 'image/png' }));
  8592. });
  8593. };
  8594. }
  8595. screenshotCanvas.toBlob(function (blob) {
  8596. var url = URL.createObjectURL(blob);
  8597. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8598. if (("download" in document.createElement("a"))) {
  8599. var a = window.document.createElement("a");
  8600. a.href = url;
  8601. if (fileName) {
  8602. a.setAttribute("download", fileName);
  8603. }
  8604. else {
  8605. var date = new Date();
  8606. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8607. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8608. }
  8609. window.document.body.appendChild(a);
  8610. a.addEventListener("click", function () {
  8611. if (a.parentElement) {
  8612. a.parentElement.removeChild(a);
  8613. }
  8614. });
  8615. a.click();
  8616. }
  8617. else {
  8618. var newWindow = window.open("");
  8619. if (!newWindow)
  8620. return;
  8621. var img = newWindow.document.createElement("img");
  8622. img.onload = function () {
  8623. // no longer need to read the blob so it's revoked
  8624. URL.revokeObjectURL(url);
  8625. };
  8626. img.src = url;
  8627. newWindow.document.body.appendChild(img);
  8628. }
  8629. });
  8630. }
  8631. };
  8632. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8633. if (mimeType === void 0) { mimeType = "image/png"; }
  8634. var width;
  8635. var height;
  8636. // If a precision value is specified
  8637. if (size.precision) {
  8638. width = Math.round(engine.getRenderWidth() * size.precision);
  8639. height = Math.round(width / engine.getAspectRatio(camera));
  8640. }
  8641. else if (size.width && size.height) {
  8642. width = size.width;
  8643. height = size.height;
  8644. }
  8645. else if (size.width && !size.height) {
  8646. width = size.width;
  8647. height = Math.round(width / engine.getAspectRatio(camera));
  8648. }
  8649. else if (size.height && !size.width) {
  8650. height = size.height;
  8651. width = Math.round(height * engine.getAspectRatio(camera));
  8652. }
  8653. else if (!isNaN(size)) {
  8654. height = size;
  8655. width = size;
  8656. }
  8657. else {
  8658. Tools.Error("Invalid 'size' parameter !");
  8659. return;
  8660. }
  8661. if (!screenshotCanvas) {
  8662. screenshotCanvas = document.createElement('canvas');
  8663. }
  8664. screenshotCanvas.width = width;
  8665. screenshotCanvas.height = height;
  8666. var renderContext = screenshotCanvas.getContext("2d");
  8667. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8668. var newWidth = width;
  8669. var newHeight = newWidth / ratio;
  8670. if (newHeight > height) {
  8671. newHeight = height;
  8672. newWidth = newHeight * ratio;
  8673. }
  8674. var offsetX = Math.max(0, width - newWidth) / 2;
  8675. var offsetY = Math.max(0, height - newHeight) / 2;
  8676. var renderingCanvas = engine.getRenderingCanvas();
  8677. if (renderContext && renderingCanvas) {
  8678. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8679. }
  8680. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8681. };
  8682. /**
  8683. * Generates an image screenshot from the specified camera.
  8684. *
  8685. * @param engine The engine to use for rendering
  8686. * @param camera The camera to use for rendering
  8687. * @param size This parameter can be set to a single number or to an object with the
  8688. * following (optional) properties: precision, width, height. If a single number is passed,
  8689. * it will be used for both width and height. If an object is passed, the screenshot size
  8690. * will be derived from the parameters. The precision property is a multiplier allowing
  8691. * rendering at a higher or lower resolution.
  8692. * @param successCallback The callback receives a single parameter which contains the
  8693. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8694. * src parameter of an <img> to display it.
  8695. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8696. * Check your browser for supported MIME types.
  8697. * @param samples Texture samples (default: 1)
  8698. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8699. * @param fileName A name for for the downloaded file.
  8700. * @constructor
  8701. */
  8702. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8703. if (mimeType === void 0) { mimeType = "image/png"; }
  8704. if (samples === void 0) { samples = 1; }
  8705. if (antialiasing === void 0) { antialiasing = false; }
  8706. var width;
  8707. var height;
  8708. //If a precision value is specified
  8709. if (size.precision) {
  8710. width = Math.round(engine.getRenderWidth() * size.precision);
  8711. height = Math.round(width / engine.getAspectRatio(camera));
  8712. size = { width: width, height: height };
  8713. }
  8714. else if (size.width && size.height) {
  8715. width = size.width;
  8716. height = size.height;
  8717. }
  8718. else if (size.width && !size.height) {
  8719. width = size.width;
  8720. height = Math.round(width / engine.getAspectRatio(camera));
  8721. size = { width: width, height: height };
  8722. }
  8723. else if (size.height && !size.width) {
  8724. height = size.height;
  8725. width = Math.round(height * engine.getAspectRatio(camera));
  8726. size = { width: width, height: height };
  8727. }
  8728. else if (!isNaN(size)) {
  8729. height = size;
  8730. width = size;
  8731. }
  8732. else {
  8733. Tools.Error("Invalid 'size' parameter !");
  8734. return;
  8735. }
  8736. var scene = camera.getScene();
  8737. var previousCamera = null;
  8738. if (scene.activeCamera !== camera) {
  8739. previousCamera = scene.activeCamera;
  8740. scene.activeCamera = camera;
  8741. }
  8742. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8743. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8744. texture.renderList = null;
  8745. texture.samples = samples;
  8746. if (antialiasing) {
  8747. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8748. }
  8749. texture.onAfterRenderObservable.add(function () {
  8750. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8751. });
  8752. scene.incrementRenderId();
  8753. scene.resetCachedMaterial();
  8754. texture.render(true);
  8755. texture.dispose();
  8756. if (previousCamera) {
  8757. scene.activeCamera = previousCamera;
  8758. }
  8759. camera.getProjectionMatrix(true); // Force cache refresh;
  8760. };
  8761. // XHR response validator for local file scenario
  8762. Tools.ValidateXHRData = function (xhr, dataType) {
  8763. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8764. if (dataType === void 0) { dataType = 7; }
  8765. try {
  8766. if (dataType & 1) {
  8767. if (xhr.responseText && xhr.responseText.length > 0) {
  8768. return true;
  8769. }
  8770. else if (dataType === 1) {
  8771. return false;
  8772. }
  8773. }
  8774. if (dataType & 2) {
  8775. // Check header width and height since there is no "TGA" magic number
  8776. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8777. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8778. return true;
  8779. }
  8780. else if (dataType === 2) {
  8781. return false;
  8782. }
  8783. }
  8784. if (dataType & 4) {
  8785. // Check for the "DDS" magic number
  8786. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8787. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8788. return true;
  8789. }
  8790. else {
  8791. return false;
  8792. }
  8793. }
  8794. }
  8795. catch (e) {
  8796. // Global protection
  8797. }
  8798. return false;
  8799. };
  8800. /**
  8801. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8802. * Be aware Math.random() could cause collisions, but:
  8803. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  8804. */
  8805. Tools.RandomId = function () {
  8806. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8807. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8808. return v.toString(16);
  8809. });
  8810. };
  8811. /**
  8812. * Test if the given uri is a base64 string.
  8813. * @param uri The uri to test
  8814. * @return True if the uri is a base64 string or false otherwise.
  8815. */
  8816. Tools.IsBase64 = function (uri) {
  8817. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8818. };
  8819. /**
  8820. * Decode the given base64 uri.
  8821. * @param uri The uri to decode
  8822. * @return The decoded base64 data.
  8823. */
  8824. Tools.DecodeBase64 = function (uri) {
  8825. var decodedString = atob(uri.split(",")[1]);
  8826. var bufferLength = decodedString.length;
  8827. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8828. for (var i = 0; i < bufferLength; i++) {
  8829. bufferView[i] = decodedString.charCodeAt(i);
  8830. }
  8831. return bufferView.buffer;
  8832. };
  8833. Object.defineProperty(Tools, "NoneLogLevel", {
  8834. get: function () {
  8835. return Tools._NoneLogLevel;
  8836. },
  8837. enumerable: true,
  8838. configurable: true
  8839. });
  8840. Object.defineProperty(Tools, "MessageLogLevel", {
  8841. get: function () {
  8842. return Tools._MessageLogLevel;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Tools, "WarningLogLevel", {
  8848. get: function () {
  8849. return Tools._WarningLogLevel;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(Tools, "ErrorLogLevel", {
  8855. get: function () {
  8856. return Tools._ErrorLogLevel;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(Tools, "AllLogLevel", {
  8862. get: function () {
  8863. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8864. },
  8865. enumerable: true,
  8866. configurable: true
  8867. });
  8868. Tools._AddLogEntry = function (entry) {
  8869. Tools._LogCache = entry + Tools._LogCache;
  8870. if (Tools.OnNewCacheEntry) {
  8871. Tools.OnNewCacheEntry(entry);
  8872. }
  8873. };
  8874. Tools._FormatMessage = function (message) {
  8875. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8876. var date = new Date();
  8877. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8878. };
  8879. Tools._LogDisabled = function (message) {
  8880. // nothing to do
  8881. };
  8882. Tools._LogEnabled = function (message) {
  8883. var formattedMessage = Tools._FormatMessage(message);
  8884. console.log("BJS - " + formattedMessage);
  8885. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8886. Tools._AddLogEntry(entry);
  8887. };
  8888. Tools._WarnDisabled = function (message) {
  8889. // nothing to do
  8890. };
  8891. Tools._WarnEnabled = function (message) {
  8892. var formattedMessage = Tools._FormatMessage(message);
  8893. console.warn("BJS - " + formattedMessage);
  8894. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8895. Tools._AddLogEntry(entry);
  8896. };
  8897. Tools._ErrorDisabled = function (message) {
  8898. // nothing to do
  8899. };
  8900. Tools._ErrorEnabled = function (message) {
  8901. Tools.errorsCount++;
  8902. var formattedMessage = Tools._FormatMessage(message);
  8903. console.error("BJS - " + formattedMessage);
  8904. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8905. Tools._AddLogEntry(entry);
  8906. };
  8907. Object.defineProperty(Tools, "LogCache", {
  8908. get: function () {
  8909. return Tools._LogCache;
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Tools.ClearLogCache = function () {
  8915. Tools._LogCache = "";
  8916. Tools.errorsCount = 0;
  8917. };
  8918. Object.defineProperty(Tools, "LogLevels", {
  8919. set: function (level) {
  8920. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8921. Tools.Log = Tools._LogEnabled;
  8922. }
  8923. else {
  8924. Tools.Log = Tools._LogDisabled;
  8925. }
  8926. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8927. Tools.Warn = Tools._WarnEnabled;
  8928. }
  8929. else {
  8930. Tools.Warn = Tools._WarnDisabled;
  8931. }
  8932. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8933. Tools.Error = Tools._ErrorEnabled;
  8934. }
  8935. else {
  8936. Tools.Error = Tools._ErrorDisabled;
  8937. }
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Tools.IsWindowObjectExist = function () {
  8943. return (typeof window) !== "undefined";
  8944. };
  8945. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8946. get: function () {
  8947. return Tools._PerformanceNoneLogLevel;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8953. get: function () {
  8954. return Tools._PerformanceUserMarkLogLevel;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8960. get: function () {
  8961. return Tools._PerformanceConsoleLogLevel;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8967. set: function (level) {
  8968. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8969. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8970. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8971. return;
  8972. }
  8973. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8974. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8975. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8976. return;
  8977. }
  8978. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8979. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8985. };
  8986. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8987. };
  8988. Tools._StartUserMark = function (counterName, condition) {
  8989. if (condition === void 0) { condition = true; }
  8990. if (!Tools._performance) {
  8991. if (!Tools.IsWindowObjectExist()) {
  8992. return;
  8993. }
  8994. Tools._performance = window.performance;
  8995. }
  8996. if (!condition || !Tools._performance.mark) {
  8997. return;
  8998. }
  8999. Tools._performance.mark(counterName + "-Begin");
  9000. };
  9001. Tools._EndUserMark = function (counterName, condition) {
  9002. if (condition === void 0) { condition = true; }
  9003. if (!condition || !Tools._performance.mark) {
  9004. return;
  9005. }
  9006. Tools._performance.mark(counterName + "-End");
  9007. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9008. };
  9009. Tools._StartPerformanceConsole = function (counterName, condition) {
  9010. if (condition === void 0) { condition = true; }
  9011. if (!condition) {
  9012. return;
  9013. }
  9014. Tools._StartUserMark(counterName, condition);
  9015. if (console.time) {
  9016. console.time(counterName);
  9017. }
  9018. };
  9019. Tools._EndPerformanceConsole = function (counterName, condition) {
  9020. if (condition === void 0) { condition = true; }
  9021. if (!condition) {
  9022. return;
  9023. }
  9024. Tools._EndUserMark(counterName, condition);
  9025. if (console.time) {
  9026. console.timeEnd(counterName);
  9027. }
  9028. };
  9029. Object.defineProperty(Tools, "Now", {
  9030. get: function () {
  9031. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9032. return window.performance.now();
  9033. }
  9034. return new Date().getTime();
  9035. },
  9036. enumerable: true,
  9037. configurable: true
  9038. });
  9039. /**
  9040. * This method will return the name of the class used to create the instance of the given object.
  9041. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9042. * @param object the object to get the class name from
  9043. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9044. */
  9045. Tools.GetClassName = function (object, isType) {
  9046. if (isType === void 0) { isType = false; }
  9047. var name = null;
  9048. if (!isType && object.getClassName) {
  9049. name = object.getClassName();
  9050. }
  9051. else {
  9052. if (object instanceof Object) {
  9053. var classObj = isType ? object : Object.getPrototypeOf(object);
  9054. name = classObj.constructor["__bjsclassName__"];
  9055. }
  9056. if (!name) {
  9057. name = typeof object;
  9058. }
  9059. }
  9060. return name;
  9061. };
  9062. Tools.First = function (array, predicate) {
  9063. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9064. var el = array_1[_i];
  9065. if (predicate(el)) {
  9066. return el;
  9067. }
  9068. }
  9069. return null;
  9070. };
  9071. /**
  9072. * This method will return the name of the full name of the class, including its owning module (if any).
  9073. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9074. * @param object the object to get the class name from
  9075. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9076. */
  9077. Tools.getFullClassName = function (object, isType) {
  9078. if (isType === void 0) { isType = false; }
  9079. var className = null;
  9080. var moduleName = null;
  9081. if (!isType && object.getClassName) {
  9082. className = object.getClassName();
  9083. }
  9084. else {
  9085. if (object instanceof Object) {
  9086. var classObj = isType ? object : Object.getPrototypeOf(object);
  9087. className = classObj.constructor["__bjsclassName__"];
  9088. moduleName = classObj.constructor["__bjsmoduleName__"];
  9089. }
  9090. if (!className) {
  9091. className = typeof object;
  9092. }
  9093. }
  9094. if (!className) {
  9095. return null;
  9096. }
  9097. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9098. };
  9099. /**
  9100. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9101. * @param array
  9102. */
  9103. Tools.arrayOrStringFeeder = function (array) {
  9104. return function (index) {
  9105. if (index >= array.length) {
  9106. return null;
  9107. }
  9108. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9109. if (val && val.getHashCode) {
  9110. val = val.getHashCode();
  9111. }
  9112. if (typeof val === "string") {
  9113. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9114. }
  9115. return val;
  9116. };
  9117. };
  9118. /**
  9119. * Compute the hashCode of a stream of number
  9120. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9121. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9122. * @return the hash code computed
  9123. */
  9124. Tools.hashCodeFromStream = function (feeder) {
  9125. // Based from here: http://stackoverflow.com/a/7616484/802124
  9126. var hash = 0;
  9127. var index = 0;
  9128. var chr = feeder(index++);
  9129. while (chr != null) {
  9130. hash = ((hash << 5) - hash) + chr;
  9131. hash |= 0; // Convert to 32bit integer
  9132. chr = feeder(index++);
  9133. }
  9134. return hash;
  9135. };
  9136. /**
  9137. * Returns a promise that resolves after the given amount of time.
  9138. * @param delay Number of milliseconds to delay
  9139. * @returns Promise that resolves after the given amount of time
  9140. */
  9141. Tools.DelayAsync = function (delay) {
  9142. return new Promise(function (resolve) {
  9143. setTimeout(function () {
  9144. resolve();
  9145. }, delay);
  9146. });
  9147. };
  9148. Tools.BaseUrl = "";
  9149. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9150. /**
  9151. * Default behaviour for cors in the application.
  9152. * It can be a string if the expected behavior is identical in the entire app.
  9153. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9154. */
  9155. Tools.CorsBehavior = "anonymous";
  9156. Tools.UseFallbackTexture = true;
  9157. /**
  9158. * Use this object to register external classes like custom textures or material
  9159. * to allow the laoders to instantiate them
  9160. */
  9161. Tools.RegisteredExternalClasses = {};
  9162. // Used in case of a texture loading problem
  9163. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9164. Tools.PreprocessUrl = function (url) {
  9165. return url;
  9166. };
  9167. // Logs
  9168. Tools._NoneLogLevel = 0;
  9169. Tools._MessageLogLevel = 1;
  9170. Tools._WarningLogLevel = 2;
  9171. Tools._ErrorLogLevel = 4;
  9172. Tools._LogCache = "";
  9173. Tools.errorsCount = 0;
  9174. Tools.Log = Tools._LogEnabled;
  9175. Tools.Warn = Tools._WarnEnabled;
  9176. Tools.Error = Tools._ErrorEnabled;
  9177. // Performances
  9178. Tools._PerformanceNoneLogLevel = 0;
  9179. Tools._PerformanceUserMarkLogLevel = 1;
  9180. Tools._PerformanceConsoleLogLevel = 2;
  9181. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9182. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9183. return Tools;
  9184. }());
  9185. BABYLON.Tools = Tools;
  9186. /**
  9187. * This class is used to track a performance counter which is number based.
  9188. * The user has access to many properties which give statistics of different nature
  9189. *
  9190. * The implementer can track two kinds of Performance Counter: time and count
  9191. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9192. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9193. */
  9194. var PerfCounter = /** @class */ (function () {
  9195. function PerfCounter() {
  9196. this._startMonitoringTime = 0;
  9197. this._min = 0;
  9198. this._max = 0;
  9199. this._average = 0;
  9200. this._lastSecAverage = 0;
  9201. this._current = 0;
  9202. this._totalValueCount = 0;
  9203. this._totalAccumulated = 0;
  9204. this._lastSecAccumulated = 0;
  9205. this._lastSecTime = 0;
  9206. this._lastSecValueCount = 0;
  9207. }
  9208. Object.defineProperty(PerfCounter.prototype, "min", {
  9209. /**
  9210. * Returns the smallest value ever
  9211. */
  9212. get: function () {
  9213. return this._min;
  9214. },
  9215. enumerable: true,
  9216. configurable: true
  9217. });
  9218. Object.defineProperty(PerfCounter.prototype, "max", {
  9219. /**
  9220. * Returns the biggest value ever
  9221. */
  9222. get: function () {
  9223. return this._max;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(PerfCounter.prototype, "average", {
  9229. /**
  9230. * Returns the average value since the performance counter is running
  9231. */
  9232. get: function () {
  9233. return this._average;
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9239. /**
  9240. * Returns the average value of the last second the counter was monitored
  9241. */
  9242. get: function () {
  9243. return this._lastSecAverage;
  9244. },
  9245. enumerable: true,
  9246. configurable: true
  9247. });
  9248. Object.defineProperty(PerfCounter.prototype, "current", {
  9249. /**
  9250. * Returns the current value
  9251. */
  9252. get: function () {
  9253. return this._current;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(PerfCounter.prototype, "total", {
  9259. get: function () {
  9260. return this._totalAccumulated;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "count", {
  9266. get: function () {
  9267. return this._totalValueCount;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. /**
  9273. * Call this method to start monitoring a new frame.
  9274. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9275. */
  9276. PerfCounter.prototype.fetchNewFrame = function () {
  9277. this._totalValueCount++;
  9278. this._current = 0;
  9279. this._lastSecValueCount++;
  9280. };
  9281. /**
  9282. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9283. * @param newCount the count value to add to the monitored count
  9284. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9285. */
  9286. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9287. if (!PerfCounter.Enabled) {
  9288. return;
  9289. }
  9290. this._current += newCount;
  9291. if (fetchResult) {
  9292. this._fetchResult();
  9293. }
  9294. };
  9295. /**
  9296. * Start monitoring this performance counter
  9297. */
  9298. PerfCounter.prototype.beginMonitoring = function () {
  9299. if (!PerfCounter.Enabled) {
  9300. return;
  9301. }
  9302. this._startMonitoringTime = Tools.Now;
  9303. };
  9304. /**
  9305. * Compute the time lapsed since the previous beginMonitoring() call.
  9306. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9307. */
  9308. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9309. if (newFrame === void 0) { newFrame = true; }
  9310. if (!PerfCounter.Enabled) {
  9311. return;
  9312. }
  9313. if (newFrame) {
  9314. this.fetchNewFrame();
  9315. }
  9316. var currentTime = Tools.Now;
  9317. this._current = currentTime - this._startMonitoringTime;
  9318. if (newFrame) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. PerfCounter.prototype._fetchResult = function () {
  9323. this._totalAccumulated += this._current;
  9324. this._lastSecAccumulated += this._current;
  9325. // Min/Max update
  9326. this._min = Math.min(this._min, this._current);
  9327. this._max = Math.max(this._max, this._current);
  9328. this._average = this._totalAccumulated / this._totalValueCount;
  9329. // Reset last sec?
  9330. var now = Tools.Now;
  9331. if ((now - this._lastSecTime) > 1000) {
  9332. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9333. this._lastSecTime = now;
  9334. this._lastSecAccumulated = 0;
  9335. this._lastSecValueCount = 0;
  9336. }
  9337. };
  9338. PerfCounter.Enabled = true;
  9339. return PerfCounter;
  9340. }());
  9341. BABYLON.PerfCounter = PerfCounter;
  9342. /**
  9343. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9344. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9345. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9346. * @param name The name of the class, case should be preserved
  9347. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9348. */
  9349. function className(name, module) {
  9350. return function (target) {
  9351. target["__bjsclassName__"] = name;
  9352. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9353. };
  9354. }
  9355. BABYLON.className = className;
  9356. /**
  9357. * An implementation of a loop for asynchronous functions.
  9358. */
  9359. var AsyncLoop = /** @class */ (function () {
  9360. /**
  9361. * Constroctor.
  9362. * @param iterations the number of iterations.
  9363. * @param _fn the function to run each iteration
  9364. * @param _successCallback the callback that will be called upon succesful execution
  9365. * @param offset starting offset.
  9366. */
  9367. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. this.iterations = iterations;
  9370. this._fn = _fn;
  9371. this._successCallback = _successCallback;
  9372. this.index = offset - 1;
  9373. this._done = false;
  9374. }
  9375. /**
  9376. * Execute the next iteration. Must be called after the last iteration was finished.
  9377. */
  9378. AsyncLoop.prototype.executeNext = function () {
  9379. if (!this._done) {
  9380. if (this.index + 1 < this.iterations) {
  9381. ++this.index;
  9382. this._fn(this);
  9383. }
  9384. else {
  9385. this.breakLoop();
  9386. }
  9387. }
  9388. };
  9389. /**
  9390. * Break the loop and run the success callback.
  9391. */
  9392. AsyncLoop.prototype.breakLoop = function () {
  9393. this._done = true;
  9394. this._successCallback();
  9395. };
  9396. /**
  9397. * Helper function
  9398. */
  9399. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9400. if (offset === void 0) { offset = 0; }
  9401. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9402. loop.executeNext();
  9403. return loop;
  9404. };
  9405. /**
  9406. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9407. * @param iterations total number of iterations
  9408. * @param syncedIterations number of synchronous iterations in each async iteration.
  9409. * @param fn the function to call each iteration.
  9410. * @param callback a success call back that will be called when iterating stops.
  9411. * @param breakFunction a break condition (optional)
  9412. * @param timeout timeout settings for the setTimeout function. default - 0.
  9413. * @constructor
  9414. */
  9415. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9416. if (timeout === void 0) { timeout = 0; }
  9417. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9418. if (breakFunction && breakFunction())
  9419. loop.breakLoop();
  9420. else {
  9421. setTimeout(function () {
  9422. for (var i = 0; i < syncedIterations; ++i) {
  9423. var iteration = (loop.index * syncedIterations) + i;
  9424. if (iteration >= iterations)
  9425. break;
  9426. fn(iteration);
  9427. if (breakFunction && breakFunction()) {
  9428. loop.breakLoop();
  9429. break;
  9430. }
  9431. }
  9432. loop.executeNext();
  9433. }, timeout);
  9434. }
  9435. }, callback);
  9436. };
  9437. return AsyncLoop;
  9438. }());
  9439. BABYLON.AsyncLoop = AsyncLoop;
  9440. })(BABYLON || (BABYLON = {}));
  9441. //# sourceMappingURL=babylon.tools.js.map
  9442. var BABYLON;
  9443. (function (BABYLON) {
  9444. var PromiseStates;
  9445. (function (PromiseStates) {
  9446. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9447. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9448. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9449. })(PromiseStates || (PromiseStates = {}));
  9450. var FulFillmentAgregator = /** @class */ (function () {
  9451. function FulFillmentAgregator() {
  9452. this.count = 0;
  9453. this.target = 0;
  9454. this.results = [];
  9455. }
  9456. return FulFillmentAgregator;
  9457. }());
  9458. var InternalPromise = /** @class */ (function () {
  9459. function InternalPromise(resolver) {
  9460. var _this = this;
  9461. this._state = PromiseStates.Pending;
  9462. this._children = new Array();
  9463. this._rejectWasConsumed = false;
  9464. if (!resolver) {
  9465. return;
  9466. }
  9467. try {
  9468. resolver(function (value) {
  9469. _this._resolve(value);
  9470. }, function (reason) {
  9471. _this._reject(reason);
  9472. });
  9473. }
  9474. catch (e) {
  9475. this._reject(e);
  9476. }
  9477. }
  9478. InternalPromise.prototype.catch = function (onRejected) {
  9479. return this.then(undefined, onRejected);
  9480. };
  9481. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9482. var _this = this;
  9483. var newPromise = new InternalPromise();
  9484. newPromise._onFulfilled = onFulfilled;
  9485. newPromise._onRejected = onRejected;
  9486. // Composition
  9487. this._children.push(newPromise);
  9488. if (this._state !== PromiseStates.Pending) {
  9489. BABYLON.Tools.SetImmediate(function () {
  9490. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9491. var returnedValue = newPromise._resolve(_this._result);
  9492. if (returnedValue !== undefined && returnedValue !== null) {
  9493. if (returnedValue._state !== undefined) {
  9494. var returnedPromise = returnedValue;
  9495. newPromise._children.push(returnedPromise);
  9496. newPromise = returnedPromise;
  9497. }
  9498. else {
  9499. newPromise._result = returnedValue;
  9500. }
  9501. }
  9502. }
  9503. else {
  9504. newPromise._reject(_this._reason);
  9505. }
  9506. });
  9507. }
  9508. return newPromise;
  9509. };
  9510. InternalPromise.prototype._moveChildren = function (children) {
  9511. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9512. if (this._state === PromiseStates.Fulfilled) {
  9513. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9514. var child = _b[_i];
  9515. child._resolve(this._result);
  9516. }
  9517. }
  9518. else if (this._state === PromiseStates.Rejected) {
  9519. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9520. var child = _d[_c];
  9521. child._reject(this._reason);
  9522. }
  9523. }
  9524. var _a;
  9525. };
  9526. InternalPromise.prototype._resolve = function (value) {
  9527. try {
  9528. this._state = PromiseStates.Fulfilled;
  9529. this._result = value;
  9530. var returnedValue = null;
  9531. if (this._onFulfilled) {
  9532. returnedValue = this._onFulfilled(value);
  9533. }
  9534. if (returnedValue !== undefined && returnedValue !== null) {
  9535. if (returnedValue._state !== undefined) {
  9536. // Transmit children
  9537. var returnedPromise = returnedValue;
  9538. returnedPromise._moveChildren(this._children);
  9539. }
  9540. else {
  9541. value = returnedValue;
  9542. }
  9543. }
  9544. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9545. var child = _a[_i];
  9546. child._resolve(value);
  9547. }
  9548. this._children.length = 0;
  9549. delete this._onFulfilled;
  9550. delete this._onRejected;
  9551. return returnedValue;
  9552. }
  9553. catch (e) {
  9554. this._reject(e, true);
  9555. }
  9556. return null;
  9557. };
  9558. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9559. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9560. this._state = PromiseStates.Rejected;
  9561. this._reason = reason;
  9562. if (this._onRejected && !onLocalThrow) {
  9563. try {
  9564. this._onRejected(reason);
  9565. this._rejectWasConsumed = true;
  9566. }
  9567. catch (e) {
  9568. reason = e;
  9569. }
  9570. }
  9571. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9572. var child = _a[_i];
  9573. if (this._rejectWasConsumed) {
  9574. child._resolve(null);
  9575. }
  9576. else {
  9577. child._reject(reason);
  9578. }
  9579. }
  9580. this._children.length = 0;
  9581. delete this._onFulfilled;
  9582. delete this._onRejected;
  9583. };
  9584. InternalPromise.resolve = function (value) {
  9585. var newPromise = new InternalPromise();
  9586. newPromise._resolve(value);
  9587. return newPromise;
  9588. };
  9589. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9590. promise.then(function (value) {
  9591. agregator.results[index] = value;
  9592. agregator.count++;
  9593. if (agregator.count === agregator.target) {
  9594. agregator.rootPromise._resolve(agregator.results);
  9595. }
  9596. return null;
  9597. }, function (reason) {
  9598. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9599. agregator.rootPromise._reject(reason);
  9600. }
  9601. });
  9602. };
  9603. InternalPromise.all = function (promises) {
  9604. var newPromise = new InternalPromise();
  9605. var agregator = new FulFillmentAgregator();
  9606. agregator.target = promises.length;
  9607. agregator.rootPromise = newPromise;
  9608. if (promises.length) {
  9609. for (var index = 0; index < promises.length; index++) {
  9610. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9611. }
  9612. }
  9613. else {
  9614. newPromise._resolve([]);
  9615. }
  9616. return newPromise;
  9617. };
  9618. InternalPromise.race = function (promises) {
  9619. var newPromise = new InternalPromise();
  9620. if (promises.length) {
  9621. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9622. var promise = promises_1[_i];
  9623. promise.then(function (value) {
  9624. if (newPromise) {
  9625. newPromise._resolve(value);
  9626. newPromise = null;
  9627. }
  9628. return null;
  9629. }, function (reason) {
  9630. if (newPromise) {
  9631. newPromise._reject(reason);
  9632. newPromise = null;
  9633. }
  9634. });
  9635. }
  9636. }
  9637. return newPromise;
  9638. };
  9639. return InternalPromise;
  9640. }());
  9641. /**
  9642. * Helper class that provides a small promise polyfill
  9643. */
  9644. var PromisePolyfill = /** @class */ (function () {
  9645. function PromisePolyfill() {
  9646. }
  9647. /**
  9648. * Static function used to check if the polyfill is required
  9649. * If this is the case then the function will inject the polyfill to window.Promise
  9650. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9651. */
  9652. PromisePolyfill.Apply = function (force) {
  9653. if (force === void 0) { force = false; }
  9654. if (force || typeof Promise === 'undefined') {
  9655. var root = window;
  9656. root.Promise = InternalPromise;
  9657. }
  9658. };
  9659. return PromisePolyfill;
  9660. }());
  9661. BABYLON.PromisePolyfill = PromisePolyfill;
  9662. })(BABYLON || (BABYLON = {}));
  9663. //# sourceMappingURL=babylon.promise.js.map
  9664. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9665. var BABYLON;
  9666. (function (BABYLON) {
  9667. /**
  9668. * Helper class to push actions to a pool of workers.
  9669. */
  9670. var WorkerPool = /** @class */ (function () {
  9671. /**
  9672. * Constructor
  9673. * @param workers Array of workers to use for actions
  9674. */
  9675. function WorkerPool(workers) {
  9676. this._pendingActions = new Array();
  9677. this._workerInfos = workers.map(function (worker) { return ({
  9678. worker: worker,
  9679. active: false
  9680. }); });
  9681. }
  9682. /**
  9683. * Terminates all workers and clears any pending actions.
  9684. */
  9685. WorkerPool.prototype.dispose = function () {
  9686. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9687. var workerInfo = _a[_i];
  9688. workerInfo.worker.terminate();
  9689. }
  9690. delete this._workerInfos;
  9691. delete this._pendingActions;
  9692. };
  9693. /**
  9694. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9695. * pended until a worker has completed its action.
  9696. * @param action The action to perform. Call onComplete when the action is complete.
  9697. */
  9698. WorkerPool.prototype.push = function (action) {
  9699. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9700. var workerInfo = _a[_i];
  9701. if (!workerInfo.active) {
  9702. this._execute(workerInfo, action);
  9703. return;
  9704. }
  9705. }
  9706. this._pendingActions.push(action);
  9707. };
  9708. WorkerPool.prototype._execute = function (workerInfo, action) {
  9709. var _this = this;
  9710. workerInfo.active = true;
  9711. action(workerInfo.worker, function () {
  9712. workerInfo.active = false;
  9713. var nextAction = _this._pendingActions.shift();
  9714. if (nextAction) {
  9715. _this._execute(workerInfo, nextAction);
  9716. }
  9717. });
  9718. };
  9719. return WorkerPool;
  9720. }());
  9721. BABYLON.WorkerPool = WorkerPool;
  9722. })(BABYLON || (BABYLON = {}));
  9723. //# sourceMappingURL=babylon.workerPool.js.map
  9724. var BABYLON;
  9725. (function (BABYLON) {
  9726. var _AlphaState = /** @class */ (function () {
  9727. /**
  9728. * Initializes the state.
  9729. */
  9730. function _AlphaState() {
  9731. this._isAlphaBlendDirty = false;
  9732. this._isBlendFunctionParametersDirty = false;
  9733. this._isBlendEquationParametersDirty = false;
  9734. this._isBlendConstantsDirty = false;
  9735. this._alphaBlend = false;
  9736. this._blendFunctionParameters = new Array(4);
  9737. this._blendEquationParameters = new Array(2);
  9738. this._blendConstants = new Array(4);
  9739. this.reset();
  9740. }
  9741. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9742. get: function () {
  9743. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9749. get: function () {
  9750. return this._alphaBlend;
  9751. },
  9752. set: function (value) {
  9753. if (this._alphaBlend === value) {
  9754. return;
  9755. }
  9756. this._alphaBlend = value;
  9757. this._isAlphaBlendDirty = true;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9763. if (this._blendConstants[0] === r &&
  9764. this._blendConstants[1] === g &&
  9765. this._blendConstants[2] === b &&
  9766. this._blendConstants[3] === a) {
  9767. return;
  9768. }
  9769. this._blendConstants[0] = r;
  9770. this._blendConstants[1] = g;
  9771. this._blendConstants[2] = b;
  9772. this._blendConstants[3] = a;
  9773. this._isBlendConstantsDirty = true;
  9774. };
  9775. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9776. if (this._blendFunctionParameters[0] === value0 &&
  9777. this._blendFunctionParameters[1] === value1 &&
  9778. this._blendFunctionParameters[2] === value2 &&
  9779. this._blendFunctionParameters[3] === value3) {
  9780. return;
  9781. }
  9782. this._blendFunctionParameters[0] = value0;
  9783. this._blendFunctionParameters[1] = value1;
  9784. this._blendFunctionParameters[2] = value2;
  9785. this._blendFunctionParameters[3] = value3;
  9786. this._isBlendFunctionParametersDirty = true;
  9787. };
  9788. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9789. if (this._blendEquationParameters[0] === rgb &&
  9790. this._blendEquationParameters[1] === alpha) {
  9791. return;
  9792. }
  9793. this._blendEquationParameters[0] = rgb;
  9794. this._blendEquationParameters[1] = alpha;
  9795. this._isBlendEquationParametersDirty = true;
  9796. };
  9797. _AlphaState.prototype.reset = function () {
  9798. this._alphaBlend = false;
  9799. this._blendFunctionParameters[0] = null;
  9800. this._blendFunctionParameters[1] = null;
  9801. this._blendFunctionParameters[2] = null;
  9802. this._blendFunctionParameters[3] = null;
  9803. this._blendEquationParameters[0] = null;
  9804. this._blendEquationParameters[1] = null;
  9805. this._blendConstants[0] = null;
  9806. this._blendConstants[1] = null;
  9807. this._blendConstants[2] = null;
  9808. this._blendConstants[3] = null;
  9809. this._isAlphaBlendDirty = true;
  9810. this._isBlendFunctionParametersDirty = false;
  9811. this._isBlendEquationParametersDirty = false;
  9812. this._isBlendConstantsDirty = false;
  9813. };
  9814. _AlphaState.prototype.apply = function (gl) {
  9815. if (!this.isDirty) {
  9816. return;
  9817. }
  9818. // Alpha blend
  9819. if (this._isAlphaBlendDirty) {
  9820. if (this._alphaBlend) {
  9821. gl.enable(gl.BLEND);
  9822. }
  9823. else {
  9824. gl.disable(gl.BLEND);
  9825. }
  9826. this._isAlphaBlendDirty = false;
  9827. }
  9828. // Alpha function
  9829. if (this._isBlendFunctionParametersDirty) {
  9830. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9831. this._isBlendFunctionParametersDirty = false;
  9832. }
  9833. // Alpha equation
  9834. if (this._isBlendEquationParametersDirty) {
  9835. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9836. this._isBlendEquationParametersDirty = false;
  9837. }
  9838. // Constants
  9839. if (this._isBlendConstantsDirty) {
  9840. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9841. this._isBlendConstantsDirty = false;
  9842. }
  9843. };
  9844. return _AlphaState;
  9845. }());
  9846. BABYLON._AlphaState = _AlphaState;
  9847. })(BABYLON || (BABYLON = {}));
  9848. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9849. var BABYLON;
  9850. (function (BABYLON) {
  9851. var _DepthCullingState = /** @class */ (function () {
  9852. /**
  9853. * Initializes the state.
  9854. */
  9855. function _DepthCullingState() {
  9856. this._isDepthTestDirty = false;
  9857. this._isDepthMaskDirty = false;
  9858. this._isDepthFuncDirty = false;
  9859. this._isCullFaceDirty = false;
  9860. this._isCullDirty = false;
  9861. this._isZOffsetDirty = false;
  9862. this._isFrontFaceDirty = false;
  9863. this.reset();
  9864. }
  9865. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9866. get: function () {
  9867. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9873. get: function () {
  9874. return this._zOffset;
  9875. },
  9876. set: function (value) {
  9877. if (this._zOffset === value) {
  9878. return;
  9879. }
  9880. this._zOffset = value;
  9881. this._isZOffsetDirty = true;
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9887. get: function () {
  9888. return this._cullFace;
  9889. },
  9890. set: function (value) {
  9891. if (this._cullFace === value) {
  9892. return;
  9893. }
  9894. this._cullFace = value;
  9895. this._isCullFaceDirty = true;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9901. get: function () {
  9902. return this._cull;
  9903. },
  9904. set: function (value) {
  9905. if (this._cull === value) {
  9906. return;
  9907. }
  9908. this._cull = value;
  9909. this._isCullDirty = true;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9915. get: function () {
  9916. return this._depthFunc;
  9917. },
  9918. set: function (value) {
  9919. if (this._depthFunc === value) {
  9920. return;
  9921. }
  9922. this._depthFunc = value;
  9923. this._isDepthFuncDirty = true;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9929. get: function () {
  9930. return this._depthMask;
  9931. },
  9932. set: function (value) {
  9933. if (this._depthMask === value) {
  9934. return;
  9935. }
  9936. this._depthMask = value;
  9937. this._isDepthMaskDirty = true;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9943. get: function () {
  9944. return this._depthTest;
  9945. },
  9946. set: function (value) {
  9947. if (this._depthTest === value) {
  9948. return;
  9949. }
  9950. this._depthTest = value;
  9951. this._isDepthTestDirty = true;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9957. get: function () {
  9958. return this._frontFace;
  9959. },
  9960. set: function (value) {
  9961. if (this._frontFace === value) {
  9962. return;
  9963. }
  9964. this._frontFace = value;
  9965. this._isFrontFaceDirty = true;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. _DepthCullingState.prototype.reset = function () {
  9971. this._depthMask = true;
  9972. this._depthTest = true;
  9973. this._depthFunc = null;
  9974. this._cullFace = null;
  9975. this._cull = null;
  9976. this._zOffset = 0;
  9977. this._frontFace = null;
  9978. this._isDepthTestDirty = true;
  9979. this._isDepthMaskDirty = true;
  9980. this._isDepthFuncDirty = false;
  9981. this._isCullFaceDirty = false;
  9982. this._isCullDirty = false;
  9983. this._isZOffsetDirty = false;
  9984. this._isFrontFaceDirty = false;
  9985. };
  9986. _DepthCullingState.prototype.apply = function (gl) {
  9987. if (!this.isDirty) {
  9988. return;
  9989. }
  9990. // Cull
  9991. if (this._isCullDirty) {
  9992. if (this.cull) {
  9993. gl.enable(gl.CULL_FACE);
  9994. }
  9995. else {
  9996. gl.disable(gl.CULL_FACE);
  9997. }
  9998. this._isCullDirty = false;
  9999. }
  10000. // Cull face
  10001. if (this._isCullFaceDirty) {
  10002. gl.cullFace(this.cullFace);
  10003. this._isCullFaceDirty = false;
  10004. }
  10005. // Depth mask
  10006. if (this._isDepthMaskDirty) {
  10007. gl.depthMask(this.depthMask);
  10008. this._isDepthMaskDirty = false;
  10009. }
  10010. // Depth test
  10011. if (this._isDepthTestDirty) {
  10012. if (this.depthTest) {
  10013. gl.enable(gl.DEPTH_TEST);
  10014. }
  10015. else {
  10016. gl.disable(gl.DEPTH_TEST);
  10017. }
  10018. this._isDepthTestDirty = false;
  10019. }
  10020. // Depth func
  10021. if (this._isDepthFuncDirty) {
  10022. gl.depthFunc(this.depthFunc);
  10023. this._isDepthFuncDirty = false;
  10024. }
  10025. // zOffset
  10026. if (this._isZOffsetDirty) {
  10027. if (this.zOffset) {
  10028. gl.enable(gl.POLYGON_OFFSET_FILL);
  10029. gl.polygonOffset(this.zOffset, 0);
  10030. }
  10031. else {
  10032. gl.disable(gl.POLYGON_OFFSET_FILL);
  10033. }
  10034. this._isZOffsetDirty = false;
  10035. }
  10036. // Front face
  10037. if (this._isFrontFaceDirty) {
  10038. gl.frontFace(this.frontFace);
  10039. this._isFrontFaceDirty = false;
  10040. }
  10041. };
  10042. return _DepthCullingState;
  10043. }());
  10044. BABYLON._DepthCullingState = _DepthCullingState;
  10045. })(BABYLON || (BABYLON = {}));
  10046. //# sourceMappingURL=babylon.depthCullingState.js.map
  10047. var BABYLON;
  10048. (function (BABYLON) {
  10049. var _StencilState = /** @class */ (function () {
  10050. function _StencilState() {
  10051. this._isStencilTestDirty = false;
  10052. this._isStencilMaskDirty = false;
  10053. this._isStencilFuncDirty = false;
  10054. this._isStencilOpDirty = false;
  10055. this.reset();
  10056. }
  10057. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10058. get: function () {
  10059. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10065. get: function () {
  10066. return this._stencilFunc;
  10067. },
  10068. set: function (value) {
  10069. if (this._stencilFunc === value) {
  10070. return;
  10071. }
  10072. this._stencilFunc = value;
  10073. this._isStencilFuncDirty = true;
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10079. get: function () {
  10080. return this._stencilFuncRef;
  10081. },
  10082. set: function (value) {
  10083. if (this._stencilFuncRef === value) {
  10084. return;
  10085. }
  10086. this._stencilFuncRef = value;
  10087. this._isStencilFuncDirty = true;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10093. get: function () {
  10094. return this._stencilFuncMask;
  10095. },
  10096. set: function (value) {
  10097. if (this._stencilFuncMask === value) {
  10098. return;
  10099. }
  10100. this._stencilFuncMask = value;
  10101. this._isStencilFuncDirty = true;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10107. get: function () {
  10108. return this._stencilOpStencilFail;
  10109. },
  10110. set: function (value) {
  10111. if (this._stencilOpStencilFail === value) {
  10112. return;
  10113. }
  10114. this._stencilOpStencilFail = value;
  10115. this._isStencilOpDirty = true;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10121. get: function () {
  10122. return this._stencilOpDepthFail;
  10123. },
  10124. set: function (value) {
  10125. if (this._stencilOpDepthFail === value) {
  10126. return;
  10127. }
  10128. this._stencilOpDepthFail = value;
  10129. this._isStencilOpDirty = true;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10135. get: function () {
  10136. return this._stencilOpStencilDepthPass;
  10137. },
  10138. set: function (value) {
  10139. if (this._stencilOpStencilDepthPass === value) {
  10140. return;
  10141. }
  10142. this._stencilOpStencilDepthPass = value;
  10143. this._isStencilOpDirty = true;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10149. get: function () {
  10150. return this._stencilMask;
  10151. },
  10152. set: function (value) {
  10153. if (this._stencilMask === value) {
  10154. return;
  10155. }
  10156. this._stencilMask = value;
  10157. this._isStencilMaskDirty = true;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10163. get: function () {
  10164. return this._stencilTest;
  10165. },
  10166. set: function (value) {
  10167. if (this._stencilTest === value) {
  10168. return;
  10169. }
  10170. this._stencilTest = value;
  10171. this._isStencilTestDirty = true;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. _StencilState.prototype.reset = function () {
  10177. this._stencilTest = false;
  10178. this._stencilMask = 0xFF;
  10179. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10180. this._stencilFuncRef = 1;
  10181. this._stencilFuncMask = 0xFF;
  10182. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10183. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10184. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10185. this._isStencilTestDirty = true;
  10186. this._isStencilMaskDirty = true;
  10187. this._isStencilFuncDirty = true;
  10188. this._isStencilOpDirty = true;
  10189. };
  10190. _StencilState.prototype.apply = function (gl) {
  10191. if (!this.isDirty) {
  10192. return;
  10193. }
  10194. // Stencil test
  10195. if (this._isStencilTestDirty) {
  10196. if (this.stencilTest) {
  10197. gl.enable(gl.STENCIL_TEST);
  10198. }
  10199. else {
  10200. gl.disable(gl.STENCIL_TEST);
  10201. }
  10202. this._isStencilTestDirty = false;
  10203. }
  10204. // Stencil mask
  10205. if (this._isStencilMaskDirty) {
  10206. gl.stencilMask(this.stencilMask);
  10207. this._isStencilMaskDirty = false;
  10208. }
  10209. // Stencil func
  10210. if (this._isStencilFuncDirty) {
  10211. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10212. this._isStencilFuncDirty = false;
  10213. }
  10214. // Stencil op
  10215. if (this._isStencilOpDirty) {
  10216. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10217. this._isStencilOpDirty = false;
  10218. }
  10219. };
  10220. return _StencilState;
  10221. }());
  10222. BABYLON._StencilState = _StencilState;
  10223. })(BABYLON || (BABYLON = {}));
  10224. //# sourceMappingURL=babylon.stencilState.js.map
  10225. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10226. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10227. s = arguments[i];
  10228. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10229. t[p] = s[p];
  10230. }
  10231. return t;
  10232. };
  10233. var BABYLON;
  10234. (function (BABYLON) {
  10235. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10236. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10237. };
  10238. var compileRawShader = function (gl, source, type) {
  10239. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10240. gl.shaderSource(shader, source);
  10241. gl.compileShader(shader);
  10242. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10243. var log = gl.getShaderInfoLog(shader);
  10244. if (log) {
  10245. throw new Error(log);
  10246. }
  10247. }
  10248. if (!shader) {
  10249. throw new Error("Something went wrong while compile the shader.");
  10250. }
  10251. return shader;
  10252. };
  10253. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10254. var magFilter = gl.NEAREST;
  10255. var minFilter = gl.NEAREST;
  10256. switch (samplingMode) {
  10257. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10258. magFilter = gl.LINEAR;
  10259. if (generateMipMaps) {
  10260. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10261. }
  10262. else {
  10263. minFilter = gl.LINEAR;
  10264. }
  10265. break;
  10266. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10267. magFilter = gl.LINEAR;
  10268. if (generateMipMaps) {
  10269. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10270. }
  10271. else {
  10272. minFilter = gl.LINEAR;
  10273. }
  10274. break;
  10275. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10276. magFilter = gl.NEAREST;
  10277. if (generateMipMaps) {
  10278. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10279. }
  10280. else {
  10281. minFilter = gl.NEAREST;
  10282. }
  10283. break;
  10284. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10285. magFilter = gl.NEAREST;
  10286. if (generateMipMaps) {
  10287. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10288. }
  10289. else {
  10290. minFilter = gl.NEAREST;
  10291. }
  10292. break;
  10293. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10294. magFilter = gl.NEAREST;
  10295. if (generateMipMaps) {
  10296. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10297. }
  10298. else {
  10299. minFilter = gl.LINEAR;
  10300. }
  10301. break;
  10302. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10303. magFilter = gl.NEAREST;
  10304. if (generateMipMaps) {
  10305. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10306. }
  10307. else {
  10308. minFilter = gl.LINEAR;
  10309. }
  10310. break;
  10311. case BABYLON.Texture.NEAREST_LINEAR:
  10312. magFilter = gl.NEAREST;
  10313. minFilter = gl.LINEAR;
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST:
  10316. magFilter = gl.NEAREST;
  10317. minFilter = gl.NEAREST;
  10318. break;
  10319. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10320. magFilter = gl.LINEAR;
  10321. if (generateMipMaps) {
  10322. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10323. }
  10324. else {
  10325. minFilter = gl.NEAREST;
  10326. }
  10327. break;
  10328. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10329. magFilter = gl.LINEAR;
  10330. if (generateMipMaps) {
  10331. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10332. }
  10333. else {
  10334. minFilter = gl.NEAREST;
  10335. }
  10336. break;
  10337. case BABYLON.Texture.LINEAR_LINEAR:
  10338. magFilter = gl.LINEAR;
  10339. minFilter = gl.LINEAR;
  10340. break;
  10341. case BABYLON.Texture.LINEAR_NEAREST:
  10342. magFilter = gl.LINEAR;
  10343. minFilter = gl.NEAREST;
  10344. break;
  10345. }
  10346. return {
  10347. min: minFilter,
  10348. mag: magFilter
  10349. };
  10350. };
  10351. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10352. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10353. var img;
  10354. var onload = function () {
  10355. loadedImages[index] = img;
  10356. loadedImages._internalCount++;
  10357. if (scene) {
  10358. scene._removePendingData(img);
  10359. }
  10360. if (loadedImages._internalCount === 6) {
  10361. onfinish(loadedImages);
  10362. }
  10363. };
  10364. var onerror = function (message, exception) {
  10365. if (scene) {
  10366. scene._removePendingData(img);
  10367. }
  10368. if (onErrorCallBack) {
  10369. onErrorCallBack(message, exception);
  10370. }
  10371. };
  10372. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10373. if (scene) {
  10374. scene._addPendingData(img);
  10375. }
  10376. };
  10377. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10378. if (onError === void 0) { onError = null; }
  10379. var loadedImages = [];
  10380. loadedImages._internalCount = 0;
  10381. for (var index = 0; index < 6; index++) {
  10382. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10383. }
  10384. };
  10385. var BufferPointer = /** @class */ (function () {
  10386. function BufferPointer() {
  10387. }
  10388. return BufferPointer;
  10389. }());
  10390. var InstancingAttributeInfo = /** @class */ (function () {
  10391. function InstancingAttributeInfo() {
  10392. }
  10393. return InstancingAttributeInfo;
  10394. }());
  10395. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10396. /**
  10397. * Define options used to create a render target texture
  10398. */
  10399. var RenderTargetCreationOptions = /** @class */ (function () {
  10400. function RenderTargetCreationOptions() {
  10401. }
  10402. return RenderTargetCreationOptions;
  10403. }());
  10404. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10405. /**
  10406. * Define options used to create a depth texture
  10407. */
  10408. var DepthTextureCreationOptions = /** @class */ (function () {
  10409. function DepthTextureCreationOptions() {
  10410. }
  10411. return DepthTextureCreationOptions;
  10412. }());
  10413. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10414. /**
  10415. * Regroup several parameters relative to the browser in use
  10416. */
  10417. var EngineCapabilities = /** @class */ (function () {
  10418. function EngineCapabilities() {
  10419. }
  10420. return EngineCapabilities;
  10421. }());
  10422. BABYLON.EngineCapabilities = EngineCapabilities;
  10423. /**
  10424. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10425. */
  10426. var Engine = /** @class */ (function () {
  10427. /**
  10428. * @constructor
  10429. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10430. * @param antialias defines enable antialiasing (default: false)
  10431. * @param options defines further options to be sent to the getContext() function
  10432. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10433. */
  10434. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10435. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10436. var _this = this;
  10437. // Public members
  10438. this.forcePOTTextures = false;
  10439. this.isFullscreen = false;
  10440. this.isPointerLock = false;
  10441. this.cullBackFaces = true;
  10442. this.renderEvenInBackground = true;
  10443. this.preventCacheWipeBetweenFrames = false;
  10444. // To enable/disable IDB support and avoid XHR on .manifest
  10445. this.enableOfflineSupport = false;
  10446. this.scenes = new Array();
  10447. this.postProcesses = new Array();
  10448. // Observables
  10449. /**
  10450. * Observable event triggered each time the rendering canvas is resized
  10451. */
  10452. this.onResizeObservable = new BABYLON.Observable();
  10453. /**
  10454. * Observable event triggered each time the canvas loses focus
  10455. */
  10456. this.onCanvasBlurObservable = new BABYLON.Observable();
  10457. /**
  10458. * Observable event triggered each time the canvas gains focus
  10459. */
  10460. this.onCanvasFocusObservable = new BABYLON.Observable();
  10461. /**
  10462. * Observable event triggered each time the canvas receives pointerout event
  10463. */
  10464. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10465. /**
  10466. * Observable event triggered before each texture is initialized
  10467. */
  10468. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10469. //WebVR
  10470. this._vrDisplay = undefined;
  10471. this._vrSupported = false;
  10472. this._vrExclusivePointerMode = false;
  10473. // Uniform buffers list
  10474. this.disableUniformBuffers = false;
  10475. this._uniformBuffers = new Array();
  10476. // Observables
  10477. /**
  10478. * Observable raised when the engine begins a new frame
  10479. */
  10480. this.onBeginFrameObservable = new BABYLON.Observable();
  10481. /**
  10482. * Observable raised when the engine ends the current frame
  10483. */
  10484. this.onEndFrameObservable = new BABYLON.Observable();
  10485. /**
  10486. * Observable raised when the engine is about to compile a shader
  10487. */
  10488. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10489. /**
  10490. * Observable raised when the engine has jsut compiled a shader
  10491. */
  10492. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10493. this._windowIsBackground = false;
  10494. this._webGLVersion = 1.0;
  10495. this._badOS = false;
  10496. this._badDesktopOS = false;
  10497. /**
  10498. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10499. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10500. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10501. */
  10502. this.disableTextureBindingOptimization = false;
  10503. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10504. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10505. this.onVRRequestPresentStart = new BABYLON.Observable();
  10506. this._colorWrite = true;
  10507. this._drawCalls = new BABYLON.PerfCounter();
  10508. this._textureCollisions = new BABYLON.PerfCounter();
  10509. this._renderingQueueLaunched = false;
  10510. this._activeRenderLoops = new Array();
  10511. // Deterministic lockstepMaxSteps
  10512. this._deterministicLockstep = false;
  10513. this._lockstepMaxSteps = 4;
  10514. // Lost context
  10515. this.onContextLostObservable = new BABYLON.Observable();
  10516. this.onContextRestoredObservable = new BABYLON.Observable();
  10517. this._contextWasLost = false;
  10518. this._doNotHandleContextLost = false;
  10519. // FPS
  10520. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10521. this._fps = 60;
  10522. this._deltaTime = 0;
  10523. /**
  10524. * Turn this value on if you want to pause FPS computation when in background
  10525. */
  10526. this.disablePerformanceMonitorInBackground = false;
  10527. // States
  10528. this._depthCullingState = new BABYLON._DepthCullingState();
  10529. this._stencilState = new BABYLON._StencilState();
  10530. this._alphaState = new BABYLON._AlphaState();
  10531. this._alphaMode = Engine.ALPHA_DISABLE;
  10532. // Cache
  10533. this._internalTexturesCache = new Array();
  10534. this._activeChannel = 0;
  10535. this._currentTextureChannel = -1;
  10536. this._boundTexturesCache = {};
  10537. this._compiledEffects = {};
  10538. this._vertexAttribArraysEnabled = [];
  10539. this._uintIndicesCurrentlySet = false;
  10540. this._currentBoundBuffer = new Array();
  10541. this._currentBufferPointers = new Array();
  10542. this._currentInstanceLocations = new Array();
  10543. this._currentInstanceBuffers = new Array();
  10544. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10545. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10546. this._vaoRecordInProgress = false;
  10547. this._mustWipeVertexAttributes = false;
  10548. this._nextFreeTextureSlots = new Array();
  10549. this._maxSimultaneousTextures = 0;
  10550. this._activeRequests = new Array();
  10551. // Hardware supported Compressed Textures
  10552. this._texturesSupported = new Array();
  10553. this._onVRFullScreenTriggered = function () {
  10554. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10555. //get the old size before we change
  10556. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10557. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10558. //get the width and height, change the render size
  10559. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10560. _this.setHardwareScalingLevel(1);
  10561. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10562. }
  10563. else {
  10564. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10565. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10566. }
  10567. };
  10568. this._boundUniforms = {};
  10569. // Register promises
  10570. BABYLON.PromisePolyfill.Apply();
  10571. var canvas = null;
  10572. Engine.Instances.push(this);
  10573. if (!canvasOrContext) {
  10574. return;
  10575. }
  10576. options = options || {};
  10577. if (canvasOrContext.getContext) {
  10578. canvas = canvasOrContext;
  10579. this._renderingCanvas = canvas;
  10580. if (antialias != null) {
  10581. options.antialias = antialias;
  10582. }
  10583. if (options.deterministicLockstep === undefined) {
  10584. options.deterministicLockstep = false;
  10585. }
  10586. if (options.lockstepMaxSteps === undefined) {
  10587. options.lockstepMaxSteps = 4;
  10588. }
  10589. if (options.preserveDrawingBuffer === undefined) {
  10590. options.preserveDrawingBuffer = false;
  10591. }
  10592. if (options.audioEngine === undefined) {
  10593. options.audioEngine = true;
  10594. }
  10595. if (options.stencil === undefined) {
  10596. options.stencil = true;
  10597. }
  10598. this._deterministicLockstep = options.deterministicLockstep;
  10599. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10600. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10601. // Exceptions
  10602. if (navigator && navigator.userAgent) {
  10603. var ua = navigator.userAgent;
  10604. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10605. var exception = _a[_i];
  10606. var key = exception.key;
  10607. var targets = exception.targets;
  10608. if (ua.indexOf(key) > -1) {
  10609. if (exception.capture && exception.captureConstraint) {
  10610. var capture = exception.capture;
  10611. var constraint = exception.captureConstraint;
  10612. var regex = new RegExp(capture);
  10613. var matches = regex.exec(ua);
  10614. if (matches && matches.length > 0) {
  10615. var capturedValue = parseInt(matches[matches.length - 1]);
  10616. if (capturedValue >= constraint) {
  10617. continue;
  10618. }
  10619. }
  10620. }
  10621. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10622. var target = targets_1[_b];
  10623. switch (target) {
  10624. case "uniformBuffer":
  10625. this.disableUniformBuffers = true;
  10626. break;
  10627. case "textureBindingOptimization":
  10628. this.disableTextureBindingOptimization = true;
  10629. break;
  10630. }
  10631. }
  10632. break;
  10633. }
  10634. }
  10635. }
  10636. // GL
  10637. if (!options.disableWebGL2Support) {
  10638. try {
  10639. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10640. if (this._gl) {
  10641. this._webGLVersion = 2.0;
  10642. }
  10643. }
  10644. catch (e) {
  10645. // Do nothing
  10646. }
  10647. }
  10648. if (!this._gl) {
  10649. if (!canvas) {
  10650. throw new Error("The provided canvas is null or undefined.");
  10651. }
  10652. try {
  10653. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10654. }
  10655. catch (e) {
  10656. throw new Error("WebGL not supported");
  10657. }
  10658. }
  10659. if (!this._gl) {
  10660. throw new Error("WebGL not supported");
  10661. }
  10662. this._onCanvasFocus = function () {
  10663. _this.onCanvasFocusObservable.notifyObservers(_this);
  10664. };
  10665. this._onCanvasBlur = function () {
  10666. _this.onCanvasBlurObservable.notifyObservers(_this);
  10667. };
  10668. canvas.addEventListener("focus", this._onCanvasFocus);
  10669. canvas.addEventListener("blur", this._onCanvasBlur);
  10670. this._onBlur = function () {
  10671. if (_this.disablePerformanceMonitorInBackground) {
  10672. _this._performanceMonitor.disable();
  10673. }
  10674. _this._windowIsBackground = true;
  10675. };
  10676. this._onFocus = function () {
  10677. if (_this.disablePerformanceMonitorInBackground) {
  10678. _this._performanceMonitor.enable();
  10679. }
  10680. _this._windowIsBackground = false;
  10681. };
  10682. this._onCanvasPointerOut = function (ev) {
  10683. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10684. };
  10685. window.addEventListener("blur", this._onBlur);
  10686. window.addEventListener("focus", this._onFocus);
  10687. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10688. // Context lost
  10689. if (!this._doNotHandleContextLost) {
  10690. this._onContextLost = function (evt) {
  10691. evt.preventDefault();
  10692. _this._contextWasLost = true;
  10693. BABYLON.Tools.Warn("WebGL context lost.");
  10694. _this.onContextLostObservable.notifyObservers(_this);
  10695. };
  10696. this._onContextRestored = function (evt) {
  10697. // Adding a timeout to avoid race condition at browser level
  10698. setTimeout(function () {
  10699. // Rebuild gl context
  10700. _this._initGLContext();
  10701. // Rebuild effects
  10702. _this._rebuildEffects();
  10703. // Rebuild textures
  10704. _this._rebuildInternalTextures();
  10705. // Rebuild buffers
  10706. _this._rebuildBuffers();
  10707. // Cache
  10708. _this.wipeCaches(true);
  10709. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10710. _this.onContextRestoredObservable.notifyObservers(_this);
  10711. _this._contextWasLost = false;
  10712. }, 0);
  10713. };
  10714. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10715. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10716. }
  10717. }
  10718. else {
  10719. this._gl = canvasOrContext;
  10720. this._renderingCanvas = this._gl.canvas;
  10721. if (this._gl.renderbufferStorageMultisample) {
  10722. this._webGLVersion = 2.0;
  10723. }
  10724. options.stencil = this._gl.getContextAttributes().stencil;
  10725. }
  10726. // Viewport
  10727. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10728. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10729. this.resize();
  10730. this._isStencilEnable = options.stencil ? true : false;
  10731. this._initGLContext();
  10732. if (canvas) {
  10733. // Fullscreen
  10734. this._onFullscreenChange = function () {
  10735. if (document.fullscreen !== undefined) {
  10736. _this.isFullscreen = document.fullscreen;
  10737. }
  10738. else if (document.mozFullScreen !== undefined) {
  10739. _this.isFullscreen = document.mozFullScreen;
  10740. }
  10741. else if (document.webkitIsFullScreen !== undefined) {
  10742. _this.isFullscreen = document.webkitIsFullScreen;
  10743. }
  10744. else if (document.msIsFullScreen !== undefined) {
  10745. _this.isFullscreen = document.msIsFullScreen;
  10746. }
  10747. // Pointer lock
  10748. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10749. canvas.requestPointerLock = canvas.requestPointerLock ||
  10750. canvas.msRequestPointerLock ||
  10751. canvas.mozRequestPointerLock ||
  10752. canvas.webkitRequestPointerLock;
  10753. if (canvas.requestPointerLock) {
  10754. canvas.requestPointerLock();
  10755. }
  10756. }
  10757. };
  10758. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10759. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10760. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10761. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10762. // Pointer lock
  10763. this._onPointerLockChange = function () {
  10764. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10765. document.webkitPointerLockElement === canvas ||
  10766. document.msPointerLockElement === canvas ||
  10767. document.pointerLockElement === canvas);
  10768. };
  10769. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10770. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10771. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10772. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10773. this._onVRDisplayPointerRestricted = function () {
  10774. if (canvas) {
  10775. canvas.requestPointerLock();
  10776. }
  10777. };
  10778. this._onVRDisplayPointerUnrestricted = function () {
  10779. document.exitPointerLock();
  10780. };
  10781. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10782. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10783. }
  10784. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10785. Engine.audioEngine = new BABYLON.AudioEngine();
  10786. }
  10787. // Prepare buffer pointers
  10788. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10789. this._currentBufferPointers[i] = new BufferPointer();
  10790. }
  10791. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10792. // Load WebVR Devices
  10793. if (options.autoEnableWebVR) {
  10794. this.initWebVR();
  10795. }
  10796. // Detect if we are running on a faulty buggy OS.
  10797. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10798. // Detect if we are running on a faulty buggy desktop OS.
  10799. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10800. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10801. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10802. }
  10803. Object.defineProperty(Engine, "LastCreatedEngine", {
  10804. get: function () {
  10805. if (Engine.Instances.length === 0) {
  10806. return null;
  10807. }
  10808. return Engine.Instances[Engine.Instances.length - 1];
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "LastCreatedScene", {
  10814. get: function () {
  10815. var lastCreatedEngine = Engine.LastCreatedEngine;
  10816. if (!lastCreatedEngine) {
  10817. return null;
  10818. }
  10819. if (lastCreatedEngine.scenes.length === 0) {
  10820. return null;
  10821. }
  10822. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. /**
  10828. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10829. */
  10830. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10831. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10832. var engine = Engine.Instances[engineIndex];
  10833. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10834. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10835. }
  10836. }
  10837. };
  10838. Object.defineProperty(Engine, "NEVER", {
  10839. get: function () {
  10840. return Engine._NEVER;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "ALWAYS", {
  10846. get: function () {
  10847. return Engine._ALWAYS;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(Engine, "LESS", {
  10853. get: function () {
  10854. return Engine._LESS;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(Engine, "EQUAL", {
  10860. get: function () {
  10861. return Engine._EQUAL;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(Engine, "LEQUAL", {
  10867. get: function () {
  10868. return Engine._LEQUAL;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(Engine, "GREATER", {
  10874. get: function () {
  10875. return Engine._GREATER;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine, "GEQUAL", {
  10881. get: function () {
  10882. return Engine._GEQUAL;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(Engine, "NOTEQUAL", {
  10888. get: function () {
  10889. return Engine._NOTEQUAL;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(Engine, "KEEP", {
  10895. get: function () {
  10896. return Engine._KEEP;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(Engine, "REPLACE", {
  10902. get: function () {
  10903. return Engine._REPLACE;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(Engine, "INCR", {
  10909. get: function () {
  10910. return Engine._INCR;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(Engine, "DECR", {
  10916. get: function () {
  10917. return Engine._DECR;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine, "INVERT", {
  10923. get: function () {
  10924. return Engine._INVERT;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine, "INCR_WRAP", {
  10930. get: function () {
  10931. return Engine._INCR_WRAP;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine, "DECR_WRAP", {
  10937. get: function () {
  10938. return Engine._DECR_WRAP;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10944. get: function () {
  10945. return Engine._ALPHA_DISABLE;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10951. get: function () {
  10952. return Engine._ALPHA_ONEONE;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Engine, "ALPHA_ADD", {
  10958. get: function () {
  10959. return Engine._ALPHA_ADD;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10965. get: function () {
  10966. return Engine._ALPHA_COMBINE;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10972. get: function () {
  10973. return Engine._ALPHA_SUBTRACT;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10979. get: function () {
  10980. return Engine._ALPHA_MULTIPLY;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10986. get: function () {
  10987. return Engine._ALPHA_MAXIMIZED;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10993. get: function () {
  10994. return Engine._ALPHA_PREMULTIPLIED;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11000. get: function () {
  11001. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11007. get: function () {
  11008. return Engine._ALPHA_INTERPOLATE;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11014. get: function () {
  11015. return Engine._ALPHA_SCREENMODE;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11021. get: function () {
  11022. return Engine._DELAYLOADSTATE_NONE;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11028. get: function () {
  11029. return Engine._DELAYLOADSTATE_LOADED;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11035. get: function () {
  11036. return Engine._DELAYLOADSTATE_LOADING;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11042. get: function () {
  11043. return Engine._DELAYLOADSTATE_NOTLOADED;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11049. get: function () {
  11050. return Engine._TEXTUREFORMAT_ALPHA;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11056. get: function () {
  11057. return Engine._TEXTUREFORMAT_LUMINANCE;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11063. /**
  11064. * R32F
  11065. */
  11066. get: function () {
  11067. return Engine._TEXTUREFORMAT_R32F;
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11073. /**
  11074. * RG32F
  11075. */
  11076. get: function () {
  11077. return Engine._TEXTUREFORMAT_RG32F;
  11078. },
  11079. enumerable: true,
  11080. configurable: true
  11081. });
  11082. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11083. /**
  11084. * RGB32F
  11085. */
  11086. get: function () {
  11087. return Engine._TEXTUREFORMAT_RGB32F;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11093. /**
  11094. * RGBA32F
  11095. */
  11096. get: function () {
  11097. return Engine._TEXTUREFORMAT_RGBA32F;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11103. get: function () {
  11104. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11110. get: function () {
  11111. return Engine._TEXTUREFORMAT_RGB;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11117. get: function () {
  11118. return Engine._TEXTUREFORMAT_RGBA;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11124. get: function () {
  11125. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11131. get: function () {
  11132. return Engine._TEXTURETYPE_FLOAT;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11138. get: function () {
  11139. return Engine._TEXTURETYPE_HALF_FLOAT;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11145. get: function () {
  11146. return Engine._SCALEMODE_FLOOR;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11152. get: function () {
  11153. return Engine._SCALEMODE_NEAREST;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11159. get: function () {
  11160. return Engine._SCALEMODE_CEILING;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine, "Version", {
  11166. get: function () {
  11167. return "3.2.0-alphaB";
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11173. get: function () {
  11174. return this._vrExclusivePointerMode;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11180. get: function () {
  11181. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11187. get: function () {
  11188. return this._webGLVersion < 2 || this.forcePOTTextures;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(Engine.prototype, "badOS", {
  11194. get: function () {
  11195. return this._badOS;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11201. get: function () {
  11202. return this._badDesktopOS;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11208. get: function () {
  11209. return this._performanceMonitor;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11215. get: function () {
  11216. return this._texturesSupported;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11222. get: function () {
  11223. return this._textureFormatInUse;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(Engine.prototype, "currentViewport", {
  11229. get: function () {
  11230. return this._cachedViewport;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11236. // Empty texture
  11237. get: function () {
  11238. if (!this._emptyTexture) {
  11239. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11240. }
  11241. return this._emptyTexture;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11247. get: function () {
  11248. if (!this._emptyTexture3D) {
  11249. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11250. }
  11251. return this._emptyTexture3D;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11257. get: function () {
  11258. if (!this._emptyCubeTexture) {
  11259. var faceData = new Uint8Array(4);
  11260. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11261. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11262. }
  11263. return this._emptyCubeTexture;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Engine.prototype._rebuildInternalTextures = function () {
  11269. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11270. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11271. var internalTexture = currentState_1[_i];
  11272. internalTexture._rebuild();
  11273. }
  11274. };
  11275. Engine.prototype._rebuildEffects = function () {
  11276. for (var key in this._compiledEffects) {
  11277. var effect = this._compiledEffects[key];
  11278. effect._prepareEffect();
  11279. }
  11280. BABYLON.Effect.ResetCache();
  11281. };
  11282. Engine.prototype._rebuildBuffers = function () {
  11283. // Index / Vertex
  11284. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11285. var scene = _a[_i];
  11286. scene.resetCachedMaterial();
  11287. scene._rebuildGeometries();
  11288. scene._rebuildTextures();
  11289. }
  11290. // Uniforms
  11291. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11292. var uniformBuffer = _c[_b];
  11293. uniformBuffer._rebuild();
  11294. }
  11295. };
  11296. Engine.prototype._initGLContext = function () {
  11297. // Caps
  11298. this._caps = new EngineCapabilities();
  11299. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11300. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11301. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11302. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11303. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11304. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11305. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11306. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11307. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11308. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11309. // Infos
  11310. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11311. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11312. if (rendererInfo != null) {
  11313. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11314. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11315. }
  11316. if (!this._glVendor) {
  11317. this._glVendor = "Unknown vendor";
  11318. }
  11319. if (!this._glRenderer) {
  11320. this._glRenderer = "Unknown renderer";
  11321. }
  11322. // Constants
  11323. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11324. if (this._gl.RGBA16F !== 0x881A) {
  11325. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11326. }
  11327. if (this._gl.RGBA32F !== 0x8814) {
  11328. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11329. }
  11330. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11331. this._gl.DEPTH24_STENCIL8 = 35056;
  11332. }
  11333. // Extensions
  11334. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11335. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11336. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11337. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11338. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11339. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11340. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11341. 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');
  11342. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11343. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11344. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11345. this._caps.highPrecisionShaderSupported = true;
  11346. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11347. if (this._caps.timerQuery) {
  11348. if (this._webGLVersion === 1) {
  11349. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11350. }
  11351. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11352. }
  11353. // Checks if some of the format renders first to allow the use of webgl inspector.
  11354. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11355. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11356. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11357. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11358. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11359. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11360. if (this._webGLVersion > 1) {
  11361. this._gl.HALF_FLOAT_OES = 0x140B;
  11362. }
  11363. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11364. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11365. // Draw buffers
  11366. if (this._webGLVersion > 1) {
  11367. this._caps.drawBuffersExtension = true;
  11368. }
  11369. else {
  11370. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11371. if (drawBuffersExtension !== null) {
  11372. this._caps.drawBuffersExtension = true;
  11373. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11374. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11375. for (var i = 0; i < 16; i++) {
  11376. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11377. }
  11378. }
  11379. else {
  11380. this._caps.drawBuffersExtension = false;
  11381. }
  11382. }
  11383. // Depth Texture
  11384. if (this._webGLVersion > 1) {
  11385. this._caps.depthTextureExtension = true;
  11386. }
  11387. else {
  11388. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11389. if (depthTextureExtension != null) {
  11390. this._caps.depthTextureExtension = true;
  11391. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11392. }
  11393. }
  11394. // Vertex array object
  11395. if (this._webGLVersion > 1) {
  11396. this._caps.vertexArrayObject = true;
  11397. }
  11398. else {
  11399. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11400. if (vertexArrayObjectExtension != null) {
  11401. this._caps.vertexArrayObject = true;
  11402. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11403. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11404. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11405. }
  11406. else {
  11407. this._caps.vertexArrayObject = false;
  11408. }
  11409. }
  11410. // Instances count
  11411. if (this._webGLVersion > 1) {
  11412. this._caps.instancedArrays = true;
  11413. }
  11414. else {
  11415. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11416. if (instanceExtension != null) {
  11417. this._caps.instancedArrays = true;
  11418. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11419. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11420. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11421. }
  11422. else {
  11423. this._caps.instancedArrays = false;
  11424. }
  11425. }
  11426. // Intelligently add supported compressed formats in order to check for.
  11427. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11428. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11429. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11430. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11431. if (this._caps.astc)
  11432. this.texturesSupported.push('-astc.ktx');
  11433. if (this._caps.s3tc)
  11434. this.texturesSupported.push('-dxt.ktx');
  11435. if (this._caps.pvrtc)
  11436. this.texturesSupported.push('-pvrtc.ktx');
  11437. if (this._caps.etc2)
  11438. this.texturesSupported.push('-etc2.ktx');
  11439. if (this._caps.etc1)
  11440. this.texturesSupported.push('-etc1.ktx');
  11441. if (this._gl.getShaderPrecisionFormat) {
  11442. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11443. if (highp) {
  11444. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11445. }
  11446. }
  11447. // Depth buffer
  11448. this.setDepthBuffer(true);
  11449. this.setDepthFunctionToLessOrEqual();
  11450. this.setDepthWrite(true);
  11451. // Texture maps
  11452. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11453. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11454. this._nextFreeTextureSlots.push(slot);
  11455. }
  11456. };
  11457. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11458. get: function () {
  11459. return this._webGLVersion;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11465. /**
  11466. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11467. */
  11468. get: function () {
  11469. return this._isStencilEnable;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Engine.prototype._prepareWorkingCanvas = function () {
  11475. if (this._workingCanvas) {
  11476. return;
  11477. }
  11478. this._workingCanvas = document.createElement("canvas");
  11479. var context = this._workingCanvas.getContext("2d");
  11480. if (context) {
  11481. this._workingContext = context;
  11482. }
  11483. };
  11484. Engine.prototype.resetTextureCache = function () {
  11485. for (var key in this._boundTexturesCache) {
  11486. var boundTexture = this._boundTexturesCache[key];
  11487. if (boundTexture) {
  11488. this._removeDesignatedSlot(boundTexture);
  11489. }
  11490. this._boundTexturesCache[key] = null;
  11491. }
  11492. if (!this.disableTextureBindingOptimization) {
  11493. this._nextFreeTextureSlots = [];
  11494. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11495. this._nextFreeTextureSlots.push(slot);
  11496. }
  11497. }
  11498. this._currentTextureChannel = -1;
  11499. };
  11500. Engine.prototype.isDeterministicLockStep = function () {
  11501. return this._deterministicLockstep;
  11502. };
  11503. Engine.prototype.getLockstepMaxSteps = function () {
  11504. return this._lockstepMaxSteps;
  11505. };
  11506. Engine.prototype.getGlInfo = function () {
  11507. return {
  11508. vendor: this._glVendor,
  11509. renderer: this._glRenderer,
  11510. version: this._glVersion
  11511. };
  11512. };
  11513. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11514. if (useScreen === void 0) { useScreen = false; }
  11515. var viewport = camera.viewport;
  11516. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11517. };
  11518. Engine.prototype.getRenderWidth = function (useScreen) {
  11519. if (useScreen === void 0) { useScreen = false; }
  11520. if (!useScreen && this._currentRenderTarget) {
  11521. return this._currentRenderTarget.width;
  11522. }
  11523. return this._gl.drawingBufferWidth;
  11524. };
  11525. Engine.prototype.getRenderHeight = function (useScreen) {
  11526. if (useScreen === void 0) { useScreen = false; }
  11527. if (!useScreen && this._currentRenderTarget) {
  11528. return this._currentRenderTarget.height;
  11529. }
  11530. return this._gl.drawingBufferHeight;
  11531. };
  11532. Engine.prototype.getRenderingCanvas = function () {
  11533. return this._renderingCanvas;
  11534. };
  11535. Engine.prototype.getRenderingCanvasClientRect = function () {
  11536. if (!this._renderingCanvas) {
  11537. return null;
  11538. }
  11539. return this._renderingCanvas.getBoundingClientRect();
  11540. };
  11541. Engine.prototype.setHardwareScalingLevel = function (level) {
  11542. this._hardwareScalingLevel = level;
  11543. this.resize();
  11544. };
  11545. Engine.prototype.getHardwareScalingLevel = function () {
  11546. return this._hardwareScalingLevel;
  11547. };
  11548. Engine.prototype.getLoadedTexturesCache = function () {
  11549. return this._internalTexturesCache;
  11550. };
  11551. Engine.prototype.getCaps = function () {
  11552. return this._caps;
  11553. };
  11554. Object.defineProperty(Engine.prototype, "drawCalls", {
  11555. /** The number of draw calls submitted last frame */
  11556. get: function () {
  11557. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11558. return 0;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11564. get: function () {
  11565. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11566. return null;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Engine.prototype.getDepthFunction = function () {
  11572. return this._depthCullingState.depthFunc;
  11573. };
  11574. Engine.prototype.setDepthFunction = function (depthFunc) {
  11575. this._depthCullingState.depthFunc = depthFunc;
  11576. };
  11577. Engine.prototype.setDepthFunctionToGreater = function () {
  11578. this._depthCullingState.depthFunc = this._gl.GREATER;
  11579. };
  11580. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11581. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11582. };
  11583. Engine.prototype.setDepthFunctionToLess = function () {
  11584. this._depthCullingState.depthFunc = this._gl.LESS;
  11585. };
  11586. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11587. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11588. };
  11589. Engine.prototype.getStencilBuffer = function () {
  11590. return this._stencilState.stencilTest;
  11591. };
  11592. Engine.prototype.setStencilBuffer = function (enable) {
  11593. this._stencilState.stencilTest = enable;
  11594. };
  11595. Engine.prototype.getStencilMask = function () {
  11596. return this._stencilState.stencilMask;
  11597. };
  11598. Engine.prototype.setStencilMask = function (mask) {
  11599. this._stencilState.stencilMask = mask;
  11600. };
  11601. Engine.prototype.getStencilFunction = function () {
  11602. return this._stencilState.stencilFunc;
  11603. };
  11604. Engine.prototype.getStencilFunctionReference = function () {
  11605. return this._stencilState.stencilFuncRef;
  11606. };
  11607. Engine.prototype.getStencilFunctionMask = function () {
  11608. return this._stencilState.stencilFuncMask;
  11609. };
  11610. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11611. this._stencilState.stencilFunc = stencilFunc;
  11612. };
  11613. Engine.prototype.setStencilFunctionReference = function (reference) {
  11614. this._stencilState.stencilFuncRef = reference;
  11615. };
  11616. Engine.prototype.setStencilFunctionMask = function (mask) {
  11617. this._stencilState.stencilFuncMask = mask;
  11618. };
  11619. Engine.prototype.getStencilOperationFail = function () {
  11620. return this._stencilState.stencilOpStencilFail;
  11621. };
  11622. Engine.prototype.getStencilOperationDepthFail = function () {
  11623. return this._stencilState.stencilOpDepthFail;
  11624. };
  11625. Engine.prototype.getStencilOperationPass = function () {
  11626. return this._stencilState.stencilOpStencilDepthPass;
  11627. };
  11628. Engine.prototype.setStencilOperationFail = function (operation) {
  11629. this._stencilState.stencilOpStencilFail = operation;
  11630. };
  11631. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11632. this._stencilState.stencilOpDepthFail = operation;
  11633. };
  11634. Engine.prototype.setStencilOperationPass = function (operation) {
  11635. this._stencilState.stencilOpStencilDepthPass = operation;
  11636. };
  11637. Engine.prototype.setDitheringState = function (value) {
  11638. if (value) {
  11639. this._gl.enable(this._gl.DITHER);
  11640. }
  11641. else {
  11642. this._gl.disable(this._gl.DITHER);
  11643. }
  11644. };
  11645. Engine.prototype.setRasterizerState = function (value) {
  11646. if (value) {
  11647. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11648. }
  11649. else {
  11650. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11651. }
  11652. };
  11653. /**
  11654. * stop executing a render loop function and remove it from the execution array
  11655. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11656. */
  11657. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11658. if (!renderFunction) {
  11659. this._activeRenderLoops = [];
  11660. return;
  11661. }
  11662. var index = this._activeRenderLoops.indexOf(renderFunction);
  11663. if (index >= 0) {
  11664. this._activeRenderLoops.splice(index, 1);
  11665. }
  11666. };
  11667. Engine.prototype._renderLoop = function () {
  11668. if (!this._contextWasLost) {
  11669. var shouldRender = true;
  11670. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11671. shouldRender = false;
  11672. }
  11673. if (shouldRender) {
  11674. // Start new frame
  11675. this.beginFrame();
  11676. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11677. var renderFunction = this._activeRenderLoops[index];
  11678. renderFunction();
  11679. }
  11680. // Present
  11681. this.endFrame();
  11682. }
  11683. }
  11684. if (this._activeRenderLoops.length > 0) {
  11685. // Register new frame
  11686. var requester = null;
  11687. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11688. requester = this._vrDisplay;
  11689. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11690. }
  11691. else {
  11692. this._renderingQueueLaunched = false;
  11693. }
  11694. };
  11695. /**
  11696. * Register and execute a render loop. The engine can have more than one render function.
  11697. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11698. * @example
  11699. * engine.runRenderLoop(function () {
  11700. * scene.render()
  11701. * })
  11702. */
  11703. Engine.prototype.runRenderLoop = function (renderFunction) {
  11704. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11705. return;
  11706. }
  11707. this._activeRenderLoops.push(renderFunction);
  11708. if (!this._renderingQueueLaunched) {
  11709. this._renderingQueueLaunched = true;
  11710. this._bindedRenderFunction = this._renderLoop.bind(this);
  11711. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11712. }
  11713. };
  11714. /**
  11715. * Toggle full screen mode.
  11716. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11717. * @param {any} options - an options object to be sent to the requestFullscreen function
  11718. */
  11719. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11720. if (this.isFullscreen) {
  11721. BABYLON.Tools.ExitFullscreen();
  11722. }
  11723. else {
  11724. this._pointerLockRequested = requestPointerLock;
  11725. if (this._renderingCanvas) {
  11726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11727. }
  11728. }
  11729. };
  11730. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11731. if (stencil === void 0) { stencil = false; }
  11732. this.applyStates();
  11733. var mode = 0;
  11734. if (backBuffer && color) {
  11735. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11736. mode |= this._gl.COLOR_BUFFER_BIT;
  11737. }
  11738. if (depth) {
  11739. this._gl.clearDepth(1.0);
  11740. mode |= this._gl.DEPTH_BUFFER_BIT;
  11741. }
  11742. if (stencil) {
  11743. this._gl.clearStencil(0);
  11744. mode |= this._gl.STENCIL_BUFFER_BIT;
  11745. }
  11746. this._gl.clear(mode);
  11747. };
  11748. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11749. var gl = this._gl;
  11750. // Save state
  11751. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11752. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11753. // Change state
  11754. gl.enable(gl.SCISSOR_TEST);
  11755. gl.scissor(x, y, width, height);
  11756. // Clear
  11757. this.clear(clearColor, true, true, true);
  11758. // Restore state
  11759. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11760. if (curScissor === true) {
  11761. gl.enable(gl.SCISSOR_TEST);
  11762. }
  11763. else {
  11764. gl.disable(gl.SCISSOR_TEST);
  11765. }
  11766. };
  11767. /**
  11768. * Set the WebGL's viewport
  11769. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11770. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11771. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11772. */
  11773. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11774. var width = requiredWidth || this.getRenderWidth();
  11775. var height = requiredHeight || this.getRenderHeight();
  11776. var x = viewport.x || 0;
  11777. var y = viewport.y || 0;
  11778. this._cachedViewport = viewport;
  11779. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11780. };
  11781. /**
  11782. * Directly set the WebGL Viewport
  11783. * The x, y, width & height are directly passed to the WebGL call
  11784. * @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.
  11785. */
  11786. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11787. var currentViewport = this._cachedViewport;
  11788. this._cachedViewport = null;
  11789. this._gl.viewport(x, y, width, height);
  11790. return currentViewport;
  11791. };
  11792. Engine.prototype.beginFrame = function () {
  11793. this.onBeginFrameObservable.notifyObservers(this);
  11794. this._measureFps();
  11795. };
  11796. Engine.prototype.endFrame = function () {
  11797. //force a flush in case we are using a bad OS.
  11798. if (this._badOS) {
  11799. this.flushFramebuffer();
  11800. }
  11801. //submit frame to the vr device, if enabled
  11802. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11803. // TODO: We should only submit the frame if we read frameData successfully.
  11804. this._vrDisplay.submitFrame();
  11805. }
  11806. this.onEndFrameObservable.notifyObservers(this);
  11807. };
  11808. /**
  11809. * resize the view according to the canvas' size.
  11810. * @example
  11811. * window.addEventListener("resize", function () {
  11812. * engine.resize();
  11813. * });
  11814. */
  11815. Engine.prototype.resize = function () {
  11816. // We're not resizing the size of the canvas while in VR mode & presenting
  11817. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11818. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11819. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11820. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11821. }
  11822. };
  11823. /**
  11824. * force a specific size of the canvas
  11825. * @param {number} width - the new canvas' width
  11826. * @param {number} height - the new canvas' height
  11827. */
  11828. Engine.prototype.setSize = function (width, height) {
  11829. if (!this._renderingCanvas) {
  11830. return;
  11831. }
  11832. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11833. return;
  11834. }
  11835. this._renderingCanvas.width = width;
  11836. this._renderingCanvas.height = height;
  11837. for (var index = 0; index < this.scenes.length; index++) {
  11838. var scene = this.scenes[index];
  11839. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11840. var cam = scene.cameras[camIndex];
  11841. cam._currentRenderId = 0;
  11842. }
  11843. }
  11844. if (this.onResizeObservable.hasObservers) {
  11845. this.onResizeObservable.notifyObservers(this);
  11846. }
  11847. };
  11848. // WebVR functions
  11849. Engine.prototype.isVRDevicePresent = function () {
  11850. return !!this._vrDisplay;
  11851. };
  11852. Engine.prototype.getVRDevice = function () {
  11853. return this._vrDisplay;
  11854. };
  11855. /**
  11856. * Initializes a webVR display and starts listening to display change events.
  11857. * The onVRDisplayChangedObservable will be notified upon these changes.
  11858. * @returns The onVRDisplayChangedObservable.
  11859. */
  11860. Engine.prototype.initWebVR = function () {
  11861. this.initWebVRAsync();
  11862. return this.onVRDisplayChangedObservable;
  11863. };
  11864. /**
  11865. * Initializes a webVR display and starts listening to display change events.
  11866. * The onVRDisplayChangedObservable will be notified upon these changes.
  11867. * @returns A promise containing a VRDisplay and if vr is supported.
  11868. */
  11869. Engine.prototype.initWebVRAsync = function () {
  11870. var _this = this;
  11871. var notifyObservers = function () {
  11872. var eventArgs = {
  11873. vrDisplay: _this._vrDisplay,
  11874. vrSupported: _this._vrSupported
  11875. };
  11876. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11877. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11878. };
  11879. if (!this._onVrDisplayConnect) {
  11880. this._onVrDisplayConnect = function (event) {
  11881. _this._vrDisplay = event.display;
  11882. notifyObservers();
  11883. };
  11884. this._onVrDisplayDisconnect = function () {
  11885. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11886. _this._vrDisplay = undefined;
  11887. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11888. notifyObservers();
  11889. };
  11890. this._onVrDisplayPresentChange = function () {
  11891. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11892. };
  11893. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11894. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11895. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11896. }
  11897. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11898. this._webVRInitPromise.then(notifyObservers);
  11899. return this._webVRInitPromise;
  11900. };
  11901. Engine.prototype.enableVR = function () {
  11902. var _this = this;
  11903. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11904. var onResolved = function () {
  11905. _this.onVRRequestPresentComplete.notifyObservers(true);
  11906. _this._onVRFullScreenTriggered();
  11907. };
  11908. var onRejected = function () {
  11909. _this.onVRRequestPresentComplete.notifyObservers(false);
  11910. };
  11911. this.onVRRequestPresentStart.notifyObservers(this);
  11912. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11913. }
  11914. };
  11915. Engine.prototype.disableVR = function () {
  11916. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11917. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11918. }
  11919. };
  11920. Engine.prototype._getVRDisplaysAsync = function () {
  11921. var _this = this;
  11922. return new Promise(function (res, rej) {
  11923. if (navigator.getVRDisplays) {
  11924. navigator.getVRDisplays().then(function (devices) {
  11925. _this._vrSupported = true;
  11926. // note that devices may actually be an empty array. This is fine;
  11927. // we expect this._vrDisplay to be undefined in this case.
  11928. _this._vrDisplay = devices[0];
  11929. res({
  11930. vrDisplay: _this._vrDisplay,
  11931. vrSupported: _this._vrSupported
  11932. });
  11933. });
  11934. }
  11935. else {
  11936. _this._vrDisplay = undefined;
  11937. _this._vrSupported = false;
  11938. res({
  11939. vrDisplay: _this._vrDisplay,
  11940. vrSupported: _this._vrSupported
  11941. });
  11942. }
  11943. });
  11944. };
  11945. /**
  11946. * Binds the frame buffer to the specified texture.
  11947. * @param texture The texture to render to or null for the default canvas
  11948. * @param faceIndex The face of the texture to render to in case of cube texture
  11949. * @param requiredWidth The width of the target to render to
  11950. * @param requiredHeight The height of the target to render to
  11951. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11952. * @param depthStencilTexture The depth stencil texture to use to render
  11953. */
  11954. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11955. if (this._currentRenderTarget) {
  11956. this.unBindFramebuffer(this._currentRenderTarget);
  11957. }
  11958. this._currentRenderTarget = texture;
  11959. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11960. var gl = this._gl;
  11961. if (texture.isCube) {
  11962. if (faceIndex === undefined) {
  11963. faceIndex = 0;
  11964. }
  11965. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11966. if (depthStencilTexture) {
  11967. if (depthStencilTexture._generateStencilBuffer) {
  11968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11969. }
  11970. else {
  11971. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11972. }
  11973. }
  11974. }
  11975. if (this._cachedViewport && !forceFullscreenViewport) {
  11976. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11977. }
  11978. else {
  11979. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11980. }
  11981. this.wipeCaches();
  11982. };
  11983. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11984. if (this._currentFramebuffer !== framebuffer) {
  11985. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11986. this._currentFramebuffer = framebuffer;
  11987. }
  11988. };
  11989. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11990. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11991. this._currentRenderTarget = null;
  11992. // If MSAA, we need to bitblt back to main texture
  11993. var gl = this._gl;
  11994. if (texture._MSAAFramebuffer) {
  11995. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11996. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11997. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11998. }
  11999. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12000. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12001. gl.generateMipmap(gl.TEXTURE_2D);
  12002. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12003. }
  12004. if (onBeforeUnbind) {
  12005. if (texture._MSAAFramebuffer) {
  12006. // Bind the correct framebuffer
  12007. this.bindUnboundFramebuffer(texture._framebuffer);
  12008. }
  12009. onBeforeUnbind();
  12010. }
  12011. this.bindUnboundFramebuffer(null);
  12012. };
  12013. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12014. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12015. this._currentRenderTarget = null;
  12016. // If MSAA, we need to bitblt back to main texture
  12017. var gl = this._gl;
  12018. if (textures[0]._MSAAFramebuffer) {
  12019. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12020. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12021. var attachments = textures[0]._attachments;
  12022. if (!attachments) {
  12023. attachments = new Array(textures.length);
  12024. textures[0]._attachments = attachments;
  12025. }
  12026. for (var i = 0; i < textures.length; i++) {
  12027. var texture = textures[i];
  12028. for (var j = 0; j < attachments.length; j++) {
  12029. attachments[j] = gl.NONE;
  12030. }
  12031. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12032. gl.readBuffer(attachments[i]);
  12033. gl.drawBuffers(attachments);
  12034. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12035. }
  12036. for (var i = 0; i < attachments.length; i++) {
  12037. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12038. }
  12039. gl.drawBuffers(attachments);
  12040. }
  12041. for (var i = 0; i < textures.length; i++) {
  12042. var texture = textures[i];
  12043. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12044. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12045. gl.generateMipmap(gl.TEXTURE_2D);
  12046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12047. }
  12048. }
  12049. if (onBeforeUnbind) {
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. // Bind the correct framebuffer
  12052. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12053. }
  12054. onBeforeUnbind();
  12055. }
  12056. this.bindUnboundFramebuffer(null);
  12057. };
  12058. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12059. if (texture.generateMipMaps) {
  12060. var gl = this._gl;
  12061. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12062. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12063. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12064. }
  12065. };
  12066. Engine.prototype.flushFramebuffer = function () {
  12067. this._gl.flush();
  12068. };
  12069. Engine.prototype.restoreDefaultFramebuffer = function () {
  12070. if (this._currentRenderTarget) {
  12071. this.unBindFramebuffer(this._currentRenderTarget);
  12072. }
  12073. else {
  12074. this.bindUnboundFramebuffer(null);
  12075. }
  12076. if (this._cachedViewport) {
  12077. this.setViewport(this._cachedViewport);
  12078. }
  12079. this.wipeCaches();
  12080. };
  12081. // UBOs
  12082. Engine.prototype.createUniformBuffer = function (elements) {
  12083. var ubo = this._gl.createBuffer();
  12084. if (!ubo) {
  12085. throw new Error("Unable to create uniform buffer");
  12086. }
  12087. this.bindUniformBuffer(ubo);
  12088. if (elements instanceof Float32Array) {
  12089. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12090. }
  12091. else {
  12092. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12093. }
  12094. this.bindUniformBuffer(null);
  12095. ubo.references = 1;
  12096. return ubo;
  12097. };
  12098. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12099. var ubo = this._gl.createBuffer();
  12100. if (!ubo) {
  12101. throw new Error("Unable to create dynamic uniform buffer");
  12102. }
  12103. this.bindUniformBuffer(ubo);
  12104. if (elements instanceof Float32Array) {
  12105. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12106. }
  12107. else {
  12108. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12109. }
  12110. this.bindUniformBuffer(null);
  12111. ubo.references = 1;
  12112. return ubo;
  12113. };
  12114. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12115. this.bindUniformBuffer(uniformBuffer);
  12116. if (offset === undefined) {
  12117. offset = 0;
  12118. }
  12119. if (count === undefined) {
  12120. if (elements instanceof Float32Array) {
  12121. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12122. }
  12123. else {
  12124. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12125. }
  12126. }
  12127. else {
  12128. if (elements instanceof Float32Array) {
  12129. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12130. }
  12131. else {
  12132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12133. }
  12134. }
  12135. this.bindUniformBuffer(null);
  12136. };
  12137. // VBOs
  12138. Engine.prototype._resetVertexBufferBinding = function () {
  12139. this.bindArrayBuffer(null);
  12140. this._cachedVertexBuffers = null;
  12141. };
  12142. Engine.prototype.createVertexBuffer = function (vertices) {
  12143. var vbo = this._gl.createBuffer();
  12144. if (!vbo) {
  12145. throw new Error("Unable to create vertex buffer");
  12146. }
  12147. this.bindArrayBuffer(vbo);
  12148. if (vertices instanceof Float32Array) {
  12149. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12150. }
  12151. else {
  12152. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12153. }
  12154. this._resetVertexBufferBinding();
  12155. vbo.references = 1;
  12156. return vbo;
  12157. };
  12158. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12159. var vbo = this._gl.createBuffer();
  12160. if (!vbo) {
  12161. throw new Error("Unable to create dynamic vertex buffer");
  12162. }
  12163. this.bindArrayBuffer(vbo);
  12164. if (vertices instanceof Float32Array) {
  12165. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12166. }
  12167. else {
  12168. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12169. }
  12170. this._resetVertexBufferBinding();
  12171. vbo.references = 1;
  12172. return vbo;
  12173. };
  12174. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12175. if (offset === void 0) { offset = 0; }
  12176. // Force cache update
  12177. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12178. this.bindIndexBuffer(indexBuffer);
  12179. var arrayBuffer;
  12180. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12181. arrayBuffer = indices;
  12182. }
  12183. else {
  12184. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12185. }
  12186. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12187. this._resetIndexBufferBinding();
  12188. };
  12189. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12190. this.bindArrayBuffer(vertexBuffer);
  12191. if (offset === undefined) {
  12192. offset = 0;
  12193. }
  12194. if (count === undefined) {
  12195. if (vertices instanceof Float32Array) {
  12196. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12197. }
  12198. else {
  12199. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12200. }
  12201. }
  12202. else {
  12203. if (vertices instanceof Float32Array) {
  12204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12205. }
  12206. else {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12208. }
  12209. }
  12210. this._resetVertexBufferBinding();
  12211. };
  12212. Engine.prototype._resetIndexBufferBinding = function () {
  12213. this.bindIndexBuffer(null);
  12214. this._cachedIndexBuffer = null;
  12215. };
  12216. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12217. var vbo = this._gl.createBuffer();
  12218. if (!vbo) {
  12219. throw new Error("Unable to create index buffer");
  12220. }
  12221. this.bindIndexBuffer(vbo);
  12222. // Check for 32 bits indices
  12223. var arrayBuffer;
  12224. var need32Bits = false;
  12225. if (indices instanceof Uint16Array) {
  12226. arrayBuffer = indices;
  12227. }
  12228. else {
  12229. //check 32 bit support
  12230. if (this._caps.uintIndices) {
  12231. if (indices instanceof Uint32Array) {
  12232. arrayBuffer = indices;
  12233. need32Bits = true;
  12234. }
  12235. else {
  12236. //number[] or Int32Array, check if 32 bit is necessary
  12237. for (var index = 0; index < indices.length; index++) {
  12238. if (indices[index] > 65535) {
  12239. need32Bits = true;
  12240. break;
  12241. }
  12242. }
  12243. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12244. }
  12245. }
  12246. else {
  12247. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12248. arrayBuffer = new Uint16Array(indices);
  12249. }
  12250. }
  12251. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12252. this._resetIndexBufferBinding();
  12253. vbo.references = 1;
  12254. vbo.is32Bits = need32Bits;
  12255. return vbo;
  12256. };
  12257. Engine.prototype.bindArrayBuffer = function (buffer) {
  12258. if (!this._vaoRecordInProgress) {
  12259. this._unbindVertexArrayObject();
  12260. }
  12261. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12262. };
  12263. Engine.prototype.bindUniformBuffer = function (buffer) {
  12264. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12265. };
  12266. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12267. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12268. };
  12269. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12270. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12271. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12272. };
  12273. ;
  12274. Engine.prototype.bindIndexBuffer = function (buffer) {
  12275. if (!this._vaoRecordInProgress) {
  12276. this._unbindVertexArrayObject();
  12277. }
  12278. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12279. };
  12280. Engine.prototype.bindBuffer = function (buffer, target) {
  12281. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12282. this._gl.bindBuffer(target, buffer);
  12283. this._currentBoundBuffer[target] = buffer;
  12284. }
  12285. };
  12286. Engine.prototype.updateArrayBuffer = function (data) {
  12287. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12288. };
  12289. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12290. var pointer = this._currentBufferPointers[indx];
  12291. var changed = false;
  12292. if (!pointer.active) {
  12293. changed = true;
  12294. pointer.active = true;
  12295. pointer.index = indx;
  12296. pointer.size = size;
  12297. pointer.type = type;
  12298. pointer.normalized = normalized;
  12299. pointer.stride = stride;
  12300. pointer.offset = offset;
  12301. pointer.buffer = buffer;
  12302. }
  12303. else {
  12304. if (pointer.buffer !== buffer) {
  12305. pointer.buffer = buffer;
  12306. changed = true;
  12307. }
  12308. if (pointer.size !== size) {
  12309. pointer.size = size;
  12310. changed = true;
  12311. }
  12312. if (pointer.type !== type) {
  12313. pointer.type = type;
  12314. changed = true;
  12315. }
  12316. if (pointer.normalized !== normalized) {
  12317. pointer.normalized = normalized;
  12318. changed = true;
  12319. }
  12320. if (pointer.stride !== stride) {
  12321. pointer.stride = stride;
  12322. changed = true;
  12323. }
  12324. if (pointer.offset !== offset) {
  12325. pointer.offset = offset;
  12326. changed = true;
  12327. }
  12328. }
  12329. if (changed || this._vaoRecordInProgress) {
  12330. this.bindArrayBuffer(buffer);
  12331. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12332. }
  12333. };
  12334. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12335. if (indexBuffer == null) {
  12336. return;
  12337. }
  12338. if (this._cachedIndexBuffer !== indexBuffer) {
  12339. this._cachedIndexBuffer = indexBuffer;
  12340. this.bindIndexBuffer(indexBuffer);
  12341. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12342. }
  12343. };
  12344. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12345. var attributes = effect.getAttributesNames();
  12346. if (!this._vaoRecordInProgress) {
  12347. this._unbindVertexArrayObject();
  12348. }
  12349. this.unbindAllAttributes();
  12350. for (var index = 0; index < attributes.length; index++) {
  12351. var order = effect.getAttributeLocation(index);
  12352. if (order >= 0) {
  12353. var vertexBuffer = vertexBuffers[attributes[index]];
  12354. if (!vertexBuffer) {
  12355. continue;
  12356. }
  12357. this._gl.enableVertexAttribArray(order);
  12358. if (!this._vaoRecordInProgress) {
  12359. this._vertexAttribArraysEnabled[order] = true;
  12360. }
  12361. var buffer = vertexBuffer.getBuffer();
  12362. if (buffer) {
  12363. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12364. if (vertexBuffer.getIsInstanced()) {
  12365. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12366. if (!this._vaoRecordInProgress) {
  12367. this._currentInstanceLocations.push(order);
  12368. this._currentInstanceBuffers.push(buffer);
  12369. }
  12370. }
  12371. }
  12372. }
  12373. }
  12374. };
  12375. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12376. var vao = this._gl.createVertexArray();
  12377. this._vaoRecordInProgress = true;
  12378. this._gl.bindVertexArray(vao);
  12379. this._mustWipeVertexAttributes = true;
  12380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12381. this.bindIndexBuffer(indexBuffer);
  12382. this._vaoRecordInProgress = false;
  12383. this._gl.bindVertexArray(null);
  12384. return vao;
  12385. };
  12386. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12387. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12388. this._cachedVertexArrayObject = vertexArrayObject;
  12389. this._gl.bindVertexArray(vertexArrayObject);
  12390. this._cachedVertexBuffers = null;
  12391. this._cachedIndexBuffer = null;
  12392. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12393. this._mustWipeVertexAttributes = true;
  12394. }
  12395. };
  12396. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12397. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12398. this._cachedVertexBuffers = vertexBuffer;
  12399. this._cachedEffectForVertexBuffers = effect;
  12400. var attributesCount = effect.getAttributesCount();
  12401. this._unbindVertexArrayObject();
  12402. this.unbindAllAttributes();
  12403. var offset = 0;
  12404. for (var index = 0; index < attributesCount; index++) {
  12405. if (index < vertexDeclaration.length) {
  12406. var order = effect.getAttributeLocation(index);
  12407. if (order >= 0) {
  12408. this._gl.enableVertexAttribArray(order);
  12409. this._vertexAttribArraysEnabled[order] = true;
  12410. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12411. }
  12412. offset += vertexDeclaration[index] * 4;
  12413. }
  12414. }
  12415. }
  12416. this._bindIndexBufferWithCache(indexBuffer);
  12417. };
  12418. Engine.prototype._unbindVertexArrayObject = function () {
  12419. if (!this._cachedVertexArrayObject) {
  12420. return;
  12421. }
  12422. this._cachedVertexArrayObject = null;
  12423. this._gl.bindVertexArray(null);
  12424. };
  12425. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12426. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12427. this._cachedVertexBuffers = vertexBuffers;
  12428. this._cachedEffectForVertexBuffers = effect;
  12429. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12430. }
  12431. this._bindIndexBufferWithCache(indexBuffer);
  12432. };
  12433. Engine.prototype.unbindInstanceAttributes = function () {
  12434. var boundBuffer;
  12435. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12436. var instancesBuffer = this._currentInstanceBuffers[i];
  12437. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12438. boundBuffer = instancesBuffer;
  12439. this.bindArrayBuffer(instancesBuffer);
  12440. }
  12441. var offsetLocation = this._currentInstanceLocations[i];
  12442. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12443. }
  12444. this._currentInstanceBuffers.length = 0;
  12445. this._currentInstanceLocations.length = 0;
  12446. };
  12447. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12448. this._gl.deleteVertexArray(vao);
  12449. };
  12450. Engine.prototype._releaseBuffer = function (buffer) {
  12451. buffer.references--;
  12452. if (buffer.references === 0) {
  12453. this._gl.deleteBuffer(buffer);
  12454. return true;
  12455. }
  12456. return false;
  12457. };
  12458. Engine.prototype.createInstancesBuffer = function (capacity) {
  12459. var buffer = this._gl.createBuffer();
  12460. if (!buffer) {
  12461. throw new Error("Unable to create instance buffer");
  12462. }
  12463. buffer.capacity = capacity;
  12464. this.bindArrayBuffer(buffer);
  12465. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12466. return buffer;
  12467. };
  12468. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12469. this._gl.deleteBuffer(buffer);
  12470. };
  12471. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12472. this.bindArrayBuffer(instancesBuffer);
  12473. if (data) {
  12474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12475. }
  12476. if (offsetLocations[0].index !== undefined) {
  12477. var stride = 0;
  12478. for (var i = 0; i < offsetLocations.length; i++) {
  12479. var ai = offsetLocations[i];
  12480. stride += ai.attributeSize * 4;
  12481. }
  12482. for (var i = 0; i < offsetLocations.length; i++) {
  12483. var ai = offsetLocations[i];
  12484. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12485. this._gl.enableVertexAttribArray(ai.index);
  12486. this._vertexAttribArraysEnabled[ai.index] = true;
  12487. }
  12488. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12489. this._gl.vertexAttribDivisor(ai.index, 1);
  12490. this._currentInstanceLocations.push(ai.index);
  12491. this._currentInstanceBuffers.push(instancesBuffer);
  12492. }
  12493. }
  12494. else {
  12495. for (var index = 0; index < 4; index++) {
  12496. var offsetLocation = offsetLocations[index];
  12497. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12498. this._gl.enableVertexAttribArray(offsetLocation);
  12499. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12500. }
  12501. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12502. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12503. this._currentInstanceLocations.push(offsetLocation);
  12504. this._currentInstanceBuffers.push(instancesBuffer);
  12505. }
  12506. }
  12507. };
  12508. Engine.prototype.applyStates = function () {
  12509. this._depthCullingState.apply(this._gl);
  12510. this._stencilState.apply(this._gl);
  12511. this._alphaState.apply(this._gl);
  12512. };
  12513. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12514. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12515. };
  12516. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12517. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12518. };
  12519. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12520. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12521. };
  12522. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12523. // Apply states
  12524. this.applyStates();
  12525. this._drawCalls.addCount(1, false);
  12526. // Render
  12527. var drawMode = this.DrawMode(fillMode);
  12528. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12529. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12530. if (instancesCount) {
  12531. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12532. }
  12533. else {
  12534. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12535. }
  12536. };
  12537. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12538. // Apply states
  12539. this.applyStates();
  12540. this._drawCalls.addCount(1, false);
  12541. var drawMode = this.DrawMode(fillMode);
  12542. if (instancesCount) {
  12543. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12544. }
  12545. else {
  12546. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12547. }
  12548. };
  12549. Engine.prototype.DrawMode = function (fillMode) {
  12550. switch (fillMode) {
  12551. // Triangle views
  12552. case BABYLON.Material.TriangleFillMode:
  12553. return this._gl.TRIANGLES;
  12554. case BABYLON.Material.PointFillMode:
  12555. return this._gl.POINTS;
  12556. case BABYLON.Material.WireFrameFillMode:
  12557. return this._gl.LINES;
  12558. // Draw modes
  12559. case BABYLON.Material.PointListDrawMode:
  12560. return this._gl.POINTS;
  12561. case BABYLON.Material.LineListDrawMode:
  12562. return this._gl.LINES;
  12563. case BABYLON.Material.LineLoopDrawMode:
  12564. return this._gl.LINE_LOOP;
  12565. case BABYLON.Material.LineStripDrawMode:
  12566. return this._gl.LINE_STRIP;
  12567. case BABYLON.Material.TriangleStripDrawMode:
  12568. return this._gl.TRIANGLE_STRIP;
  12569. case BABYLON.Material.TriangleFanDrawMode:
  12570. return this._gl.TRIANGLE_FAN;
  12571. default:
  12572. return this._gl.TRIANGLES;
  12573. }
  12574. };
  12575. // Shaders
  12576. Engine.prototype._releaseEffect = function (effect) {
  12577. if (this._compiledEffects[effect._key]) {
  12578. delete this._compiledEffects[effect._key];
  12579. this._deleteProgram(effect.getProgram());
  12580. }
  12581. };
  12582. Engine.prototype._deleteProgram = function (program) {
  12583. if (program) {
  12584. program.__SPECTOR_rebuildProgram = null;
  12585. if (program.transformFeedback) {
  12586. this.deleteTransformFeedback(program.transformFeedback);
  12587. program.transformFeedback = null;
  12588. }
  12589. this._gl.deleteProgram(program);
  12590. }
  12591. };
  12592. /**
  12593. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12594. * @param samplers An array of string used to represent textures
  12595. */
  12596. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12597. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12598. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12599. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12600. if (this._compiledEffects[name]) {
  12601. var compiledEffect = this._compiledEffects[name];
  12602. if (onCompiled && compiledEffect.isReady()) {
  12603. onCompiled(compiledEffect);
  12604. }
  12605. return compiledEffect;
  12606. }
  12607. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12608. effect._key = name;
  12609. this._compiledEffects[name] = effect;
  12610. return effect;
  12611. };
  12612. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12613. if (uniformsNames === void 0) { uniformsNames = []; }
  12614. if (samplers === void 0) { samplers = []; }
  12615. if (defines === void 0) { defines = ""; }
  12616. return this.createEffect({
  12617. vertex: "particles",
  12618. fragmentElement: fragmentName
  12619. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12620. };
  12621. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12622. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12623. context = context || this._gl;
  12624. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12625. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12626. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12627. };
  12628. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12629. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12630. context = context || this._gl;
  12631. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12632. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12633. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12634. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12635. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12636. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12637. return program;
  12638. };
  12639. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12640. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12641. var shaderProgram = context.createProgram();
  12642. if (!shaderProgram) {
  12643. throw new Error("Unable to create program");
  12644. }
  12645. context.attachShader(shaderProgram, vertexShader);
  12646. context.attachShader(shaderProgram, fragmentShader);
  12647. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12648. var transformFeedback = this.createTransformFeedback();
  12649. this.bindTransformFeedback(transformFeedback);
  12650. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12651. shaderProgram.transformFeedback = transformFeedback;
  12652. }
  12653. context.linkProgram(shaderProgram);
  12654. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12655. this.bindTransformFeedback(null);
  12656. }
  12657. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12658. if (!linked) {
  12659. context.validateProgram(shaderProgram);
  12660. var error = context.getProgramInfoLog(shaderProgram);
  12661. if (error) {
  12662. throw new Error(error);
  12663. }
  12664. }
  12665. context.deleteShader(vertexShader);
  12666. context.deleteShader(fragmentShader);
  12667. return shaderProgram;
  12668. };
  12669. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12670. var results = new Array();
  12671. for (var index = 0; index < uniformsNames.length; index++) {
  12672. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12673. }
  12674. return results;
  12675. };
  12676. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12677. var results = [];
  12678. for (var index = 0; index < attributesNames.length; index++) {
  12679. try {
  12680. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12681. }
  12682. catch (e) {
  12683. results.push(-1);
  12684. }
  12685. }
  12686. return results;
  12687. };
  12688. Engine.prototype.enableEffect = function (effect) {
  12689. if (!effect) {
  12690. return;
  12691. }
  12692. // Use program
  12693. this.bindSamplers(effect);
  12694. this._currentEffect = effect;
  12695. if (effect.onBind) {
  12696. effect.onBind(effect);
  12697. }
  12698. effect.onBindObservable.notifyObservers(effect);
  12699. };
  12700. Engine.prototype.setIntArray = function (uniform, array) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform1iv(uniform, array);
  12704. };
  12705. Engine.prototype.setIntArray2 = function (uniform, array) {
  12706. if (!uniform || array.length % 2 !== 0)
  12707. return;
  12708. this._gl.uniform2iv(uniform, array);
  12709. };
  12710. Engine.prototype.setIntArray3 = function (uniform, array) {
  12711. if (!uniform || array.length % 3 !== 0)
  12712. return;
  12713. this._gl.uniform3iv(uniform, array);
  12714. };
  12715. Engine.prototype.setIntArray4 = function (uniform, array) {
  12716. if (!uniform || array.length % 4 !== 0)
  12717. return;
  12718. this._gl.uniform4iv(uniform, array);
  12719. };
  12720. Engine.prototype.setFloatArray = function (uniform, array) {
  12721. if (!uniform)
  12722. return;
  12723. this._gl.uniform1fv(uniform, array);
  12724. };
  12725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12726. if (!uniform || array.length % 2 !== 0)
  12727. return;
  12728. this._gl.uniform2fv(uniform, array);
  12729. };
  12730. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12731. if (!uniform || array.length % 3 !== 0)
  12732. return;
  12733. this._gl.uniform3fv(uniform, array);
  12734. };
  12735. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12736. if (!uniform || array.length % 4 !== 0)
  12737. return;
  12738. this._gl.uniform4fv(uniform, array);
  12739. };
  12740. Engine.prototype.setArray = function (uniform, array) {
  12741. if (!uniform)
  12742. return;
  12743. this._gl.uniform1fv(uniform, array);
  12744. };
  12745. Engine.prototype.setArray2 = function (uniform, array) {
  12746. if (!uniform || array.length % 2 !== 0)
  12747. return;
  12748. this._gl.uniform2fv(uniform, array);
  12749. };
  12750. Engine.prototype.setArray3 = function (uniform, array) {
  12751. if (!uniform || array.length % 3 !== 0)
  12752. return;
  12753. this._gl.uniform3fv(uniform, array);
  12754. };
  12755. Engine.prototype.setArray4 = function (uniform, array) {
  12756. if (!uniform || array.length % 4 !== 0)
  12757. return;
  12758. this._gl.uniform4fv(uniform, array);
  12759. };
  12760. Engine.prototype.setMatrices = function (uniform, matrices) {
  12761. if (!uniform)
  12762. return;
  12763. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12764. };
  12765. Engine.prototype.setMatrix = function (uniform, matrix) {
  12766. if (!uniform)
  12767. return;
  12768. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12769. };
  12770. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12771. if (!uniform)
  12772. return;
  12773. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12774. };
  12775. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12776. if (!uniform)
  12777. return;
  12778. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12779. };
  12780. Engine.prototype.setInt = function (uniform, value) {
  12781. if (!uniform)
  12782. return;
  12783. this._gl.uniform1i(uniform, value);
  12784. };
  12785. Engine.prototype.setFloat = function (uniform, value) {
  12786. if (!uniform)
  12787. return;
  12788. this._gl.uniform1f(uniform, value);
  12789. };
  12790. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12791. if (!uniform)
  12792. return;
  12793. this._gl.uniform2f(uniform, x, y);
  12794. };
  12795. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12796. if (!uniform)
  12797. return;
  12798. this._gl.uniform3f(uniform, x, y, z);
  12799. };
  12800. Engine.prototype.setBool = function (uniform, bool) {
  12801. if (!uniform)
  12802. return;
  12803. this._gl.uniform1i(uniform, bool);
  12804. };
  12805. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12806. if (!uniform)
  12807. return;
  12808. this._gl.uniform4f(uniform, x, y, z, w);
  12809. };
  12810. Engine.prototype.setColor3 = function (uniform, color3) {
  12811. if (!uniform)
  12812. return;
  12813. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12814. };
  12815. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12816. if (!uniform)
  12817. return;
  12818. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12819. };
  12820. /**
  12821. * Sets a Color4 on a uniform variable
  12822. * @param uniform defines the uniform location
  12823. * @param color4 defines the value to be set
  12824. */
  12825. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12826. if (!uniform)
  12827. return;
  12828. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12829. };
  12830. // States
  12831. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12832. if (zOffset === void 0) { zOffset = 0; }
  12833. if (reverseSide === void 0) { reverseSide = false; }
  12834. // Culling
  12835. if (this._depthCullingState.cull !== culling || force) {
  12836. this._depthCullingState.cull = culling;
  12837. }
  12838. // Cull face
  12839. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12840. if (this._depthCullingState.cullFace !== cullFace || force) {
  12841. this._depthCullingState.cullFace = cullFace;
  12842. }
  12843. // Z offset
  12844. this.setZOffset(zOffset);
  12845. // Front face
  12846. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12847. if (this._depthCullingState.frontFace !== frontFace || force) {
  12848. this._depthCullingState.frontFace = frontFace;
  12849. }
  12850. };
  12851. Engine.prototype.setZOffset = function (value) {
  12852. this._depthCullingState.zOffset = value;
  12853. };
  12854. Engine.prototype.getZOffset = function () {
  12855. return this._depthCullingState.zOffset;
  12856. };
  12857. Engine.prototype.setDepthBuffer = function (enable) {
  12858. this._depthCullingState.depthTest = enable;
  12859. };
  12860. Engine.prototype.getDepthWrite = function () {
  12861. return this._depthCullingState.depthMask;
  12862. };
  12863. Engine.prototype.setDepthWrite = function (enable) {
  12864. this._depthCullingState.depthMask = enable;
  12865. };
  12866. Engine.prototype.setColorWrite = function (enable) {
  12867. this._gl.colorMask(enable, enable, enable, enable);
  12868. this._colorWrite = enable;
  12869. };
  12870. Engine.prototype.getColorWrite = function () {
  12871. return this._colorWrite;
  12872. };
  12873. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12874. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12875. };
  12876. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12877. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12878. if (this._alphaMode === mode) {
  12879. return;
  12880. }
  12881. switch (mode) {
  12882. case Engine.ALPHA_DISABLE:
  12883. this._alphaState.alphaBlend = false;
  12884. break;
  12885. case Engine.ALPHA_PREMULTIPLIED:
  12886. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12887. this._alphaState.alphaBlend = true;
  12888. break;
  12889. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12890. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12891. this._alphaState.alphaBlend = true;
  12892. break;
  12893. case Engine.ALPHA_COMBINE:
  12894. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12895. this._alphaState.alphaBlend = true;
  12896. break;
  12897. case Engine.ALPHA_ONEONE:
  12898. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12899. this._alphaState.alphaBlend = true;
  12900. break;
  12901. case Engine.ALPHA_ADD:
  12902. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12903. this._alphaState.alphaBlend = true;
  12904. break;
  12905. case Engine.ALPHA_SUBTRACT:
  12906. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12907. this._alphaState.alphaBlend = true;
  12908. break;
  12909. case Engine.ALPHA_MULTIPLY:
  12910. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12911. this._alphaState.alphaBlend = true;
  12912. break;
  12913. case Engine.ALPHA_MAXIMIZED:
  12914. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12915. this._alphaState.alphaBlend = true;
  12916. break;
  12917. case Engine.ALPHA_INTERPOLATE:
  12918. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12919. this._alphaState.alphaBlend = true;
  12920. break;
  12921. case Engine.ALPHA_SCREENMODE:
  12922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12923. this._alphaState.alphaBlend = true;
  12924. break;
  12925. }
  12926. if (!noDepthWriteChange) {
  12927. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12928. }
  12929. this._alphaMode = mode;
  12930. };
  12931. Engine.prototype.getAlphaMode = function () {
  12932. return this._alphaMode;
  12933. };
  12934. // Textures
  12935. Engine.prototype.wipeCaches = function (bruteForce) {
  12936. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12937. return;
  12938. }
  12939. this._currentEffect = null;
  12940. // 6/8/2017: deltakosh: Should not be required anymore.
  12941. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12942. if (bruteForce) {
  12943. this.resetTextureCache();
  12944. this._currentProgram = null;
  12945. this._stencilState.reset();
  12946. this._depthCullingState.reset();
  12947. this.setDepthFunctionToLessOrEqual();
  12948. this._alphaState.reset();
  12949. }
  12950. this._resetVertexBufferBinding();
  12951. this._cachedIndexBuffer = null;
  12952. this._cachedEffectForVertexBuffers = null;
  12953. this._unbindVertexArrayObject();
  12954. this.bindIndexBuffer(null);
  12955. };
  12956. /**
  12957. * Set the compressed texture format to use, based on the formats you have, and the formats
  12958. * supported by the hardware / browser.
  12959. *
  12960. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12961. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12962. * to API arguments needed to compressed textures. This puts the burden on the container
  12963. * generator to house the arcane code for determining these for current & future formats.
  12964. *
  12965. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12966. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12967. *
  12968. * Note: The result of this call is not taken into account when a texture is base64.
  12969. *
  12970. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12971. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12972. *
  12973. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12974. * @returns The extension selected.
  12975. */
  12976. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12977. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12978. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12979. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12980. return this._textureFormatInUse = this._texturesSupported[i];
  12981. }
  12982. }
  12983. }
  12984. // actively set format to nothing, to allow this to be called more than once
  12985. // and possibly fail the 2nd time
  12986. this._textureFormatInUse = null;
  12987. return null;
  12988. };
  12989. Engine.prototype._createTexture = function () {
  12990. var texture = this._gl.createTexture();
  12991. if (!texture) {
  12992. throw new Error("Unable to create texture");
  12993. }
  12994. return texture;
  12995. };
  12996. /**
  12997. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12998. * @param {string} urlArg- This contains one of the following:
  12999. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13000. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13001. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13002. *
  13003. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13004. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13005. * @param {Scene} scene- Needed for loading to the correct scene.
  13006. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13007. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13008. * @param {callback} onError- Optional callback to be called upon failure.
  13009. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13010. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13011. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13012. *
  13013. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13014. */
  13015. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13016. var _this = this;
  13017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13018. if (onLoad === void 0) { onLoad = null; }
  13019. if (onError === void 0) { onError = null; }
  13020. if (buffer === void 0) { buffer = null; }
  13021. if (fallBack === void 0) { fallBack = null; }
  13022. if (format === void 0) { format = null; }
  13023. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13024. var fromData = url.substr(0, 5) === "data:";
  13025. var fromBlob = url.substr(0, 5) === "blob:";
  13026. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13027. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13028. // establish the file extension, if possible
  13029. var lastDot = url.lastIndexOf('.');
  13030. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13031. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13032. var isTGA = (extension.indexOf(".tga") === 0);
  13033. // determine if a ktx file should be substituted
  13034. var isKTX = false;
  13035. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13036. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13037. isKTX = true;
  13038. }
  13039. if (scene) {
  13040. scene._addPendingData(texture);
  13041. }
  13042. texture.url = url;
  13043. texture.generateMipMaps = !noMipmap;
  13044. texture.samplingMode = samplingMode;
  13045. texture.invertY = invertY;
  13046. if (!this._doNotHandleContextLost) {
  13047. // Keep a link to the buffer only if we plan to handle context lost
  13048. texture._buffer = buffer;
  13049. }
  13050. var onLoadObserver = null;
  13051. if (onLoad && !fallBack) {
  13052. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13053. }
  13054. if (!fallBack)
  13055. this._internalTexturesCache.push(texture);
  13056. var onerror = function (message, exception) {
  13057. if (scene) {
  13058. scene._removePendingData(texture);
  13059. }
  13060. if (onLoadObserver) {
  13061. texture.onLoadedObservable.remove(onLoadObserver);
  13062. }
  13063. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13064. if (isKTX) {
  13065. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13066. }
  13067. else if (BABYLON.Tools.UseFallbackTexture) {
  13068. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13069. }
  13070. if (onError) {
  13071. onError(message || "Unknown error", exception);
  13072. }
  13073. };
  13074. var callback = null;
  13075. // processing for non-image formats
  13076. if (isKTX || isTGA || isDDS) {
  13077. if (isKTX) {
  13078. callback = function (data) {
  13079. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13080. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13081. ktx.uploadLevels(_this._gl, !noMipmap);
  13082. return false;
  13083. }, samplingMode);
  13084. };
  13085. }
  13086. else if (isTGA) {
  13087. callback = function (arrayBuffer) {
  13088. var data = new Uint8Array(arrayBuffer);
  13089. var header = BABYLON.TGATools.GetTGAHeader(data);
  13090. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13091. BABYLON.TGATools.UploadContent(_this._gl, data);
  13092. return false;
  13093. }, samplingMode);
  13094. };
  13095. }
  13096. else if (isDDS) {
  13097. callback = function (data) {
  13098. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13099. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13100. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13101. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13102. return false;
  13103. }, samplingMode);
  13104. };
  13105. }
  13106. if (!buffer) {
  13107. this._loadFile(url, function (data) {
  13108. if (callback) {
  13109. callback(data);
  13110. }
  13111. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13112. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13113. });
  13114. }
  13115. else {
  13116. if (callback) {
  13117. callback(buffer);
  13118. }
  13119. }
  13120. // image format processing
  13121. }
  13122. else {
  13123. var onload = function (img) {
  13124. if (fromBlob && !_this._doNotHandleContextLost) {
  13125. // We need to store the image if we need to rebuild the texture
  13126. // in case of a webgl context lost
  13127. texture._buffer = img;
  13128. }
  13129. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13130. var gl = _this._gl;
  13131. var isPot = (img.width === potWidth && img.height === potHeight);
  13132. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13133. if (isPot) {
  13134. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13135. return false;
  13136. }
  13137. // Using shaders to rescale because canvas.drawImage is lossy
  13138. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13139. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13140. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13145. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13146. _this._releaseTexture(source);
  13147. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13148. continuationCallback();
  13149. });
  13150. return true;
  13151. }, samplingMode);
  13152. };
  13153. if (!fromData || isBase64)
  13154. if (buffer instanceof HTMLImageElement) {
  13155. onload(buffer);
  13156. }
  13157. else {
  13158. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13159. }
  13160. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13161. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13162. else
  13163. onload(buffer);
  13164. }
  13165. return texture;
  13166. };
  13167. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13168. var _this = this;
  13169. var rtt = this.createRenderTargetTexture({
  13170. width: destination.width,
  13171. height: destination.height,
  13172. }, {
  13173. generateMipMaps: false,
  13174. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13175. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13176. generateDepthBuffer: false,
  13177. generateStencilBuffer: false
  13178. });
  13179. if (!this._rescalePostProcess) {
  13180. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13181. }
  13182. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13183. _this._rescalePostProcess.onApply = function (effect) {
  13184. effect._bindTexture("textureSampler", source);
  13185. };
  13186. var hostingScene = scene;
  13187. if (!hostingScene) {
  13188. hostingScene = _this.scenes[_this.scenes.length - 1];
  13189. }
  13190. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13191. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13192. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13193. _this.unBindFramebuffer(rtt);
  13194. _this._releaseTexture(rtt);
  13195. if (onComplete) {
  13196. onComplete();
  13197. }
  13198. });
  13199. };
  13200. Engine.prototype._getInternalFormat = function (format) {
  13201. var internalFormat = this._gl.RGBA;
  13202. switch (format) {
  13203. case Engine.TEXTUREFORMAT_ALPHA:
  13204. internalFormat = this._gl.ALPHA;
  13205. break;
  13206. case Engine.TEXTUREFORMAT_LUMINANCE:
  13207. internalFormat = this._gl.LUMINANCE;
  13208. break;
  13209. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13210. internalFormat = this._gl.LUMINANCE_ALPHA;
  13211. break;
  13212. case Engine.TEXTUREFORMAT_RGB:
  13213. case Engine.TEXTUREFORMAT_RGB32F:
  13214. internalFormat = this._gl.RGB;
  13215. break;
  13216. case Engine.TEXTUREFORMAT_RGBA:
  13217. case Engine.TEXTUREFORMAT_RGBA32F:
  13218. internalFormat = this._gl.RGBA;
  13219. break;
  13220. case Engine.TEXTUREFORMAT_R32F:
  13221. internalFormat = this._gl.RED;
  13222. break;
  13223. case Engine.TEXTUREFORMAT_RG32F:
  13224. internalFormat = this._gl.RG;
  13225. break;
  13226. }
  13227. return internalFormat;
  13228. };
  13229. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13230. if (compression === void 0) { compression = null; }
  13231. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13232. if (!texture) {
  13233. return;
  13234. }
  13235. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13236. var internalFormat = this._getInternalFormat(format);
  13237. var textureType = this._getWebGLTextureType(type);
  13238. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13239. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13240. if (!this._doNotHandleContextLost) {
  13241. texture._bufferView = data;
  13242. texture.format = format;
  13243. texture.type = type;
  13244. texture.invertY = invertY;
  13245. texture._compression = compression;
  13246. }
  13247. if (texture.width % 4 !== 0) {
  13248. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13249. }
  13250. if (compression && data) {
  13251. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13252. }
  13253. else {
  13254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13255. }
  13256. if (texture.generateMipMaps) {
  13257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13258. }
  13259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13260. // this.resetTextureCache();
  13261. texture.isReady = true;
  13262. };
  13263. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13264. if (compression === void 0) { compression = null; }
  13265. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13266. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13267. texture.baseWidth = width;
  13268. texture.baseHeight = height;
  13269. texture.width = width;
  13270. texture.height = height;
  13271. texture.format = format;
  13272. texture.generateMipMaps = generateMipMaps;
  13273. texture.samplingMode = samplingMode;
  13274. texture.invertY = invertY;
  13275. texture._compression = compression;
  13276. texture.type = type;
  13277. if (!this._doNotHandleContextLost) {
  13278. texture._bufferView = data;
  13279. }
  13280. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13281. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13282. // Filters
  13283. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13285. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13286. if (generateMipMaps) {
  13287. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13288. }
  13289. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13290. this._internalTexturesCache.push(texture);
  13291. return texture;
  13292. };
  13293. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13294. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13295. texture.baseWidth = width;
  13296. texture.baseHeight = height;
  13297. if (generateMipMaps) {
  13298. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13299. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13300. }
  13301. // this.resetTextureCache();
  13302. texture.width = width;
  13303. texture.height = height;
  13304. texture.isReady = false;
  13305. texture.generateMipMaps = generateMipMaps;
  13306. texture.samplingMode = samplingMode;
  13307. this.updateTextureSamplingMode(samplingMode, texture);
  13308. this._internalTexturesCache.push(texture);
  13309. return texture;
  13310. };
  13311. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13312. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13313. if (texture.isCube) {
  13314. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13315. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13316. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13318. }
  13319. else if (texture.is3D) {
  13320. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13321. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13322. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13323. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13324. }
  13325. else {
  13326. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13327. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13329. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13330. }
  13331. texture.samplingMode = samplingMode;
  13332. };
  13333. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13334. if (premulAlpha === void 0) { premulAlpha = false; }
  13335. if (!texture) {
  13336. return;
  13337. }
  13338. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13340. if (premulAlpha) {
  13341. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13342. }
  13343. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13345. if (texture.generateMipMaps) {
  13346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13347. }
  13348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13349. if (premulAlpha) {
  13350. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13351. }
  13352. texture.isReady = true;
  13353. };
  13354. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13355. if (!texture || texture._isDisabled) {
  13356. return;
  13357. }
  13358. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13359. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13360. try {
  13361. // Testing video texture support
  13362. if (this._videoTextureSupported === undefined) {
  13363. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13364. if (this._gl.getError() !== 0) {
  13365. this._videoTextureSupported = false;
  13366. }
  13367. else {
  13368. this._videoTextureSupported = true;
  13369. }
  13370. }
  13371. // Copy video through the current working canvas if video texture is not supported
  13372. if (!this._videoTextureSupported) {
  13373. if (!texture._workingCanvas) {
  13374. texture._workingCanvas = document.createElement("canvas");
  13375. var context = texture._workingCanvas.getContext("2d");
  13376. if (!context) {
  13377. throw new Error("Unable to get 2d context");
  13378. }
  13379. texture._workingContext = context;
  13380. texture._workingCanvas.width = texture.width;
  13381. texture._workingCanvas.height = texture.height;
  13382. }
  13383. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13385. }
  13386. else {
  13387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13388. }
  13389. if (texture.generateMipMaps) {
  13390. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13391. }
  13392. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13393. // this.resetTextureCache();
  13394. texture.isReady = true;
  13395. }
  13396. catch (ex) {
  13397. // Something unexpected
  13398. // Let's disable the texture
  13399. texture._isDisabled = true;
  13400. }
  13401. };
  13402. /**
  13403. * Updates a depth texture Comparison Mode and Function.
  13404. * If the comparison Function is equal to 0, the mode will be set to none.
  13405. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13406. * @param texture The texture to set the comparison function for
  13407. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13408. */
  13409. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13410. if (this.webGLVersion === 1) {
  13411. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13412. return;
  13413. }
  13414. var gl = this._gl;
  13415. if (texture.isCube) {
  13416. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13417. if (comparisonFunction === 0) {
  13418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13420. }
  13421. else {
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13424. }
  13425. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13426. }
  13427. else {
  13428. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13429. if (comparisonFunction === 0) {
  13430. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13432. }
  13433. else {
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13436. }
  13437. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13438. }
  13439. texture._comparisonFunction = comparisonFunction;
  13440. };
  13441. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13442. var width = size.width || size;
  13443. var height = size.height || size;
  13444. internalTexture.baseWidth = width;
  13445. internalTexture.baseHeight = height;
  13446. internalTexture.width = width;
  13447. internalTexture.height = height;
  13448. internalTexture.isReady = true;
  13449. internalTexture.samples = 1;
  13450. internalTexture.generateMipMaps = false;
  13451. internalTexture._generateDepthBuffer = true;
  13452. internalTexture._generateStencilBuffer = generateStencil;
  13453. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13454. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13455. internalTexture._comparisonFunction = comparisonFunction;
  13456. var gl = this._gl;
  13457. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13458. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13459. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13460. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13461. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13462. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13463. if (comparisonFunction === 0) {
  13464. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13465. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13466. }
  13467. else {
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13469. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13470. }
  13471. };
  13472. /**
  13473. * Creates a depth stencil texture.
  13474. * This is only available in WebGL 2 or with the depth texture extension available.
  13475. * @param size The size of face edge in the texture.
  13476. * @param options The options defining the texture.
  13477. * @returns The texture
  13478. */
  13479. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13480. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13481. if (!this._caps.depthTextureExtension) {
  13482. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13483. return internalTexture;
  13484. }
  13485. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13486. var gl = this._gl;
  13487. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13488. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13489. if (this.webGLVersion > 1) {
  13490. if (internalOptions.generateStencil) {
  13491. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13492. }
  13493. else {
  13494. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13495. }
  13496. }
  13497. else {
  13498. if (internalOptions.generateStencil) {
  13499. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13500. }
  13501. else {
  13502. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13503. }
  13504. }
  13505. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13506. return internalTexture;
  13507. };
  13508. /**
  13509. * Creates a depth stencil cube texture.
  13510. * This is only available in WebGL 2.
  13511. * @param size The size of face edge in the cube texture.
  13512. * @param options The options defining the cube texture.
  13513. * @returns The cube texture
  13514. */
  13515. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13516. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13517. internalTexture.isCube = true;
  13518. if (this.webGLVersion === 1) {
  13519. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13520. return internalTexture;
  13521. }
  13522. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13523. var gl = this._gl;
  13524. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13525. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13526. // Create the depth/stencil buffer
  13527. for (var face = 0; face < 6; face++) {
  13528. if (internalOptions.generateStencil) {
  13529. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13530. }
  13531. else {
  13532. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13533. }
  13534. }
  13535. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13536. return internalTexture;
  13537. };
  13538. /**
  13539. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13540. * @param renderTarget The render target to set the frame buffer for
  13541. */
  13542. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13543. // Create the framebuffer
  13544. var internalTexture = renderTarget.getInternalTexture();
  13545. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13546. return;
  13547. }
  13548. var gl = this._gl;
  13549. var depthStencilTexture = renderTarget.depthStencilTexture;
  13550. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13551. if (depthStencilTexture.isCube) {
  13552. if (depthStencilTexture._generateStencilBuffer) {
  13553. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13554. }
  13555. else {
  13556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13557. }
  13558. }
  13559. else {
  13560. if (depthStencilTexture._generateStencilBuffer) {
  13561. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13562. }
  13563. else {
  13564. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13565. }
  13566. }
  13567. this.bindUnboundFramebuffer(null);
  13568. };
  13569. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13570. var fullOptions = new RenderTargetCreationOptions();
  13571. if (options !== undefined && typeof options === "object") {
  13572. fullOptions.generateMipMaps = options.generateMipMaps;
  13573. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13574. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13575. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13576. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13577. }
  13578. else {
  13579. fullOptions.generateMipMaps = options;
  13580. fullOptions.generateDepthBuffer = true;
  13581. fullOptions.generateStencilBuffer = false;
  13582. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13583. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13584. }
  13585. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13586. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13587. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13588. }
  13589. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13590. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13591. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13592. }
  13593. var gl = this._gl;
  13594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13595. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13596. var width = size.width || size;
  13597. var height = size.height || size;
  13598. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13599. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13600. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13601. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13602. }
  13603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13607. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13608. // Create the framebuffer
  13609. var framebuffer = gl.createFramebuffer();
  13610. this.bindUnboundFramebuffer(framebuffer);
  13611. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13612. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13613. if (fullOptions.generateMipMaps) {
  13614. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13615. }
  13616. // Unbind
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13618. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13619. this.bindUnboundFramebuffer(null);
  13620. texture._framebuffer = framebuffer;
  13621. texture.baseWidth = width;
  13622. texture.baseHeight = height;
  13623. texture.width = width;
  13624. texture.height = height;
  13625. texture.isReady = true;
  13626. texture.samples = 1;
  13627. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13628. texture.samplingMode = fullOptions.samplingMode;
  13629. texture.type = fullOptions.type;
  13630. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13631. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13632. // this.resetTextureCache();
  13633. this._internalTexturesCache.push(texture);
  13634. return texture;
  13635. };
  13636. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13637. var generateMipMaps = false;
  13638. var generateDepthBuffer = true;
  13639. var generateStencilBuffer = false;
  13640. var generateDepthTexture = false;
  13641. var textureCount = 1;
  13642. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13643. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13644. var types = [], samplingModes = [];
  13645. if (options !== undefined) {
  13646. generateMipMaps = options.generateMipMaps;
  13647. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13648. generateStencilBuffer = options.generateStencilBuffer;
  13649. generateDepthTexture = options.generateDepthTexture;
  13650. textureCount = options.textureCount || 1;
  13651. if (options.types) {
  13652. types = options.types;
  13653. }
  13654. if (options.samplingModes) {
  13655. samplingModes = options.samplingModes;
  13656. }
  13657. }
  13658. var gl = this._gl;
  13659. // Create the framebuffer
  13660. var framebuffer = gl.createFramebuffer();
  13661. this.bindUnboundFramebuffer(framebuffer);
  13662. var width = size.width || size;
  13663. var height = size.height || size;
  13664. var textures = [];
  13665. var attachments = [];
  13666. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13667. for (var i = 0; i < textureCount; i++) {
  13668. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13669. var type = types[i] || defaultType;
  13670. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13671. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13672. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13673. }
  13674. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13675. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13676. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13677. }
  13678. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13679. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13680. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13681. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13682. }
  13683. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13684. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13685. textures.push(texture);
  13686. attachments.push(attachment);
  13687. gl.activeTexture(gl["TEXTURE" + i]);
  13688. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13693. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13694. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13695. if (generateMipMaps) {
  13696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13697. }
  13698. // Unbind
  13699. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13700. texture._framebuffer = framebuffer;
  13701. texture._depthStencilBuffer = depthStencilBuffer;
  13702. texture.baseWidth = width;
  13703. texture.baseHeight = height;
  13704. texture.width = width;
  13705. texture.height = height;
  13706. texture.isReady = true;
  13707. texture.samples = 1;
  13708. texture.generateMipMaps = generateMipMaps;
  13709. texture.samplingMode = samplingMode;
  13710. texture.type = type;
  13711. texture._generateDepthBuffer = generateDepthBuffer;
  13712. texture._generateStencilBuffer = generateStencilBuffer;
  13713. texture._attachments = attachments;
  13714. this._internalTexturesCache.push(texture);
  13715. }
  13716. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13717. // Depth texture
  13718. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13719. gl.activeTexture(gl.TEXTURE0);
  13720. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13725. 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);
  13726. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13727. depthTexture._framebuffer = framebuffer;
  13728. depthTexture.baseWidth = width;
  13729. depthTexture.baseHeight = height;
  13730. depthTexture.width = width;
  13731. depthTexture.height = height;
  13732. depthTexture.isReady = true;
  13733. depthTexture.samples = 1;
  13734. depthTexture.generateMipMaps = generateMipMaps;
  13735. depthTexture.samplingMode = gl.NEAREST;
  13736. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13737. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13738. textures.push(depthTexture);
  13739. this._internalTexturesCache.push(depthTexture);
  13740. }
  13741. gl.drawBuffers(attachments);
  13742. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13743. this.bindUnboundFramebuffer(null);
  13744. this.resetTextureCache();
  13745. return textures;
  13746. };
  13747. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13748. if (samples === void 0) { samples = 1; }
  13749. var depthStencilBuffer = null;
  13750. var gl = this._gl;
  13751. // Create the depth/stencil buffer
  13752. if (generateStencilBuffer) {
  13753. depthStencilBuffer = gl.createRenderbuffer();
  13754. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13755. if (samples > 1) {
  13756. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13757. }
  13758. else {
  13759. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13760. }
  13761. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13762. }
  13763. else if (generateDepthBuffer) {
  13764. depthStencilBuffer = gl.createRenderbuffer();
  13765. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13766. if (samples > 1) {
  13767. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13768. }
  13769. else {
  13770. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13771. }
  13772. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13773. }
  13774. return depthStencilBuffer;
  13775. };
  13776. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13777. if (this.webGLVersion < 2 || !texture) {
  13778. return 1;
  13779. }
  13780. if (texture.samples === samples) {
  13781. return samples;
  13782. }
  13783. var gl = this._gl;
  13784. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13785. // Dispose previous render buffers
  13786. if (texture._depthStencilBuffer) {
  13787. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13788. texture._depthStencilBuffer = null;
  13789. }
  13790. if (texture._MSAAFramebuffer) {
  13791. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13792. texture._MSAAFramebuffer = null;
  13793. }
  13794. if (texture._MSAARenderBuffer) {
  13795. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13796. texture._MSAARenderBuffer = null;
  13797. }
  13798. if (samples > 1) {
  13799. var framebuffer = gl.createFramebuffer();
  13800. if (!framebuffer) {
  13801. throw new Error("Unable to create multi sampled framebuffer");
  13802. }
  13803. texture._MSAAFramebuffer = framebuffer;
  13804. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13805. var colorRenderbuffer = gl.createRenderbuffer();
  13806. if (!colorRenderbuffer) {
  13807. throw new Error("Unable to create multi sampled framebuffer");
  13808. }
  13809. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13810. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13811. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13812. texture._MSAARenderBuffer = colorRenderbuffer;
  13813. }
  13814. else {
  13815. this.bindUnboundFramebuffer(texture._framebuffer);
  13816. }
  13817. texture.samples = samples;
  13818. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13819. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13820. this.bindUnboundFramebuffer(null);
  13821. return samples;
  13822. };
  13823. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13824. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13825. return 1;
  13826. }
  13827. if (textures[0].samples === samples) {
  13828. return samples;
  13829. }
  13830. var gl = this._gl;
  13831. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13832. // Dispose previous render buffers
  13833. if (textures[0]._depthStencilBuffer) {
  13834. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13835. textures[0]._depthStencilBuffer = null;
  13836. }
  13837. if (textures[0]._MSAAFramebuffer) {
  13838. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13839. textures[0]._MSAAFramebuffer = null;
  13840. }
  13841. for (var i = 0; i < textures.length; i++) {
  13842. if (textures[i]._MSAARenderBuffer) {
  13843. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13844. textures[i]._MSAARenderBuffer = null;
  13845. }
  13846. }
  13847. if (samples > 1) {
  13848. var framebuffer = gl.createFramebuffer();
  13849. if (!framebuffer) {
  13850. throw new Error("Unable to create multi sampled framebuffer");
  13851. }
  13852. this.bindUnboundFramebuffer(framebuffer);
  13853. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13854. var attachments = [];
  13855. for (var i = 0; i < textures.length; i++) {
  13856. var texture = textures[i];
  13857. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13858. var colorRenderbuffer = gl.createRenderbuffer();
  13859. if (!colorRenderbuffer) {
  13860. throw new Error("Unable to create multi sampled framebuffer");
  13861. }
  13862. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13863. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13864. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13865. texture._MSAAFramebuffer = framebuffer;
  13866. texture._MSAARenderBuffer = colorRenderbuffer;
  13867. texture.samples = samples;
  13868. texture._depthStencilBuffer = depthStencilBuffer;
  13869. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13870. attachments.push(attachment);
  13871. }
  13872. gl.drawBuffers(attachments);
  13873. }
  13874. else {
  13875. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13876. }
  13877. this.bindUnboundFramebuffer(null);
  13878. return samples;
  13879. };
  13880. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13881. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13882. };
  13883. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13884. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13885. };
  13886. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13887. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13888. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13890. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13891. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13892. }
  13893. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13894. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13895. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13896. }
  13897. var gl = this._gl;
  13898. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13900. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13901. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13902. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13903. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13904. }
  13905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13909. for (var face = 0; face < 6; face++) {
  13910. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13911. }
  13912. // Create the framebuffer
  13913. var framebuffer = gl.createFramebuffer();
  13914. this.bindUnboundFramebuffer(framebuffer);
  13915. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13916. // MipMaps
  13917. if (fullOptions.generateMipMaps) {
  13918. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13919. }
  13920. // Unbind
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13922. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13923. this.bindUnboundFramebuffer(null);
  13924. texture._framebuffer = framebuffer;
  13925. texture.width = size;
  13926. texture.height = size;
  13927. texture.isReady = true;
  13928. texture.isCube = true;
  13929. texture.samples = 1;
  13930. texture.generateMipMaps = fullOptions.generateMipMaps;
  13931. texture.samplingMode = fullOptions.samplingMode;
  13932. texture.type = fullOptions.type;
  13933. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13934. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13935. this._internalTexturesCache.push(texture);
  13936. return texture;
  13937. };
  13938. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13939. var _this = this;
  13940. if (onLoad === void 0) { onLoad = null; }
  13941. if (onError === void 0) { onError = null; }
  13942. if (forcedExtension === void 0) { forcedExtension = null; }
  13943. var callback = function (loadData) {
  13944. if (!loadData) {
  13945. if (onLoad) {
  13946. onLoad(null);
  13947. }
  13948. return;
  13949. }
  13950. var texture = loadData.texture;
  13951. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13952. texture._lodGenerationScale = scale;
  13953. texture._lodGenerationOffset = offset;
  13954. if (_this._caps.textureLOD) {
  13955. // Do not add extra process if texture lod is supported.
  13956. if (onLoad) {
  13957. onLoad(texture);
  13958. }
  13959. return;
  13960. }
  13961. var mipSlices = 3;
  13962. var gl = _this._gl;
  13963. var width = loadData.width;
  13964. if (!width) {
  13965. return;
  13966. }
  13967. var textures = [];
  13968. for (var i = 0; i < mipSlices; i++) {
  13969. //compute LOD from even spacing in smoothness (matching shader calculation)
  13970. var smoothness = i / (mipSlices - 1);
  13971. var roughness = 1 - smoothness;
  13972. var minLODIndex = offset; // roughness = 0
  13973. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13974. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13975. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13976. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13977. glTextureFromLod.isCube = true;
  13978. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13983. if (loadData.isDDS) {
  13984. var info = loadData.info;
  13985. var data = loadData.data;
  13986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13987. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13988. }
  13989. else {
  13990. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13991. }
  13992. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13993. // Wrap in a base texture for easy binding.
  13994. var lodTexture = new BABYLON.BaseTexture(scene);
  13995. lodTexture.isCube = true;
  13996. lodTexture._texture = glTextureFromLod;
  13997. glTextureFromLod.isReady = true;
  13998. textures.push(lodTexture);
  13999. }
  14000. texture._lodTextureHigh = textures[2];
  14001. texture._lodTextureMid = textures[1];
  14002. texture._lodTextureLow = textures[0];
  14003. if (onLoad) {
  14004. onLoad(texture);
  14005. }
  14006. };
  14007. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14008. };
  14009. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14010. var _this = this;
  14011. if (onLoad === void 0) { onLoad = null; }
  14012. if (onError === void 0) { onError = null; }
  14013. if (forcedExtension === void 0) { forcedExtension = null; }
  14014. var gl = this._gl;
  14015. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14016. texture.isCube = true;
  14017. texture.url = rootUrl;
  14018. texture.generateMipMaps = !noMipmap;
  14019. if (!this._doNotHandleContextLost) {
  14020. texture._extension = forcedExtension;
  14021. texture._files = files;
  14022. }
  14023. var isKTX = false;
  14024. var isDDS = false;
  14025. var lastDot = rootUrl.lastIndexOf('.');
  14026. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14027. if (this._textureFormatInUse) {
  14028. extension = this._textureFormatInUse;
  14029. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14030. isKTX = true;
  14031. }
  14032. else {
  14033. isDDS = (extension === ".dds");
  14034. }
  14035. var onerror = function (request, exception) {
  14036. if (onError && request) {
  14037. onError(request.status + " " + request.statusText, exception);
  14038. }
  14039. };
  14040. if (isKTX) {
  14041. this._loadFile(rootUrl, function (data) {
  14042. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14043. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14046. ktx.uploadLevels(_this._gl, !noMipmap);
  14047. _this.setCubeMapTextureParams(gl, loadMipmap);
  14048. texture.width = ktx.pixelWidth;
  14049. texture.height = ktx.pixelHeight;
  14050. texture.isReady = true;
  14051. }, undefined, undefined, true, onerror);
  14052. }
  14053. else if (isDDS) {
  14054. if (files && files.length === 6) {
  14055. this._cascadeLoadFiles(scene, function (imgs) {
  14056. var info;
  14057. var loadMipmap = false;
  14058. var width = 0;
  14059. for (var index = 0; index < imgs.length; index++) {
  14060. var data = imgs[index];
  14061. info = BABYLON.DDSTools.GetDDSInfo(data);
  14062. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14064. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14065. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14066. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14067. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14068. }
  14069. texture.width = info.width;
  14070. texture.height = info.height;
  14071. texture.type = info.textureType;
  14072. width = info.width;
  14073. }
  14074. _this.setCubeMapTextureParams(gl, loadMipmap);
  14075. texture.isReady = true;
  14076. if (onLoad) {
  14077. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14078. }
  14079. }, files, onError);
  14080. }
  14081. else {
  14082. this._loadFile(rootUrl, function (data) {
  14083. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. _this.setCubeMapTextureParams(gl, loadMipmap);
  14092. texture.width = info.width;
  14093. texture.height = info.height;
  14094. texture.isReady = true;
  14095. texture.type = info.textureType;
  14096. if (onLoad) {
  14097. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14098. }
  14099. }, undefined, undefined, true, onerror);
  14100. }
  14101. }
  14102. else {
  14103. if (!files) {
  14104. throw new Error("Cannot load cubemap because files were not defined");
  14105. }
  14106. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14107. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14108. var height = width;
  14109. _this._prepareWorkingCanvas();
  14110. if (!_this._workingCanvas || !_this._workingContext) {
  14111. return;
  14112. }
  14113. _this._workingCanvas.width = width;
  14114. _this._workingCanvas.height = height;
  14115. var faces = [
  14116. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14117. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14118. ];
  14119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14120. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14121. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14122. for (var index = 0; index < faces.length; index++) {
  14123. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14124. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14125. }
  14126. if (!noMipmap) {
  14127. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14128. }
  14129. _this.setCubeMapTextureParams(gl, !noMipmap);
  14130. texture.width = width;
  14131. texture.height = height;
  14132. texture.isReady = true;
  14133. if (format) {
  14134. texture.format = format;
  14135. }
  14136. texture.onLoadedObservable.notifyObservers(texture);
  14137. texture.onLoadedObservable.clear();
  14138. if (onLoad) {
  14139. onLoad();
  14140. }
  14141. }, files, onError);
  14142. }
  14143. this._internalTexturesCache.push(texture);
  14144. return texture;
  14145. };
  14146. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14152. // this.resetTextureCache();
  14153. };
  14154. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14155. if (compression === void 0) { compression = null; }
  14156. if (level === void 0) { level = 0; }
  14157. texture._bufferViewArray = data;
  14158. texture.format = format;
  14159. texture.type = type;
  14160. texture.invertY = invertY;
  14161. texture._compression = compression;
  14162. var gl = this._gl;
  14163. var textureType = this._getWebGLTextureType(type);
  14164. var internalFormat = this._getInternalFormat(format);
  14165. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14166. var needConversion = false;
  14167. if (internalFormat === gl.RGB) {
  14168. internalFormat = gl.RGBA;
  14169. needConversion = true;
  14170. }
  14171. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14173. if (texture.width % 4 !== 0) {
  14174. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14175. }
  14176. // Data are known to be in +X +Y +Z -X -Y -Z
  14177. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14178. var faceData = data[faceIndex];
  14179. if (compression) {
  14180. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14181. }
  14182. else {
  14183. if (needConversion) {
  14184. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14185. }
  14186. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14187. }
  14188. }
  14189. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14190. if (isPot && texture.generateMipMaps && level === 0) {
  14191. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14194. // this.resetTextureCache();
  14195. texture.isReady = true;
  14196. };
  14197. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14198. if (compression === void 0) { compression = null; }
  14199. var gl = this._gl;
  14200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14201. texture.isCube = true;
  14202. texture.generateMipMaps = generateMipMaps;
  14203. texture.format = format;
  14204. texture.type = type;
  14205. if (!this._doNotHandleContextLost) {
  14206. texture._bufferViewArray = data;
  14207. }
  14208. var textureType = this._getWebGLTextureType(type);
  14209. var internalFormat = this._getInternalFormat(format);
  14210. if (internalFormat === gl.RGB) {
  14211. internalFormat = gl.RGBA;
  14212. }
  14213. var width = size;
  14214. var height = width;
  14215. texture.width = width;
  14216. texture.height = height;
  14217. // Double check on POT to generate Mips.
  14218. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14219. if (!isPot) {
  14220. generateMipMaps = false;
  14221. }
  14222. // Upload data if needed. The texture won't be ready until then.
  14223. if (data) {
  14224. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14225. }
  14226. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14227. // Filters
  14228. if (data && generateMipMaps) {
  14229. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14230. }
  14231. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14234. }
  14235. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14238. }
  14239. else {
  14240. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14241. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14242. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14243. }
  14244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14247. return texture;
  14248. };
  14249. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14250. var _this = this;
  14251. if (onLoad === void 0) { onLoad = null; }
  14252. if (onError === void 0) { onError = null; }
  14253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14254. if (invertY === void 0) { invertY = false; }
  14255. var gl = this._gl;
  14256. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14257. scene._addPendingData(texture);
  14258. texture.url = url;
  14259. this._internalTexturesCache.push(texture);
  14260. var onerror = function (request, exception) {
  14261. scene._removePendingData(texture);
  14262. if (onError && request) {
  14263. onError(request.status + " " + request.statusText, exception);
  14264. }
  14265. };
  14266. var internalCallback = function (data) {
  14267. var width = texture.width;
  14268. var faceDataArrays = callback(data);
  14269. if (!faceDataArrays) {
  14270. return;
  14271. }
  14272. if (mipmmapGenerator) {
  14273. var textureType = _this._getWebGLTextureType(type);
  14274. var internalFormat = _this._getInternalFormat(format);
  14275. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14276. var needConversion = false;
  14277. if (internalFormat === gl.RGB) {
  14278. internalFormat = gl.RGBA;
  14279. needConversion = true;
  14280. }
  14281. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14282. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14283. var mipData = mipmmapGenerator(faceDataArrays);
  14284. for (var level = 0; level < mipData.length; level++) {
  14285. var mipSize = width >> level;
  14286. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14287. var mipFaceData = mipData[level][faceIndex];
  14288. if (needConversion) {
  14289. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14290. }
  14291. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14292. }
  14293. }
  14294. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14295. }
  14296. else {
  14297. texture.generateMipMaps = !noMipmap;
  14298. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14299. }
  14300. texture.isReady = true;
  14301. // this.resetTextureCache();
  14302. scene._removePendingData(texture);
  14303. if (onLoad) {
  14304. onLoad();
  14305. }
  14306. };
  14307. this._loadFile(url, function (data) {
  14308. internalCallback(data);
  14309. }, undefined, scene.database, true, onerror);
  14310. return texture;
  14311. };
  14312. ;
  14313. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14314. if (compression === void 0) { compression = null; }
  14315. var internalFormat = this._getInternalFormat(format);
  14316. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14317. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14318. if (!this._doNotHandleContextLost) {
  14319. texture._bufferView = data;
  14320. texture.format = format;
  14321. texture.invertY = invertY;
  14322. texture._compression = compression;
  14323. }
  14324. if (texture.width % 4 !== 0) {
  14325. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14326. }
  14327. if (compression && data) {
  14328. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14329. }
  14330. else {
  14331. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14332. }
  14333. if (texture.generateMipMaps) {
  14334. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14335. }
  14336. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14337. // this.resetTextureCache();
  14338. texture.isReady = true;
  14339. };
  14340. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14341. if (compression === void 0) { compression = null; }
  14342. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14343. texture.baseWidth = width;
  14344. texture.baseHeight = height;
  14345. texture.baseDepth = depth;
  14346. texture.width = width;
  14347. texture.height = height;
  14348. texture.depth = depth;
  14349. texture.format = format;
  14350. texture.generateMipMaps = generateMipMaps;
  14351. texture.samplingMode = samplingMode;
  14352. texture.is3D = true;
  14353. if (!this._doNotHandleContextLost) {
  14354. texture._bufferView = data;
  14355. }
  14356. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14358. // Filters
  14359. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14360. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14361. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14362. if (generateMipMaps) {
  14363. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14364. }
  14365. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14366. this._internalTexturesCache.push(texture);
  14367. return texture;
  14368. };
  14369. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14370. var gl = this._gl;
  14371. if (!gl) {
  14372. return;
  14373. }
  14374. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14377. if (!noMipmap && !isCompressed) {
  14378. gl.generateMipmap(gl.TEXTURE_2D);
  14379. }
  14380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14381. // this.resetTextureCache();
  14382. if (scene) {
  14383. scene._removePendingData(texture);
  14384. }
  14385. texture.onLoadedObservable.notifyObservers(texture);
  14386. texture.onLoadedObservable.clear();
  14387. };
  14388. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14389. var _this = this;
  14390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14391. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14392. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14393. var gl = this._gl;
  14394. if (!gl) {
  14395. return;
  14396. }
  14397. if (!texture._webGLTexture) {
  14398. // this.resetTextureCache();
  14399. if (scene) {
  14400. scene._removePendingData(texture);
  14401. }
  14402. return;
  14403. }
  14404. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14405. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14406. texture.baseWidth = width;
  14407. texture.baseHeight = height;
  14408. texture.width = potWidth;
  14409. texture.height = potHeight;
  14410. texture.isReady = true;
  14411. if (processFunction(potWidth, potHeight, function () {
  14412. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14413. })) {
  14414. // Returning as texture needs extra async steps
  14415. return;
  14416. }
  14417. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14418. };
  14419. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14420. // Create new RGBA data container.
  14421. var rgbaData;
  14422. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14423. rgbaData = new Float32Array(width * height * 4);
  14424. }
  14425. else {
  14426. rgbaData = new Uint32Array(width * height * 4);
  14427. }
  14428. // Convert each pixel.
  14429. for (var x = 0; x < width; x++) {
  14430. for (var y = 0; y < height; y++) {
  14431. var index = (y * width + x) * 3;
  14432. var newIndex = (y * width + x) * 4;
  14433. // Map Old Value to new value.
  14434. rgbaData[newIndex + 0] = rgbData[index + 0];
  14435. rgbaData[newIndex + 1] = rgbData[index + 1];
  14436. rgbaData[newIndex + 2] = rgbData[index + 2];
  14437. // Add fully opaque alpha channel.
  14438. rgbaData[newIndex + 3] = 1;
  14439. }
  14440. }
  14441. return rgbaData;
  14442. };
  14443. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14444. var gl = this._gl;
  14445. if (texture._framebuffer) {
  14446. gl.deleteFramebuffer(texture._framebuffer);
  14447. texture._framebuffer = null;
  14448. }
  14449. if (texture._depthStencilBuffer) {
  14450. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14451. texture._depthStencilBuffer = null;
  14452. }
  14453. if (texture._MSAAFramebuffer) {
  14454. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14455. texture._MSAAFramebuffer = null;
  14456. }
  14457. if (texture._MSAARenderBuffer) {
  14458. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14459. texture._MSAARenderBuffer = null;
  14460. }
  14461. };
  14462. Engine.prototype._releaseTexture = function (texture) {
  14463. var gl = this._gl;
  14464. this._releaseFramebufferObjects(texture);
  14465. gl.deleteTexture(texture._webGLTexture);
  14466. // Unbind channels
  14467. this.unbindAllTextures();
  14468. var index = this._internalTexturesCache.indexOf(texture);
  14469. if (index !== -1) {
  14470. this._internalTexturesCache.splice(index, 1);
  14471. }
  14472. // Integrated fixed lod samplers.
  14473. if (texture._lodTextureHigh) {
  14474. texture._lodTextureHigh.dispose();
  14475. }
  14476. if (texture._lodTextureMid) {
  14477. texture._lodTextureMid.dispose();
  14478. }
  14479. if (texture._lodTextureLow) {
  14480. texture._lodTextureLow.dispose();
  14481. }
  14482. };
  14483. Engine.prototype.setProgram = function (program) {
  14484. if (this._currentProgram !== program) {
  14485. this._gl.useProgram(program);
  14486. this._currentProgram = program;
  14487. }
  14488. };
  14489. Engine.prototype.bindSamplers = function (effect) {
  14490. this.setProgram(effect.getProgram());
  14491. var samplers = effect.getSamplers();
  14492. for (var index = 0; index < samplers.length; index++) {
  14493. var uniform = effect.getUniform(samplers[index]);
  14494. if (uniform) {
  14495. this._boundUniforms[index] = uniform;
  14496. }
  14497. }
  14498. this._currentEffect = null;
  14499. };
  14500. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14501. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14502. return;
  14503. }
  14504. // Remove
  14505. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14506. // Bind last to it
  14507. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14508. // Bind to dummy
  14509. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14510. };
  14511. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14512. if (!internalTexture) {
  14513. return -1;
  14514. }
  14515. internalTexture._initialSlot = channel;
  14516. if (this.disableTextureBindingOptimization) {
  14517. if (channel !== internalTexture._designatedSlot) {
  14518. this._textureCollisions.addCount(1, false);
  14519. }
  14520. }
  14521. else {
  14522. if (channel !== internalTexture._designatedSlot) {
  14523. if (internalTexture._designatedSlot > -1) {
  14524. return internalTexture._designatedSlot;
  14525. }
  14526. else {
  14527. // No slot for this texture, let's pick a new one (if we find a free slot)
  14528. if (this._nextFreeTextureSlots.length) {
  14529. return this._nextFreeTextureSlots[0];
  14530. }
  14531. // We need to recycle the oldest bound texture, sorry.
  14532. this._textureCollisions.addCount(1, false);
  14533. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14534. }
  14535. }
  14536. }
  14537. return channel;
  14538. };
  14539. Engine.prototype._linkTrackers = function (previous, next) {
  14540. previous.next = next;
  14541. next.previous = previous;
  14542. };
  14543. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14544. var currentSlot = internalTexture._designatedSlot;
  14545. if (currentSlot === -1) {
  14546. return -1;
  14547. }
  14548. internalTexture._designatedSlot = -1;
  14549. if (this.disableTextureBindingOptimization) {
  14550. return -1;
  14551. }
  14552. // Remove from bound list
  14553. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14554. // Free the slot
  14555. this._boundTexturesCache[currentSlot] = null;
  14556. this._nextFreeTextureSlots.push(currentSlot);
  14557. return currentSlot;
  14558. };
  14559. Engine.prototype._activateCurrentTexture = function () {
  14560. if (this._currentTextureChannel !== this._activeChannel) {
  14561. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14562. this._currentTextureChannel = this._activeChannel;
  14563. }
  14564. };
  14565. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14566. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14567. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14568. this._activeChannel = texture._designatedSlot;
  14569. }
  14570. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14571. var isTextureForRendering = texture && texture._initialSlot > -1;
  14572. if (currentTextureBound !== texture) {
  14573. if (currentTextureBound) {
  14574. this._removeDesignatedSlot(currentTextureBound);
  14575. }
  14576. this._activateCurrentTexture();
  14577. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14578. this._boundTexturesCache[this._activeChannel] = texture;
  14579. if (texture) {
  14580. if (!this.disableTextureBindingOptimization) {
  14581. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14582. if (slotIndex > -1) {
  14583. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14584. }
  14585. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14586. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14587. }
  14588. texture._designatedSlot = this._activeChannel;
  14589. }
  14590. }
  14591. else if (forTextureDataUpdate) {
  14592. this._activateCurrentTexture();
  14593. }
  14594. if (isTextureForRendering && !forTextureDataUpdate) {
  14595. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14596. }
  14597. };
  14598. Engine.prototype._bindTexture = function (channel, texture) {
  14599. if (channel < 0) {
  14600. return;
  14601. }
  14602. if (texture) {
  14603. channel = this._getCorrectTextureChannel(channel, texture);
  14604. }
  14605. this._activeChannel = channel;
  14606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14607. };
  14608. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14609. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14610. };
  14611. Engine.prototype.unbindAllTextures = function () {
  14612. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14613. this._activeChannel = channel;
  14614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14615. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14616. if (this.webGLVersion > 1) {
  14617. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14618. }
  14619. }
  14620. };
  14621. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14622. if (channel < 0) {
  14623. return;
  14624. }
  14625. if (uniform) {
  14626. this._boundUniforms[channel] = uniform;
  14627. }
  14628. this._setTexture(channel, texture);
  14629. };
  14630. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14631. var uniform = this._boundUniforms[sourceSlot];
  14632. if (uniform._currentState === destination) {
  14633. return;
  14634. }
  14635. this._gl.uniform1i(uniform, destination);
  14636. uniform._currentState = destination;
  14637. };
  14638. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14639. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14640. // Not ready?
  14641. if (!texture) {
  14642. if (this._boundTexturesCache[channel] != null) {
  14643. this._activeChannel = channel;
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14645. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14646. if (this.webGLVersion > 1) {
  14647. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14648. }
  14649. }
  14650. return false;
  14651. }
  14652. // Video
  14653. if (texture.video) {
  14654. this._activeChannel = channel;
  14655. texture.update();
  14656. }
  14657. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14658. texture.delayLoad();
  14659. return false;
  14660. }
  14661. var internalTexture;
  14662. if (texture.isReady()) {
  14663. internalTexture = texture.getInternalTexture();
  14664. }
  14665. else if (texture.isCube) {
  14666. internalTexture = this.emptyCubeTexture;
  14667. }
  14668. else if (texture.is3D) {
  14669. internalTexture = this.emptyTexture3D;
  14670. }
  14671. else {
  14672. internalTexture = this.emptyTexture;
  14673. }
  14674. if (!isPartOfTextureArray) {
  14675. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14676. }
  14677. if (this._boundTexturesCache[channel] === internalTexture) {
  14678. this._moveBoundTextureOnTop(internalTexture);
  14679. if (!isPartOfTextureArray) {
  14680. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14681. }
  14682. return false;
  14683. }
  14684. this._activeChannel = channel;
  14685. if (internalTexture && internalTexture.is3D) {
  14686. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14687. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14688. internalTexture._cachedWrapU = texture.wrapU;
  14689. switch (texture.wrapU) {
  14690. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14691. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14692. break;
  14693. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14694. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14695. break;
  14696. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14697. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14698. break;
  14699. }
  14700. }
  14701. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14702. internalTexture._cachedWrapV = texture.wrapV;
  14703. switch (texture.wrapV) {
  14704. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14705. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14706. break;
  14707. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14708. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14709. break;
  14710. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14711. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14712. break;
  14713. }
  14714. }
  14715. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14716. internalTexture._cachedWrapR = texture.wrapR;
  14717. switch (texture.wrapR) {
  14718. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14719. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14720. break;
  14721. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14722. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14723. break;
  14724. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14725. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14726. break;
  14727. }
  14728. }
  14729. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14730. }
  14731. else if (internalTexture && internalTexture.isCube) {
  14732. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14733. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14734. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14735. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14736. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14737. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14738. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14739. }
  14740. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14741. }
  14742. else {
  14743. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14744. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14745. internalTexture._cachedWrapU = texture.wrapU;
  14746. switch (texture.wrapU) {
  14747. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14748. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14749. break;
  14750. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14751. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14752. break;
  14753. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14755. break;
  14756. }
  14757. }
  14758. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14759. internalTexture._cachedWrapV = texture.wrapV;
  14760. switch (texture.wrapV) {
  14761. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14762. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14763. break;
  14764. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14765. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14766. break;
  14767. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14768. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14769. break;
  14770. }
  14771. }
  14772. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14773. }
  14774. return true;
  14775. };
  14776. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14777. if (channel < 0 || !uniform) {
  14778. return;
  14779. }
  14780. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14781. this._textureUnits = new Int32Array(textures.length);
  14782. }
  14783. for (var i = 0; i < textures.length; i++) {
  14784. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14785. }
  14786. this._gl.uniform1iv(uniform, this._textureUnits);
  14787. for (var index = 0; index < textures.length; index++) {
  14788. this._setTexture(this._textureUnits[index], textures[index], true);
  14789. }
  14790. };
  14791. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14792. var internalTexture = texture.getInternalTexture();
  14793. if (!internalTexture) {
  14794. return;
  14795. }
  14796. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14797. var value = texture.anisotropicFilteringLevel;
  14798. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14799. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14800. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14801. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14802. }
  14803. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14804. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14805. internalTexture._cachedAnisotropicFilteringLevel = value;
  14806. }
  14807. };
  14808. Engine.prototype.readPixels = function (x, y, width, height) {
  14809. var data = new Uint8Array(height * width * 4);
  14810. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14811. return data;
  14812. };
  14813. /**
  14814. * Add an externaly attached data from its key.
  14815. * This method call will fail and return false, if such key already exists.
  14816. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14817. * @param key the unique key that identifies the data
  14818. * @param data the data object to associate to the key for this Engine instance
  14819. * @return true if no such key were already present and the data was added successfully, false otherwise
  14820. */
  14821. Engine.prototype.addExternalData = function (key, data) {
  14822. if (!this._externalData) {
  14823. this._externalData = new BABYLON.StringDictionary();
  14824. }
  14825. return this._externalData.add(key, data);
  14826. };
  14827. /**
  14828. * Get an externaly attached data from its key
  14829. * @param key the unique key that identifies the data
  14830. * @return the associated data, if present (can be null), or undefined if not present
  14831. */
  14832. Engine.prototype.getExternalData = function (key) {
  14833. if (!this._externalData) {
  14834. this._externalData = new BABYLON.StringDictionary();
  14835. }
  14836. return this._externalData.get(key);
  14837. };
  14838. /**
  14839. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14840. * @param key the unique key that identifies the data
  14841. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14842. * @return the associated data, can be null if the factory returned null.
  14843. */
  14844. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14845. if (!this._externalData) {
  14846. this._externalData = new BABYLON.StringDictionary();
  14847. }
  14848. return this._externalData.getOrAddWithFactory(key, factory);
  14849. };
  14850. /**
  14851. * Remove an externaly attached data from the Engine instance
  14852. * @param key the unique key that identifies the data
  14853. * @return true if the data was successfully removed, false if it doesn't exist
  14854. */
  14855. Engine.prototype.removeExternalData = function (key) {
  14856. if (!this._externalData) {
  14857. this._externalData = new BABYLON.StringDictionary();
  14858. }
  14859. return this._externalData.remove(key);
  14860. };
  14861. Engine.prototype.unbindAllAttributes = function () {
  14862. if (this._mustWipeVertexAttributes) {
  14863. this._mustWipeVertexAttributes = false;
  14864. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14865. this._gl.disableVertexAttribArray(i);
  14866. this._vertexAttribArraysEnabled[i] = false;
  14867. this._currentBufferPointers[i].active = false;
  14868. }
  14869. return;
  14870. }
  14871. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14872. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14873. continue;
  14874. }
  14875. this._gl.disableVertexAttribArray(i);
  14876. this._vertexAttribArraysEnabled[i] = false;
  14877. this._currentBufferPointers[i].active = false;
  14878. }
  14879. };
  14880. Engine.prototype.releaseEffects = function () {
  14881. for (var name in this._compiledEffects) {
  14882. this._deleteProgram(this._compiledEffects[name]._program);
  14883. }
  14884. this._compiledEffects = {};
  14885. };
  14886. // Dispose
  14887. Engine.prototype.dispose = function () {
  14888. this.hideLoadingUI();
  14889. this.stopRenderLoop();
  14890. // Release postProcesses
  14891. while (this.postProcesses.length) {
  14892. this.postProcesses[0].dispose();
  14893. }
  14894. // Empty texture
  14895. if (this._emptyTexture) {
  14896. this._releaseTexture(this._emptyTexture);
  14897. this._emptyTexture = null;
  14898. }
  14899. if (this._emptyCubeTexture) {
  14900. this._releaseTexture(this._emptyCubeTexture);
  14901. this._emptyCubeTexture = null;
  14902. }
  14903. // Rescale PP
  14904. if (this._rescalePostProcess) {
  14905. this._rescalePostProcess.dispose();
  14906. }
  14907. // Release scenes
  14908. while (this.scenes.length) {
  14909. this.scenes[0].dispose();
  14910. }
  14911. // Release audio engine
  14912. if (Engine.audioEngine) {
  14913. Engine.audioEngine.dispose();
  14914. }
  14915. // Release effects
  14916. this.releaseEffects();
  14917. // Unbind
  14918. this.unbindAllAttributes();
  14919. if (this._dummyFramebuffer) {
  14920. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14921. }
  14922. //WebVR
  14923. this.disableVR();
  14924. // Events
  14925. if (BABYLON.Tools.IsWindowObjectExist()) {
  14926. window.removeEventListener("blur", this._onBlur);
  14927. window.removeEventListener("focus", this._onFocus);
  14928. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14929. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14930. if (this._renderingCanvas) {
  14931. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14932. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14933. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14934. if (!this._doNotHandleContextLost) {
  14935. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14936. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14937. }
  14938. }
  14939. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14940. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14941. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14942. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14943. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14944. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14945. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14946. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14947. if (this._onVrDisplayConnect) {
  14948. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14949. if (this._onVrDisplayDisconnect) {
  14950. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14951. }
  14952. if (this._onVrDisplayPresentChange) {
  14953. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14954. }
  14955. this._onVrDisplayConnect = null;
  14956. this._onVrDisplayDisconnect = null;
  14957. }
  14958. }
  14959. // Remove from Instances
  14960. var index = Engine.Instances.indexOf(this);
  14961. if (index >= 0) {
  14962. Engine.Instances.splice(index, 1);
  14963. }
  14964. this._workingCanvas = null;
  14965. this._workingContext = null;
  14966. this._currentBufferPointers = [];
  14967. this._renderingCanvas = null;
  14968. this._currentProgram = null;
  14969. this._bindedRenderFunction = null;
  14970. this.onResizeObservable.clear();
  14971. this.onCanvasBlurObservable.clear();
  14972. this.onCanvasFocusObservable.clear();
  14973. this.onCanvasPointerOutObservable.clear();
  14974. this.onBeginFrameObservable.clear();
  14975. this.onEndFrameObservable.clear();
  14976. BABYLON.Effect.ResetCache();
  14977. // Abort active requests
  14978. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14979. var request = _a[_i];
  14980. request.abort();
  14981. }
  14982. };
  14983. // Loading screen
  14984. Engine.prototype.displayLoadingUI = function () {
  14985. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14986. return;
  14987. }
  14988. var loadingScreen = this.loadingScreen;
  14989. if (loadingScreen) {
  14990. loadingScreen.displayLoadingUI();
  14991. }
  14992. };
  14993. Engine.prototype.hideLoadingUI = function () {
  14994. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14995. return;
  14996. }
  14997. var loadingScreen = this.loadingScreen;
  14998. if (loadingScreen) {
  14999. loadingScreen.hideLoadingUI();
  15000. }
  15001. };
  15002. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15003. get: function () {
  15004. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15005. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15006. return this._loadingScreen;
  15007. },
  15008. set: function (loadingScreen) {
  15009. this._loadingScreen = loadingScreen;
  15010. },
  15011. enumerable: true,
  15012. configurable: true
  15013. });
  15014. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15015. set: function (text) {
  15016. this.loadingScreen.loadingUIText = text;
  15017. },
  15018. enumerable: true,
  15019. configurable: true
  15020. });
  15021. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15022. set: function (color) {
  15023. this.loadingScreen.loadingUIBackgroundColor = color;
  15024. },
  15025. enumerable: true,
  15026. configurable: true
  15027. });
  15028. Engine.prototype.attachContextLostEvent = function (callback) {
  15029. if (this._renderingCanvas) {
  15030. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15031. }
  15032. };
  15033. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15034. if (this._renderingCanvas) {
  15035. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15036. }
  15037. };
  15038. Engine.prototype.getVertexShaderSource = function (program) {
  15039. var shaders = this._gl.getAttachedShaders(program);
  15040. if (!shaders) {
  15041. return null;
  15042. }
  15043. return this._gl.getShaderSource(shaders[0]);
  15044. };
  15045. Engine.prototype.getFragmentShaderSource = function (program) {
  15046. var shaders = this._gl.getAttachedShaders(program);
  15047. if (!shaders) {
  15048. return null;
  15049. }
  15050. return this._gl.getShaderSource(shaders[1]);
  15051. };
  15052. Engine.prototype.getError = function () {
  15053. return this._gl.getError();
  15054. };
  15055. // FPS
  15056. Engine.prototype.getFps = function () {
  15057. return this._fps;
  15058. };
  15059. Engine.prototype.getDeltaTime = function () {
  15060. return this._deltaTime;
  15061. };
  15062. Engine.prototype._measureFps = function () {
  15063. this._performanceMonitor.sampleFrame();
  15064. this._fps = this._performanceMonitor.averageFPS;
  15065. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15066. };
  15067. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15068. if (faceIndex === void 0) { faceIndex = -1; }
  15069. var gl = this._gl;
  15070. if (!this._dummyFramebuffer) {
  15071. var dummy = gl.createFramebuffer();
  15072. if (!dummy) {
  15073. throw new Error("Unable to create dummy framebuffer");
  15074. }
  15075. this._dummyFramebuffer = dummy;
  15076. }
  15077. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15078. if (faceIndex > -1) {
  15079. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15080. }
  15081. else {
  15082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15083. }
  15084. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15085. var buffer;
  15086. switch (readType) {
  15087. case gl.UNSIGNED_BYTE:
  15088. buffer = new Uint8Array(4 * width * height);
  15089. readType = gl.UNSIGNED_BYTE;
  15090. break;
  15091. default:
  15092. buffer = new Float32Array(4 * width * height);
  15093. readType = gl.FLOAT;
  15094. break;
  15095. }
  15096. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15097. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15098. return buffer;
  15099. };
  15100. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15101. if (this._webGLVersion > 1) {
  15102. return this._caps.colorBufferFloat;
  15103. }
  15104. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15105. };
  15106. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15107. if (this._webGLVersion > 1) {
  15108. return this._caps.colorBufferFloat;
  15109. }
  15110. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15111. };
  15112. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15113. Engine.prototype._canRenderToFramebuffer = function (type) {
  15114. var gl = this._gl;
  15115. //clear existing errors
  15116. while (gl.getError() !== gl.NO_ERROR) { }
  15117. var successful = true;
  15118. var texture = gl.createTexture();
  15119. gl.bindTexture(gl.TEXTURE_2D, texture);
  15120. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15123. var fb = gl.createFramebuffer();
  15124. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15126. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15127. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15128. successful = successful && (gl.getError() === gl.NO_ERROR);
  15129. //try render by clearing frame buffer's color buffer
  15130. if (successful) {
  15131. gl.clear(gl.COLOR_BUFFER_BIT);
  15132. successful = successful && (gl.getError() === gl.NO_ERROR);
  15133. }
  15134. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15135. if (successful) {
  15136. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15137. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15138. var readFormat = gl.RGBA;
  15139. var readType = gl.UNSIGNED_BYTE;
  15140. var buffer = new Uint8Array(4);
  15141. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15142. successful = successful && (gl.getError() === gl.NO_ERROR);
  15143. }
  15144. //clean up
  15145. gl.deleteTexture(texture);
  15146. gl.deleteFramebuffer(fb);
  15147. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15148. //clear accumulated errors
  15149. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15150. return successful;
  15151. };
  15152. Engine.prototype._getWebGLTextureType = function (type) {
  15153. if (type === Engine.TEXTURETYPE_FLOAT) {
  15154. return this._gl.FLOAT;
  15155. }
  15156. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15157. // Add Half Float Constant.
  15158. return this._gl.HALF_FLOAT_OES;
  15159. }
  15160. return this._gl.UNSIGNED_BYTE;
  15161. };
  15162. ;
  15163. /** @ignore */
  15164. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15165. if (this._webGLVersion === 1) {
  15166. return this._gl.RGBA;
  15167. }
  15168. if (type === Engine.TEXTURETYPE_FLOAT) {
  15169. if (format) {
  15170. switch (format) {
  15171. case Engine.TEXTUREFORMAT_R32F:
  15172. return this._gl.R32F;
  15173. case Engine.TEXTUREFORMAT_RG32F:
  15174. return this._gl.RG32F;
  15175. case Engine.TEXTUREFORMAT_RGB32F:
  15176. return this._gl.RGB32F;
  15177. }
  15178. }
  15179. return this._gl.RGBA32F;
  15180. }
  15181. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15182. return this._gl.RGBA16F;
  15183. }
  15184. return this._gl.RGBA;
  15185. };
  15186. ;
  15187. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15188. if (type === Engine.TEXTURETYPE_FLOAT) {
  15189. return this._gl.RGBA32F;
  15190. }
  15191. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15192. return this._gl.RGBA16F;
  15193. }
  15194. return this._gl.RGBA8;
  15195. };
  15196. ;
  15197. Engine.prototype.createQuery = function () {
  15198. return this._gl.createQuery();
  15199. };
  15200. Engine.prototype.deleteQuery = function (query) {
  15201. this._gl.deleteQuery(query);
  15202. return this;
  15203. };
  15204. Engine.prototype.isQueryResultAvailable = function (query) {
  15205. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15206. };
  15207. Engine.prototype.getQueryResult = function (query) {
  15208. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15209. };
  15210. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15211. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15212. this._gl.beginQuery(glAlgorithm, query);
  15213. return this;
  15214. };
  15215. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15216. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15217. this._gl.endQuery(glAlgorithm);
  15218. return this;
  15219. };
  15220. /* Time queries */
  15221. Engine.prototype._createTimeQuery = function () {
  15222. var timerQuery = this._caps.timerQuery;
  15223. if (timerQuery.createQueryEXT) {
  15224. return timerQuery.createQueryEXT();
  15225. }
  15226. return this.createQuery();
  15227. };
  15228. Engine.prototype._deleteTimeQuery = function (query) {
  15229. var timerQuery = this._caps.timerQuery;
  15230. if (timerQuery.deleteQueryEXT) {
  15231. timerQuery.deleteQueryEXT(query);
  15232. return;
  15233. }
  15234. this.deleteQuery(query);
  15235. };
  15236. Engine.prototype._getTimeQueryResult = function (query) {
  15237. var timerQuery = this._caps.timerQuery;
  15238. if (timerQuery.getQueryObjectEXT) {
  15239. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15240. }
  15241. return this.getQueryResult(query);
  15242. };
  15243. Engine.prototype._getTimeQueryAvailability = function (query) {
  15244. var timerQuery = this._caps.timerQuery;
  15245. if (timerQuery.getQueryObjectEXT) {
  15246. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15247. }
  15248. return this.isQueryResultAvailable(query);
  15249. };
  15250. Engine.prototype.startTimeQuery = function () {
  15251. var timerQuery = this._caps.timerQuery;
  15252. if (!timerQuery) {
  15253. return null;
  15254. }
  15255. var token = new BABYLON._TimeToken();
  15256. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15257. if (this._caps.canUseTimestampForTimerQuery) {
  15258. token._startTimeQuery = this._createTimeQuery();
  15259. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15260. }
  15261. else {
  15262. if (this._currentNonTimestampToken) {
  15263. return this._currentNonTimestampToken;
  15264. }
  15265. token._timeElapsedQuery = this._createTimeQuery();
  15266. if (timerQuery.beginQueryEXT) {
  15267. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15268. }
  15269. else {
  15270. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15271. }
  15272. this._currentNonTimestampToken = token;
  15273. }
  15274. return token;
  15275. };
  15276. Engine.prototype.endTimeQuery = function (token) {
  15277. var timerQuery = this._caps.timerQuery;
  15278. if (!timerQuery || !token) {
  15279. return -1;
  15280. }
  15281. if (this._caps.canUseTimestampForTimerQuery) {
  15282. if (!token._startTimeQuery) {
  15283. return -1;
  15284. }
  15285. if (!token._endTimeQuery) {
  15286. token._endTimeQuery = this._createTimeQuery();
  15287. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15288. }
  15289. }
  15290. else if (!token._timeElapsedQueryEnded) {
  15291. if (!token._timeElapsedQuery) {
  15292. return -1;
  15293. }
  15294. if (timerQuery.endQueryEXT) {
  15295. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15296. }
  15297. else {
  15298. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15299. }
  15300. token._timeElapsedQueryEnded = true;
  15301. }
  15302. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15303. var available = false;
  15304. if (token._endTimeQuery) {
  15305. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15306. }
  15307. else if (token._timeElapsedQuery) {
  15308. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15309. }
  15310. if (available && !disjoint) {
  15311. var result = 0;
  15312. if (this._caps.canUseTimestampForTimerQuery) {
  15313. if (!token._startTimeQuery || !token._endTimeQuery) {
  15314. return -1;
  15315. }
  15316. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15317. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15318. result = timeEnd - timeStart;
  15319. this._deleteTimeQuery(token._startTimeQuery);
  15320. this._deleteTimeQuery(token._endTimeQuery);
  15321. token._startTimeQuery = null;
  15322. token._endTimeQuery = null;
  15323. }
  15324. else {
  15325. if (!token._timeElapsedQuery) {
  15326. return -1;
  15327. }
  15328. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15329. this._deleteTimeQuery(token._timeElapsedQuery);
  15330. token._timeElapsedQuery = null;
  15331. token._timeElapsedQueryEnded = false;
  15332. this._currentNonTimestampToken = null;
  15333. }
  15334. return result;
  15335. }
  15336. return -1;
  15337. };
  15338. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15339. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15340. };
  15341. // Transform feedback
  15342. Engine.prototype.createTransformFeedback = function () {
  15343. return this._gl.createTransformFeedback();
  15344. };
  15345. Engine.prototype.deleteTransformFeedback = function (value) {
  15346. this._gl.deleteTransformFeedback(value);
  15347. };
  15348. Engine.prototype.bindTransformFeedback = function (value) {
  15349. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15350. };
  15351. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15352. if (usePoints === void 0) { usePoints = true; }
  15353. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15354. };
  15355. Engine.prototype.endTransformFeedback = function () {
  15356. this._gl.endTransformFeedback();
  15357. };
  15358. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15359. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15360. };
  15361. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15362. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15363. };
  15364. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15365. var _this = this;
  15366. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15367. this._activeRequests.push(request);
  15368. request.onCompleteObservable.add(function (request) {
  15369. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15370. });
  15371. return request;
  15372. };
  15373. /** @ignore */
  15374. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15375. var _this = this;
  15376. return new Promise(function (resolve, reject) {
  15377. _this._loadFile(url, function (data) {
  15378. resolve(data);
  15379. }, undefined, database, useArrayBuffer, function (request, exception) {
  15380. reject(exception);
  15381. });
  15382. });
  15383. };
  15384. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15385. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15386. var onload = function (data) {
  15387. loadedFiles[index] = data;
  15388. loadedFiles._internalCount++;
  15389. if (loadedFiles._internalCount === 6) {
  15390. onfinish(loadedFiles);
  15391. }
  15392. };
  15393. var onerror = function (request, exception) {
  15394. if (onErrorCallBack && request) {
  15395. onErrorCallBack(request.status + " " + request.statusText, exception);
  15396. }
  15397. };
  15398. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15399. };
  15400. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15401. if (onError === void 0) { onError = null; }
  15402. var loadedFiles = [];
  15403. loadedFiles._internalCount = 0;
  15404. for (var index = 0; index < 6; index++) {
  15405. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15406. }
  15407. };
  15408. // Statics
  15409. Engine.isSupported = function () {
  15410. try {
  15411. var tempcanvas = document.createElement("canvas");
  15412. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15413. return gl != null && !!window.WebGLRenderingContext;
  15414. }
  15415. catch (e) {
  15416. return false;
  15417. }
  15418. };
  15419. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15420. Engine.ExceptionList = [
  15421. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15422. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15423. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15424. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15425. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15426. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15427. ];
  15428. Engine.Instances = new Array();
  15429. // Const statics
  15430. Engine._ALPHA_DISABLE = 0;
  15431. Engine._ALPHA_ADD = 1;
  15432. Engine._ALPHA_COMBINE = 2;
  15433. Engine._ALPHA_SUBTRACT = 3;
  15434. Engine._ALPHA_MULTIPLY = 4;
  15435. Engine._ALPHA_MAXIMIZED = 5;
  15436. Engine._ALPHA_ONEONE = 6;
  15437. Engine._ALPHA_PREMULTIPLIED = 7;
  15438. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15439. Engine._ALPHA_INTERPOLATE = 9;
  15440. Engine._ALPHA_SCREENMODE = 10;
  15441. Engine._DELAYLOADSTATE_NONE = 0;
  15442. Engine._DELAYLOADSTATE_LOADED = 1;
  15443. Engine._DELAYLOADSTATE_LOADING = 2;
  15444. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15445. Engine._TEXTUREFORMAT_ALPHA = 0;
  15446. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15447. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15448. Engine._TEXTUREFORMAT_RGB = 4;
  15449. Engine._TEXTUREFORMAT_RGBA = 5;
  15450. Engine._TEXTUREFORMAT_R32F = 6;
  15451. Engine._TEXTUREFORMAT_RG32F = 7;
  15452. Engine._TEXTUREFORMAT_RGB32F = 8;
  15453. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15454. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15455. Engine._TEXTURETYPE_FLOAT = 1;
  15456. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15457. // Depht or Stencil test Constants.
  15458. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15459. 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.
  15460. 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.
  15461. 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.
  15462. 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.
  15463. 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.
  15464. 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.
  15465. 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.
  15466. // Stencil Actions Constants.
  15467. Engine._KEEP = 0x1E00;
  15468. Engine._REPLACE = 0x1E01;
  15469. Engine._INCR = 0x1E02;
  15470. Engine._DECR = 0x1E03;
  15471. Engine._INVERT = 0x150A;
  15472. Engine._INCR_WRAP = 0x8507;
  15473. Engine._DECR_WRAP = 0x8508;
  15474. // Texture rescaling mode
  15475. Engine._SCALEMODE_FLOOR = 1;
  15476. Engine._SCALEMODE_NEAREST = 2;
  15477. Engine._SCALEMODE_CEILING = 3;
  15478. // Updatable statics so stick with vars here
  15479. Engine.CollisionsEpsilon = 0.001;
  15480. Engine.CodeRepository = "src/";
  15481. Engine.ShadersRepository = "src/Shaders/";
  15482. return Engine;
  15483. }());
  15484. BABYLON.Engine = Engine;
  15485. })(BABYLON || (BABYLON = {}));
  15486. //# sourceMappingURL=babylon.engine.js.map
  15487. var BABYLON;
  15488. (function (BABYLON) {
  15489. /**
  15490. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15491. */
  15492. var Node = /** @class */ (function () {
  15493. /**
  15494. * Creates a new Node
  15495. * @param {string} name - the name and id to be given to this node
  15496. * @param {BABYLON.Scene} the scene this node will be added to
  15497. */
  15498. function Node(name, scene) {
  15499. if (scene === void 0) { scene = null; }
  15500. /**
  15501. * Gets or sets a string used to store user defined state for the node
  15502. */
  15503. this.state = "";
  15504. /**
  15505. * Gets or sets an object used to store user defined information for the node
  15506. */
  15507. this.metadata = null;
  15508. /**
  15509. * Gets or sets a boolean used to define if the node must be serialized
  15510. */
  15511. this.doNotSerialize = false;
  15512. /** @ignore */
  15513. this._isDisposed = false;
  15514. /**
  15515. * Gets a list of {BABYLON.Animation} associated with the node
  15516. */
  15517. this.animations = new Array();
  15518. this._ranges = {};
  15519. this._isEnabled = true;
  15520. this._isReady = true;
  15521. /** @ignore */
  15522. this._currentRenderId = -1;
  15523. this._parentRenderId = -1;
  15524. this._animationPropertiesOverride = null;
  15525. /**
  15526. * An event triggered when the mesh is disposed
  15527. * @type {BABYLON.Observable}
  15528. */
  15529. this.onDisposeObservable = new BABYLON.Observable();
  15530. // Behaviors
  15531. this._behaviors = new Array();
  15532. this.name = name;
  15533. this.id = name;
  15534. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15535. this.uniqueId = this._scene.getUniqueId();
  15536. this._initCache();
  15537. }
  15538. /**
  15539. * Gets a boolean indicating if the node has been disposed
  15540. * @returns true if the node was disposed
  15541. */
  15542. Node.prototype.isDisposed = function () {
  15543. return this._isDisposed;
  15544. };
  15545. Object.defineProperty(Node.prototype, "parent", {
  15546. get: function () {
  15547. return this._parentNode;
  15548. },
  15549. /**
  15550. * Gets or sets the parent of the node
  15551. */
  15552. set: function (parent) {
  15553. if (this._parentNode === parent) {
  15554. return;
  15555. }
  15556. // Remove self from list of children of parent
  15557. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15558. var index = this._parentNode._children.indexOf(this);
  15559. if (index !== -1) {
  15560. this._parentNode._children.splice(index, 1);
  15561. }
  15562. }
  15563. // Store new parent
  15564. this._parentNode = parent;
  15565. // Add as child to new parent
  15566. if (this._parentNode) {
  15567. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15568. this._parentNode._children = new Array();
  15569. }
  15570. this._parentNode._children.push(this);
  15571. }
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15577. /**
  15578. * Gets or sets the animation properties override
  15579. */
  15580. get: function () {
  15581. return this._animationPropertiesOverride;
  15582. },
  15583. set: function (value) {
  15584. this._animationPropertiesOverride = value;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. /**
  15590. * Gets a string idenfifying the name of the class
  15591. * @returns "Node" string
  15592. */
  15593. Node.prototype.getClassName = function () {
  15594. return "Node";
  15595. };
  15596. Object.defineProperty(Node.prototype, "onDispose", {
  15597. /**
  15598. * Sets a callback that will be raised when the node will be disposed
  15599. */
  15600. set: function (callback) {
  15601. if (this._onDisposeObserver) {
  15602. this.onDisposeObservable.remove(this._onDisposeObserver);
  15603. }
  15604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15605. },
  15606. enumerable: true,
  15607. configurable: true
  15608. });
  15609. /**
  15610. * Gets the scene of the node
  15611. * @returns a {BABYLON.Scene}
  15612. */
  15613. Node.prototype.getScene = function () {
  15614. return this._scene;
  15615. };
  15616. /**
  15617. * Gets the engine of the node
  15618. * @returns a {BABYLON.Engine}
  15619. */
  15620. Node.prototype.getEngine = function () {
  15621. return this._scene.getEngine();
  15622. };
  15623. /**
  15624. * Attach a behavior to the node
  15625. * @see http://doc.babylonjs.com/features/behaviour
  15626. * @param behavior defines the behavior to attach
  15627. * @returns the current Node
  15628. */
  15629. Node.prototype.addBehavior = function (behavior) {
  15630. var _this = this;
  15631. var index = this._behaviors.indexOf(behavior);
  15632. if (index !== -1) {
  15633. return this;
  15634. }
  15635. behavior.init();
  15636. if (this._scene.isLoading) {
  15637. // We defer the attach when the scene will be loaded
  15638. var observer = this._scene.onDataLoadedObservable.add(function () {
  15639. behavior.attach(_this);
  15640. setTimeout(function () {
  15641. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15642. _this._scene.onDataLoadedObservable.remove(observer);
  15643. }, 0);
  15644. });
  15645. }
  15646. else {
  15647. behavior.attach(this);
  15648. }
  15649. this._behaviors.push(behavior);
  15650. return this;
  15651. };
  15652. /**
  15653. * Remove an attached behavior
  15654. * @see http://doc.babylonjs.com/features/behaviour
  15655. * @param behavior defines the behavior to attach
  15656. * @returns the current Node
  15657. */
  15658. Node.prototype.removeBehavior = function (behavior) {
  15659. var index = this._behaviors.indexOf(behavior);
  15660. if (index === -1) {
  15661. return this;
  15662. }
  15663. this._behaviors[index].detach();
  15664. this._behaviors.splice(index, 1);
  15665. return this;
  15666. };
  15667. Object.defineProperty(Node.prototype, "behaviors", {
  15668. /**
  15669. * Gets the list of attached behaviors
  15670. * @see http://doc.babylonjs.com/features/behaviour
  15671. */
  15672. get: function () {
  15673. return this._behaviors;
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. /**
  15679. * Gets an attached behavior by name
  15680. * @param name defines the name of the behavior to look for
  15681. * @see http://doc.babylonjs.com/features/behaviour
  15682. * @returns null if behavior was not found else the requested behavior
  15683. */
  15684. Node.prototype.getBehaviorByName = function (name) {
  15685. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15686. var behavior = _a[_i];
  15687. if (behavior.name === name) {
  15688. return behavior;
  15689. }
  15690. }
  15691. return null;
  15692. };
  15693. /**
  15694. * Returns the world matrix of the node
  15695. * @returns a matrix containing the node's world matrix
  15696. */
  15697. Node.prototype.getWorldMatrix = function () {
  15698. return BABYLON.Matrix.Identity();
  15699. };
  15700. // override it in derived class if you add new variables to the cache
  15701. // and call the parent class method
  15702. /** @ignore */
  15703. Node.prototype._initCache = function () {
  15704. this._cache = {};
  15705. this._cache.parent = undefined;
  15706. };
  15707. /** @ignore */
  15708. Node.prototype.updateCache = function (force) {
  15709. if (!force && this.isSynchronized())
  15710. return;
  15711. this._cache.parent = this.parent;
  15712. this._updateCache();
  15713. };
  15714. // override it in derived class if you add new variables to the cache
  15715. // and call the parent class method if !ignoreParentClass
  15716. /** @ignore */
  15717. Node.prototype._updateCache = function (ignoreParentClass) {
  15718. };
  15719. // override it in derived class if you add new variables to the cache
  15720. /** @ignore */
  15721. Node.prototype._isSynchronized = function () {
  15722. return true;
  15723. };
  15724. /** @ignore */
  15725. Node.prototype._markSyncedWithParent = function () {
  15726. if (this.parent) {
  15727. this._parentRenderId = this.parent._currentRenderId;
  15728. }
  15729. };
  15730. /** @ignore */
  15731. Node.prototype.isSynchronizedWithParent = function () {
  15732. if (!this.parent) {
  15733. return true;
  15734. }
  15735. if (this._parentRenderId !== this.parent._currentRenderId) {
  15736. return false;
  15737. }
  15738. return this.parent.isSynchronized();
  15739. };
  15740. /** @ignore */
  15741. Node.prototype.isSynchronized = function (updateCache) {
  15742. var check = this.hasNewParent();
  15743. check = check || !this.isSynchronizedWithParent();
  15744. check = check || !this._isSynchronized();
  15745. if (updateCache)
  15746. this.updateCache(true);
  15747. return !check;
  15748. };
  15749. /** @ignore */
  15750. Node.prototype.hasNewParent = function (update) {
  15751. if (this._cache.parent === this.parent)
  15752. return false;
  15753. if (update)
  15754. this._cache.parent = this.parent;
  15755. return true;
  15756. };
  15757. /**
  15758. * Is this node ready to be used/rendered
  15759. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15760. * @return true if the node is ready
  15761. */
  15762. Node.prototype.isReady = function (completeCheck) {
  15763. if (completeCheck === void 0) { completeCheck = false; }
  15764. return this._isReady;
  15765. };
  15766. /**
  15767. * Is this node enabled?
  15768. * 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
  15769. * @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
  15770. * @return whether this node (and its parent) is enabled
  15771. * @see setEnabled
  15772. */
  15773. Node.prototype.isEnabled = function (checkAncestors) {
  15774. if (checkAncestors === void 0) { checkAncestors = true; }
  15775. if (checkAncestors === false) {
  15776. return this._isEnabled;
  15777. }
  15778. if (this._isEnabled === false) {
  15779. return false;
  15780. }
  15781. if (this.parent !== undefined && this.parent !== null) {
  15782. return this.parent.isEnabled(checkAncestors);
  15783. }
  15784. return true;
  15785. };
  15786. /**
  15787. * Set the enabled state of this node
  15788. * @param value defines the new enabled state
  15789. * @see isEnabled
  15790. */
  15791. Node.prototype.setEnabled = function (value) {
  15792. this._isEnabled = value;
  15793. };
  15794. /**
  15795. * Is this node a descendant of the given node?
  15796. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15797. * @param ancestor defines the parent node to inspect
  15798. * @see parent
  15799. * @returns a boolean indicating if this node is a descendant of the given node
  15800. */
  15801. Node.prototype.isDescendantOf = function (ancestor) {
  15802. if (this.parent) {
  15803. if (this.parent === ancestor) {
  15804. return true;
  15805. }
  15806. return this.parent.isDescendantOf(ancestor);
  15807. }
  15808. return false;
  15809. };
  15810. /** @ignore */
  15811. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15812. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15813. if (!this._children) {
  15814. return;
  15815. }
  15816. for (var index = 0; index < this._children.length; index++) {
  15817. var item = this._children[index];
  15818. if (!predicate || predicate(item)) {
  15819. results.push(item);
  15820. }
  15821. if (!directDescendantsOnly) {
  15822. item._getDescendants(results, false, predicate);
  15823. }
  15824. }
  15825. };
  15826. /**
  15827. * Will return all nodes that have this node as ascendant
  15828. * @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
  15829. * @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
  15830. * @return all children nodes of all types
  15831. */
  15832. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15833. var results = new Array();
  15834. this._getDescendants(results, directDescendantsOnly, predicate);
  15835. return results;
  15836. };
  15837. /**
  15838. * Get all child-meshes of this node
  15839. * @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
  15840. * @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
  15841. * @returns an array of {BABYLON.AbstractMesh}
  15842. */
  15843. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15844. var results = [];
  15845. this._getDescendants(results, directDescendantsOnly, function (node) {
  15846. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15847. });
  15848. return results;
  15849. };
  15850. /**
  15851. * Get all child-transformNodes of this node
  15852. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15853. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15854. * @returns an array of {BABYLON.TransformNode}
  15855. */
  15856. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15857. var results = [];
  15858. this._getDescendants(results, directDescendantsOnly, function (node) {
  15859. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15860. });
  15861. return results;
  15862. };
  15863. /**
  15864. * Get all direct children of this node
  15865. * @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
  15866. * @returns an array of {BABYLON.Node}
  15867. */
  15868. Node.prototype.getChildren = function (predicate) {
  15869. return this.getDescendants(true, predicate);
  15870. };
  15871. /** @ignore */
  15872. Node.prototype._setReady = function (state) {
  15873. if (state === this._isReady) {
  15874. return;
  15875. }
  15876. if (!state) {
  15877. this._isReady = false;
  15878. return;
  15879. }
  15880. this._isReady = true;
  15881. if (this.onReady) {
  15882. this.onReady(this);
  15883. }
  15884. };
  15885. /**
  15886. * Get an animation by name
  15887. * @param name defines the name of the animation to look for
  15888. * @returns null if not found else the requested animation
  15889. */
  15890. Node.prototype.getAnimationByName = function (name) {
  15891. for (var i = 0; i < this.animations.length; i++) {
  15892. var animation = this.animations[i];
  15893. if (animation.name === name) {
  15894. return animation;
  15895. }
  15896. }
  15897. return null;
  15898. };
  15899. /**
  15900. * Creates an animation range for this node
  15901. * @param name defines the name of the range
  15902. * @param from defines the starting key
  15903. * @param to defines the end key
  15904. */
  15905. Node.prototype.createAnimationRange = function (name, from, to) {
  15906. // check name not already in use
  15907. if (!this._ranges[name]) {
  15908. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15909. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15910. if (this.animations[i]) {
  15911. this.animations[i].createRange(name, from, to);
  15912. }
  15913. }
  15914. }
  15915. };
  15916. /**
  15917. * Delete a specific animation range
  15918. * @param name defines the name of the range to delete
  15919. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15920. */
  15921. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15922. if (deleteFrames === void 0) { deleteFrames = true; }
  15923. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15924. if (this.animations[i]) {
  15925. this.animations[i].deleteRange(name, deleteFrames);
  15926. }
  15927. }
  15928. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15929. };
  15930. /**
  15931. * Get an animation range by name
  15932. * @param name defines the name of the animation range to look for
  15933. * @returns null if not found else the requested animation range
  15934. */
  15935. Node.prototype.getAnimationRange = function (name) {
  15936. return this._ranges[name];
  15937. };
  15938. /**
  15939. * Will start the animation sequence
  15940. * @param name defines the range frames for animation sequence
  15941. * @param loop defines if the animation should loop (false by default)
  15942. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15943. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15944. * @returns the object created for this animation. If range does not exist, it will return null
  15945. */
  15946. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15947. var range = this.getAnimationRange(name);
  15948. if (!range) {
  15949. return null;
  15950. }
  15951. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15952. };
  15953. /**
  15954. * Serialize animation ranges into a JSON compatible object
  15955. * @returns serialization object
  15956. */
  15957. Node.prototype.serializeAnimationRanges = function () {
  15958. var serializationRanges = [];
  15959. for (var name in this._ranges) {
  15960. var localRange = this._ranges[name];
  15961. if (!localRange) {
  15962. continue;
  15963. }
  15964. var range = {};
  15965. range.name = name;
  15966. range.from = localRange.from;
  15967. range.to = localRange.to;
  15968. serializationRanges.push(range);
  15969. }
  15970. return serializationRanges;
  15971. };
  15972. /**
  15973. * Computes the world matrix of the node
  15974. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15975. * @returns the world matrix
  15976. */
  15977. Node.prototype.computeWorldMatrix = function (force) {
  15978. return BABYLON.Matrix.Identity();
  15979. };
  15980. /**
  15981. * Releases resources associated with this node.
  15982. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15983. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15984. */
  15985. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15986. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15987. if (!doNotRecurse) {
  15988. var nodes = this.getDescendants(true);
  15989. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15990. var node = nodes_1[_i];
  15991. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15992. }
  15993. }
  15994. else {
  15995. var transformNodes = this.getChildTransformNodes(true);
  15996. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15997. var transformNode = transformNodes_1[_a];
  15998. transformNode.parent = null;
  15999. transformNode.computeWorldMatrix(true);
  16000. }
  16001. }
  16002. this.parent = null;
  16003. // Callback
  16004. this.onDisposeObservable.notifyObservers(this);
  16005. this.onDisposeObservable.clear();
  16006. // Behaviors
  16007. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16008. var behavior = _c[_b];
  16009. behavior.detach();
  16010. }
  16011. this._behaviors = [];
  16012. this._isDisposed = true;
  16013. };
  16014. /**
  16015. * Parse animation range data from a serialization object and store them into a given node
  16016. * @param node defines where to store the animation ranges
  16017. * @param parsedNode defines the serialization object to read data from
  16018. * @param scene defines the hosting scene
  16019. */
  16020. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16021. if (parsedNode.ranges) {
  16022. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16023. var data = parsedNode.ranges[index];
  16024. node.createAnimationRange(data.name, data.from, data.to);
  16025. }
  16026. }
  16027. };
  16028. __decorate([
  16029. BABYLON.serialize()
  16030. ], Node.prototype, "name", void 0);
  16031. __decorate([
  16032. BABYLON.serialize()
  16033. ], Node.prototype, "id", void 0);
  16034. __decorate([
  16035. BABYLON.serialize()
  16036. ], Node.prototype, "uniqueId", void 0);
  16037. __decorate([
  16038. BABYLON.serialize()
  16039. ], Node.prototype, "state", void 0);
  16040. __decorate([
  16041. BABYLON.serialize()
  16042. ], Node.prototype, "metadata", void 0);
  16043. return Node;
  16044. }());
  16045. BABYLON.Node = Node;
  16046. })(BABYLON || (BABYLON = {}));
  16047. //# sourceMappingURL=babylon.node.js.map
  16048. var BABYLON;
  16049. (function (BABYLON) {
  16050. var BoundingSphere = /** @class */ (function () {
  16051. function BoundingSphere(minimum, maximum) {
  16052. this.minimum = minimum;
  16053. this.maximum = maximum;
  16054. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16055. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16056. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16057. this.radius = distance * 0.5;
  16058. this.centerWorld = BABYLON.Vector3.Zero();
  16059. this._update(BABYLON.Matrix.Identity());
  16060. }
  16061. // Methods
  16062. BoundingSphere.prototype._update = function (world) {
  16063. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16064. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16065. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16066. };
  16067. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16068. for (var i = 0; i < 6; i++) {
  16069. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16070. return false;
  16071. }
  16072. return true;
  16073. };
  16074. BoundingSphere.prototype.intersectsPoint = function (point) {
  16075. var x = this.centerWorld.x - point.x;
  16076. var y = this.centerWorld.y - point.y;
  16077. var z = this.centerWorld.z - point.z;
  16078. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16079. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16080. return false;
  16081. return true;
  16082. };
  16083. // Statics
  16084. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16085. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16086. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16087. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16088. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16089. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16090. return false;
  16091. return true;
  16092. };
  16093. return BoundingSphere;
  16094. }());
  16095. BABYLON.BoundingSphere = BoundingSphere;
  16096. })(BABYLON || (BABYLON = {}));
  16097. //# sourceMappingURL=babylon.boundingSphere.js.map
  16098. var BABYLON;
  16099. (function (BABYLON) {
  16100. var BoundingBox = /** @class */ (function () {
  16101. function BoundingBox(minimum, maximum) {
  16102. this.minimum = minimum;
  16103. this.maximum = maximum;
  16104. this.vectors = new Array();
  16105. this.vectorsWorld = new Array();
  16106. // Bounding vectors
  16107. this.vectors.push(this.minimum.clone());
  16108. this.vectors.push(this.maximum.clone());
  16109. this.vectors.push(this.minimum.clone());
  16110. this.vectors[2].x = this.maximum.x;
  16111. this.vectors.push(this.minimum.clone());
  16112. this.vectors[3].y = this.maximum.y;
  16113. this.vectors.push(this.minimum.clone());
  16114. this.vectors[4].z = this.maximum.z;
  16115. this.vectors.push(this.maximum.clone());
  16116. this.vectors[5].z = this.minimum.z;
  16117. this.vectors.push(this.maximum.clone());
  16118. this.vectors[6].x = this.minimum.x;
  16119. this.vectors.push(this.maximum.clone());
  16120. this.vectors[7].y = this.minimum.y;
  16121. // OBB
  16122. this.center = this.maximum.add(this.minimum).scale(0.5);
  16123. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16124. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16125. // World
  16126. for (var index = 0; index < this.vectors.length; index++) {
  16127. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16128. }
  16129. this.minimumWorld = BABYLON.Vector3.Zero();
  16130. this.maximumWorld = BABYLON.Vector3.Zero();
  16131. this.centerWorld = BABYLON.Vector3.Zero();
  16132. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16133. this._update(BABYLON.Matrix.Identity());
  16134. }
  16135. // Methods
  16136. BoundingBox.prototype.getWorldMatrix = function () {
  16137. return this._worldMatrix;
  16138. };
  16139. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16140. this._worldMatrix.copyFrom(matrix);
  16141. return this;
  16142. };
  16143. BoundingBox.prototype._update = function (world) {
  16144. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16145. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16146. for (var index = 0; index < this.vectors.length; index++) {
  16147. var v = this.vectorsWorld[index];
  16148. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16149. if (v.x < this.minimumWorld.x)
  16150. this.minimumWorld.x = v.x;
  16151. if (v.y < this.minimumWorld.y)
  16152. this.minimumWorld.y = v.y;
  16153. if (v.z < this.minimumWorld.z)
  16154. this.minimumWorld.z = v.z;
  16155. if (v.x > this.maximumWorld.x)
  16156. this.maximumWorld.x = v.x;
  16157. if (v.y > this.maximumWorld.y)
  16158. this.maximumWorld.y = v.y;
  16159. if (v.z > this.maximumWorld.z)
  16160. this.maximumWorld.z = v.z;
  16161. }
  16162. // Extend
  16163. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16164. this.extendSizeWorld.scaleInPlace(0.5);
  16165. // OBB
  16166. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16167. this.centerWorld.scaleInPlace(0.5);
  16168. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16169. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16170. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16171. this._worldMatrix = world;
  16172. };
  16173. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16174. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16175. };
  16176. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16177. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16178. };
  16179. BoundingBox.prototype.intersectsPoint = function (point) {
  16180. var delta = -BABYLON.Epsilon;
  16181. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16182. return false;
  16183. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16184. return false;
  16185. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16186. return false;
  16187. return true;
  16188. };
  16189. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16190. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16191. };
  16192. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16193. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16194. return false;
  16195. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16196. return false;
  16197. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingBox.Intersects = function (box0, box1) {
  16203. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16204. return false;
  16205. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16206. return false;
  16207. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16208. return false;
  16209. return true;
  16210. };
  16211. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16212. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16213. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16214. return (num <= (sphereRadius * sphereRadius));
  16215. };
  16216. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16217. for (var p = 0; p < 6; p++) {
  16218. for (var i = 0; i < 8; i++) {
  16219. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16220. return false;
  16221. }
  16222. }
  16223. }
  16224. return true;
  16225. };
  16226. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16227. for (var p = 0; p < 6; p++) {
  16228. var inCount = 8;
  16229. for (var i = 0; i < 8; i++) {
  16230. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16231. --inCount;
  16232. }
  16233. else {
  16234. break;
  16235. }
  16236. }
  16237. if (inCount === 0)
  16238. return false;
  16239. }
  16240. return true;
  16241. };
  16242. return BoundingBox;
  16243. }());
  16244. BABYLON.BoundingBox = BoundingBox;
  16245. })(BABYLON || (BABYLON = {}));
  16246. //# sourceMappingURL=babylon.boundingBox.js.map
  16247. var BABYLON;
  16248. (function (BABYLON) {
  16249. var computeBoxExtents = function (axis, box) {
  16250. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16251. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16252. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16253. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16254. var r = r0 + r1 + r2;
  16255. return {
  16256. min: p - r,
  16257. max: p + r
  16258. };
  16259. };
  16260. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16261. var axisOverlap = function (axis, box0, box1) {
  16262. var result0 = computeBoxExtents(axis, box0);
  16263. var result1 = computeBoxExtents(axis, box1);
  16264. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16265. };
  16266. var BoundingInfo = /** @class */ (function () {
  16267. function BoundingInfo(minimum, maximum) {
  16268. this.minimum = minimum;
  16269. this.maximum = maximum;
  16270. this._isLocked = false;
  16271. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16272. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16273. }
  16274. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16275. get: function () {
  16276. return this._isLocked;
  16277. },
  16278. set: function (value) {
  16279. this._isLocked = value;
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. // Methods
  16285. BoundingInfo.prototype.update = function (world) {
  16286. if (this._isLocked) {
  16287. return;
  16288. }
  16289. this.boundingBox._update(world);
  16290. this.boundingSphere._update(world);
  16291. };
  16292. /**
  16293. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16294. * @param center New center of the bounding info
  16295. * @param extend New extend of the bounding info
  16296. */
  16297. BoundingInfo.prototype.centerOn = function (center, extend) {
  16298. this.minimum = center.subtract(extend);
  16299. this.maximum = center.add(extend);
  16300. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16301. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16302. return this;
  16303. };
  16304. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16305. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16306. return false;
  16307. return this.boundingBox.isInFrustum(frustumPlanes);
  16308. };
  16309. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16310. /**
  16311. * Gets the world distance between the min and max points of the bounding box
  16312. */
  16313. get: function () {
  16314. var boundingBox = this.boundingBox;
  16315. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16316. return size.length();
  16317. },
  16318. enumerable: true,
  16319. configurable: true
  16320. });
  16321. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16322. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16323. };
  16324. BoundingInfo.prototype._checkCollision = function (collider) {
  16325. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16326. };
  16327. BoundingInfo.prototype.intersectsPoint = function (point) {
  16328. if (!this.boundingSphere.centerWorld) {
  16329. return false;
  16330. }
  16331. if (!this.boundingSphere.intersectsPoint(point)) {
  16332. return false;
  16333. }
  16334. if (!this.boundingBox.intersectsPoint(point)) {
  16335. return false;
  16336. }
  16337. return true;
  16338. };
  16339. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16340. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16341. return false;
  16342. }
  16343. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16344. return false;
  16345. }
  16346. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16347. return false;
  16348. }
  16349. if (!precise) {
  16350. return true;
  16351. }
  16352. var box0 = this.boundingBox;
  16353. var box1 = boundingInfo.boundingBox;
  16354. if (!axisOverlap(box0.directions[0], box0, box1))
  16355. return false;
  16356. if (!axisOverlap(box0.directions[1], box0, box1))
  16357. return false;
  16358. if (!axisOverlap(box0.directions[2], box0, box1))
  16359. return false;
  16360. if (!axisOverlap(box1.directions[0], box0, box1))
  16361. return false;
  16362. if (!axisOverlap(box1.directions[1], box0, box1))
  16363. return false;
  16364. if (!axisOverlap(box1.directions[2], box0, box1))
  16365. return false;
  16366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16367. return false;
  16368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16369. return false;
  16370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16371. return false;
  16372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16373. return false;
  16374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16375. return false;
  16376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16377. return false;
  16378. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16379. return false;
  16380. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16381. return false;
  16382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16383. return false;
  16384. return true;
  16385. };
  16386. return BoundingInfo;
  16387. }());
  16388. BABYLON.BoundingInfo = BoundingInfo;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.boundingInfo.js.map
  16391. var BABYLON;
  16392. (function (BABYLON) {
  16393. var TransformNode = /** @class */ (function (_super) {
  16394. __extends(TransformNode, _super);
  16395. function TransformNode(name, scene, isPure) {
  16396. if (scene === void 0) { scene = null; }
  16397. if (isPure === void 0) { isPure = true; }
  16398. var _this = _super.call(this, name, scene) || this;
  16399. // Properties
  16400. _this._rotation = BABYLON.Vector3.Zero();
  16401. _this._scaling = BABYLON.Vector3.One();
  16402. _this._isDirty = false;
  16403. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16404. _this.scalingDeterminant = 1;
  16405. _this.infiniteDistance = false;
  16406. _this.position = BABYLON.Vector3.Zero();
  16407. _this._localWorld = BABYLON.Matrix.Zero();
  16408. _this._worldMatrix = BABYLON.Matrix.Zero();
  16409. _this._worldMatrixDeterminant = 0;
  16410. _this._absolutePosition = BABYLON.Vector3.Zero();
  16411. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16412. _this._postMultiplyPivotMatrix = false;
  16413. _this._isWorldMatrixFrozen = false;
  16414. /**
  16415. * An event triggered after the world matrix is updated
  16416. * @type {BABYLON.Observable}
  16417. */
  16418. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16419. _this._nonUniformScaling = false;
  16420. if (isPure) {
  16421. _this.getScene().addTransformNode(_this);
  16422. }
  16423. return _this;
  16424. }
  16425. /**
  16426. * Gets a string idenfifying the name of the class
  16427. * @returns "TransformNode" string
  16428. */
  16429. TransformNode.prototype.getClassName = function () {
  16430. return "TransformNode";
  16431. };
  16432. Object.defineProperty(TransformNode.prototype, "rotation", {
  16433. /**
  16434. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16435. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16436. * Default : (0.0, 0.0, 0.0)
  16437. */
  16438. get: function () {
  16439. return this._rotation;
  16440. },
  16441. set: function (newRotation) {
  16442. this._rotation = newRotation;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(TransformNode.prototype, "scaling", {
  16448. /**
  16449. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16450. * Default : (1.0, 1.0, 1.0)
  16451. */
  16452. get: function () {
  16453. return this._scaling;
  16454. },
  16455. /**
  16456. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16457. * Default : (1.0, 1.0, 1.0)
  16458. */
  16459. set: function (newScaling) {
  16460. this._scaling = newScaling;
  16461. },
  16462. enumerable: true,
  16463. configurable: true
  16464. });
  16465. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16466. /**
  16467. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16468. * It's null by default.
  16469. * 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)
  16470. */
  16471. get: function () {
  16472. return this._rotationQuaternion;
  16473. },
  16474. set: function (quaternion) {
  16475. this._rotationQuaternion = quaternion;
  16476. //reset the rotation vector.
  16477. if (quaternion && this.rotation.length()) {
  16478. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16479. }
  16480. },
  16481. enumerable: true,
  16482. configurable: true
  16483. });
  16484. /**
  16485. * Returns the latest update of the World matrix
  16486. * Returns a Matrix.
  16487. */
  16488. TransformNode.prototype.getWorldMatrix = function () {
  16489. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16490. this.computeWorldMatrix();
  16491. }
  16492. return this._worldMatrix;
  16493. };
  16494. /**
  16495. * Returns the latest update of the World matrix determinant.
  16496. */
  16497. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16498. return this._worldMatrixDeterminant;
  16499. };
  16500. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16501. /**
  16502. * Returns directly the latest state of the mesh World matrix.
  16503. * A Matrix is returned.
  16504. */
  16505. get: function () {
  16506. return this._worldMatrix;
  16507. },
  16508. enumerable: true,
  16509. configurable: true
  16510. });
  16511. /**
  16512. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16513. * Returns the AbstractMesh.
  16514. */
  16515. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16516. this._poseMatrix.copyFrom(matrix);
  16517. return this;
  16518. };
  16519. /**
  16520. * Returns the mesh Pose matrix.
  16521. * Returned object : Matrix
  16522. */
  16523. TransformNode.prototype.getPoseMatrix = function () {
  16524. return this._poseMatrix;
  16525. };
  16526. TransformNode.prototype._isSynchronized = function () {
  16527. if (this._isDirty) {
  16528. return false;
  16529. }
  16530. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16531. return false;
  16532. if (this._cache.pivotMatrixUpdated) {
  16533. return false;
  16534. }
  16535. if (this.infiniteDistance) {
  16536. return false;
  16537. }
  16538. if (!this._cache.position.equals(this.position))
  16539. return false;
  16540. if (this.rotationQuaternion) {
  16541. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16542. return false;
  16543. }
  16544. if (!this._cache.rotation.equals(this.rotation))
  16545. return false;
  16546. if (!this._cache.scaling.equals(this.scaling))
  16547. return false;
  16548. return true;
  16549. };
  16550. TransformNode.prototype._initCache = function () {
  16551. _super.prototype._initCache.call(this);
  16552. this._cache.localMatrixUpdated = false;
  16553. this._cache.position = BABYLON.Vector3.Zero();
  16554. this._cache.scaling = BABYLON.Vector3.Zero();
  16555. this._cache.rotation = BABYLON.Vector3.Zero();
  16556. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16557. this._cache.billboardMode = -1;
  16558. };
  16559. TransformNode.prototype.markAsDirty = function (property) {
  16560. if (property === "rotation") {
  16561. this.rotationQuaternion = null;
  16562. }
  16563. this._currentRenderId = Number.MAX_VALUE;
  16564. this._isDirty = true;
  16565. return this;
  16566. };
  16567. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16568. /**
  16569. * Returns the current mesh absolute position.
  16570. * Retuns a Vector3.
  16571. */
  16572. get: function () {
  16573. return this._absolutePosition;
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. /**
  16579. * Sets a new matrix to apply before all other transformation
  16580. * @param matrix defines the transform matrix
  16581. * @returns the current TransformNode
  16582. */
  16583. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16584. return this.setPivotMatrix(matrix, false);
  16585. };
  16586. /**
  16587. * Sets a new pivot matrix to the current node
  16588. * @param matrix defines the new pivot matrix to use
  16589. * @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
  16590. * @returns the current TransformNode
  16591. */
  16592. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16593. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16594. this._pivotMatrix = matrix.clone();
  16595. this._cache.pivotMatrixUpdated = true;
  16596. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16597. if (this._postMultiplyPivotMatrix) {
  16598. if (!this._pivotMatrixInverse) {
  16599. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16600. }
  16601. else {
  16602. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16603. }
  16604. }
  16605. return this;
  16606. };
  16607. /**
  16608. * Returns the mesh pivot matrix.
  16609. * Default : Identity.
  16610. * A Matrix is returned.
  16611. */
  16612. TransformNode.prototype.getPivotMatrix = function () {
  16613. return this._pivotMatrix;
  16614. };
  16615. /**
  16616. * Prevents the World matrix to be computed any longer.
  16617. * Returns the AbstractMesh.
  16618. */
  16619. TransformNode.prototype.freezeWorldMatrix = function () {
  16620. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16621. this.computeWorldMatrix(true);
  16622. this._isWorldMatrixFrozen = true;
  16623. return this;
  16624. };
  16625. /**
  16626. * Allows back the World matrix computation.
  16627. * Returns the AbstractMesh.
  16628. */
  16629. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16630. this._isWorldMatrixFrozen = false;
  16631. this.computeWorldMatrix(true);
  16632. return this;
  16633. };
  16634. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16635. /**
  16636. * True if the World matrix has been frozen.
  16637. * Returns a boolean.
  16638. */
  16639. get: function () {
  16640. return this._isWorldMatrixFrozen;
  16641. },
  16642. enumerable: true,
  16643. configurable: true
  16644. });
  16645. /**
  16646. * Retuns the mesh absolute position in the World.
  16647. * Returns a Vector3.
  16648. */
  16649. TransformNode.prototype.getAbsolutePosition = function () {
  16650. this.computeWorldMatrix();
  16651. return this._absolutePosition;
  16652. };
  16653. /**
  16654. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16655. * Returns the AbstractMesh.
  16656. */
  16657. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16658. if (!absolutePosition) {
  16659. return this;
  16660. }
  16661. var absolutePositionX;
  16662. var absolutePositionY;
  16663. var absolutePositionZ;
  16664. if (absolutePosition.x === undefined) {
  16665. if (arguments.length < 3) {
  16666. return this;
  16667. }
  16668. absolutePositionX = arguments[0];
  16669. absolutePositionY = arguments[1];
  16670. absolutePositionZ = arguments[2];
  16671. }
  16672. else {
  16673. absolutePositionX = absolutePosition.x;
  16674. absolutePositionY = absolutePosition.y;
  16675. absolutePositionZ = absolutePosition.z;
  16676. }
  16677. if (this.parent) {
  16678. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16679. invertParentWorldMatrix.invert();
  16680. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16681. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16682. }
  16683. else {
  16684. this.position.x = absolutePositionX;
  16685. this.position.y = absolutePositionY;
  16686. this.position.z = absolutePositionZ;
  16687. }
  16688. return this;
  16689. };
  16690. /**
  16691. * Sets the mesh position in its local space.
  16692. * Returns the AbstractMesh.
  16693. */
  16694. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16695. this.computeWorldMatrix();
  16696. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16697. return this;
  16698. };
  16699. /**
  16700. * Returns the mesh position in the local space from the current World matrix values.
  16701. * Returns a new Vector3.
  16702. */
  16703. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16704. this.computeWorldMatrix();
  16705. var invLocalWorldMatrix = this._localWorld.clone();
  16706. invLocalWorldMatrix.invert();
  16707. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16708. };
  16709. /**
  16710. * Translates the mesh along the passed Vector3 in its local space.
  16711. * Returns the AbstractMesh.
  16712. */
  16713. TransformNode.prototype.locallyTranslate = function (vector3) {
  16714. this.computeWorldMatrix(true);
  16715. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16716. return this;
  16717. };
  16718. /**
  16719. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16720. * @param targetPoint the position (must be in same space as current mesh) to look at
  16721. * @param yawCor optional yaw (y-axis) correction in radians
  16722. * @param pitchCor optional pitch (x-axis) correction in radians
  16723. * @param rollCor optional roll (z-axis) correction in radians
  16724. * @param space the choosen space of the target
  16725. * @returns the TransformNode.
  16726. */
  16727. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16728. if (yawCor === void 0) { yawCor = 0; }
  16729. if (pitchCor === void 0) { pitchCor = 0; }
  16730. if (rollCor === void 0) { rollCor = 0; }
  16731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16732. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16733. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16734. targetPoint.subtractToRef(pos, dv);
  16735. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16736. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16737. var pitch = Math.atan2(dv.y, len);
  16738. if (this.rotationQuaternion) {
  16739. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16740. }
  16741. else {
  16742. this.rotation.x = pitch + pitchCor;
  16743. this.rotation.y = yaw + yawCor;
  16744. this.rotation.z = rollCor;
  16745. }
  16746. return this;
  16747. };
  16748. /**
  16749. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16750. * This Vector3 is expressed in the World space.
  16751. */
  16752. TransformNode.prototype.getDirection = function (localAxis) {
  16753. var result = BABYLON.Vector3.Zero();
  16754. this.getDirectionToRef(localAxis, result);
  16755. return result;
  16756. };
  16757. /**
  16758. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16759. * localAxis is expressed in the mesh local space.
  16760. * result is computed in the Wordl space from the mesh World matrix.
  16761. * Returns the AbstractMesh.
  16762. */
  16763. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16764. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16765. return this;
  16766. };
  16767. /**
  16768. * Sets a new pivot point to the current node
  16769. * @param point defines the new pivot point to use
  16770. * @param space defines if the point is in world or local space (local by default)
  16771. * @returns the current TransformNode
  16772. */
  16773. TransformNode.prototype.setPivotPoint = function (point, space) {
  16774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16775. if (this.getScene().getRenderId() == 0) {
  16776. this.computeWorldMatrix(true);
  16777. }
  16778. var wm = this.getWorldMatrix();
  16779. if (space == BABYLON.Space.WORLD) {
  16780. var tmat = BABYLON.Tmp.Matrix[0];
  16781. wm.invertToRef(tmat);
  16782. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16783. }
  16784. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16785. };
  16786. /**
  16787. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16788. */
  16789. TransformNode.prototype.getPivotPoint = function () {
  16790. var point = BABYLON.Vector3.Zero();
  16791. this.getPivotPointToRef(point);
  16792. return point;
  16793. };
  16794. /**
  16795. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16796. * Returns the AbstractMesh.
  16797. */
  16798. TransformNode.prototype.getPivotPointToRef = function (result) {
  16799. result.x = -this._pivotMatrix.m[12];
  16800. result.y = -this._pivotMatrix.m[13];
  16801. result.z = -this._pivotMatrix.m[14];
  16802. return this;
  16803. };
  16804. /**
  16805. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16806. */
  16807. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16808. var point = BABYLON.Vector3.Zero();
  16809. this.getAbsolutePivotPointToRef(point);
  16810. return point;
  16811. };
  16812. /**
  16813. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16814. * Returns the AbstractMesh.
  16815. */
  16816. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16817. result.x = this._pivotMatrix.m[12];
  16818. result.y = this._pivotMatrix.m[13];
  16819. result.z = this._pivotMatrix.m[14];
  16820. this.getPivotPointToRef(result);
  16821. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16822. return this;
  16823. };
  16824. /**
  16825. * Defines the passed node as the parent of the current node.
  16826. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16827. * Returns the TransformNode.
  16828. */
  16829. TransformNode.prototype.setParent = function (node) {
  16830. if (node === null) {
  16831. var rotation = BABYLON.Tmp.Quaternion[0];
  16832. var position = BABYLON.Tmp.Vector3[0];
  16833. var scale = BABYLON.Tmp.Vector3[1];
  16834. if (this.parent && this.parent.computeWorldMatrix) {
  16835. this.parent.computeWorldMatrix(true);
  16836. }
  16837. this.computeWorldMatrix(true);
  16838. this.getWorldMatrix().decompose(scale, rotation, position);
  16839. if (this.rotationQuaternion) {
  16840. this.rotationQuaternion.copyFrom(rotation);
  16841. }
  16842. else {
  16843. rotation.toEulerAnglesToRef(this.rotation);
  16844. }
  16845. this.scaling.x = scale.x;
  16846. this.scaling.y = scale.y;
  16847. this.scaling.z = scale.z;
  16848. this.position.x = position.x;
  16849. this.position.y = position.y;
  16850. this.position.z = position.z;
  16851. }
  16852. else {
  16853. var rotation = BABYLON.Tmp.Quaternion[0];
  16854. var position = BABYLON.Tmp.Vector3[0];
  16855. var scale = BABYLON.Tmp.Vector3[1];
  16856. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16857. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16858. this.computeWorldMatrix(true);
  16859. node.computeWorldMatrix(true);
  16860. node.getWorldMatrix().invertToRef(invParentMatrix);
  16861. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16862. diffMatrix.decompose(scale, rotation, position);
  16863. if (this.rotationQuaternion) {
  16864. this.rotationQuaternion.copyFrom(rotation);
  16865. }
  16866. else {
  16867. rotation.toEulerAnglesToRef(this.rotation);
  16868. }
  16869. this.position.x = position.x;
  16870. this.position.y = position.y;
  16871. this.position.z = position.z;
  16872. this.scaling.x = scale.x;
  16873. this.scaling.y = scale.y;
  16874. this.scaling.z = scale.z;
  16875. }
  16876. this.parent = node;
  16877. return this;
  16878. };
  16879. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16880. get: function () {
  16881. return this._nonUniformScaling;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16887. if (this._nonUniformScaling === value) {
  16888. return false;
  16889. }
  16890. this._nonUniformScaling = true;
  16891. return true;
  16892. };
  16893. /**
  16894. * Attach the current TransformNode to another TransformNode associated with a bone
  16895. * @param bone Bone affecting the TransformNode
  16896. * @param affectedTransformNode TransformNode associated with the bone
  16897. */
  16898. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16899. this._transformToBoneReferal = affectedTransformNode;
  16900. this.parent = bone;
  16901. if (bone.getWorldMatrix().determinant() < 0) {
  16902. this.scalingDeterminant *= -1;
  16903. }
  16904. return this;
  16905. };
  16906. TransformNode.prototype.detachFromBone = function () {
  16907. if (!this.parent) {
  16908. return this;
  16909. }
  16910. if (this.parent.getWorldMatrix().determinant() < 0) {
  16911. this.scalingDeterminant *= -1;
  16912. }
  16913. this._transformToBoneReferal = null;
  16914. this.parent = null;
  16915. return this;
  16916. };
  16917. /**
  16918. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16919. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16920. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16921. * The passed axis is also normalized.
  16922. * Returns the AbstractMesh.
  16923. */
  16924. TransformNode.prototype.rotate = function (axis, amount, space) {
  16925. axis.normalize();
  16926. if (!this.rotationQuaternion) {
  16927. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16928. this.rotation = BABYLON.Vector3.Zero();
  16929. }
  16930. var rotationQuaternion;
  16931. if (!space || space === BABYLON.Space.LOCAL) {
  16932. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16933. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16934. }
  16935. else {
  16936. if (this.parent) {
  16937. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16938. invertParentWorldMatrix.invert();
  16939. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16940. }
  16941. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16942. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16943. }
  16944. return this;
  16945. };
  16946. /**
  16947. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16948. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16949. * The passed axis is also normalized.
  16950. * Returns the AbstractMesh.
  16951. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16952. */
  16953. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16954. axis.normalize();
  16955. if (!this.rotationQuaternion) {
  16956. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16957. this.rotation.copyFromFloats(0, 0, 0);
  16958. }
  16959. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16960. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16961. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16962. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16963. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16964. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16965. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16966. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16967. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16968. return this;
  16969. };
  16970. /**
  16971. * Translates the mesh along the axis vector for the passed distance in the given space.
  16972. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16973. * Returns the AbstractMesh.
  16974. */
  16975. TransformNode.prototype.translate = function (axis, distance, space) {
  16976. var displacementVector = axis.scale(distance);
  16977. if (!space || space === BABYLON.Space.LOCAL) {
  16978. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16979. this.setPositionWithLocalVector(tempV3);
  16980. }
  16981. else {
  16982. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16983. }
  16984. return this;
  16985. };
  16986. /**
  16987. * Adds a rotation step to the mesh current rotation.
  16988. * x, y, z are Euler angles expressed in radians.
  16989. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16990. * This means this rotation is made in the mesh local space only.
  16991. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16992. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16993. * ```javascript
  16994. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16995. * ```
  16996. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16997. * 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.
  16998. * Returns the AbstractMesh.
  16999. */
  17000. TransformNode.prototype.addRotation = function (x, y, z) {
  17001. var rotationQuaternion;
  17002. if (this.rotationQuaternion) {
  17003. rotationQuaternion = this.rotationQuaternion;
  17004. }
  17005. else {
  17006. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17007. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17008. }
  17009. var accumulation = BABYLON.Tmp.Quaternion[0];
  17010. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17011. rotationQuaternion.multiplyInPlace(accumulation);
  17012. if (!this.rotationQuaternion) {
  17013. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17014. }
  17015. return this;
  17016. };
  17017. /**
  17018. * Computes the mesh World matrix and returns it.
  17019. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17020. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17021. * If the parameter `force`is set to `true`, the actual computation is done.
  17022. * Returns the mesh World Matrix.
  17023. */
  17024. TransformNode.prototype.computeWorldMatrix = function (force) {
  17025. if (this._isWorldMatrixFrozen) {
  17026. return this._worldMatrix;
  17027. }
  17028. if (!force && this.isSynchronized(true)) {
  17029. return this._worldMatrix;
  17030. }
  17031. this._cache.position.copyFrom(this.position);
  17032. this._cache.scaling.copyFrom(this.scaling);
  17033. this._cache.pivotMatrixUpdated = false;
  17034. this._cache.billboardMode = this.billboardMode;
  17035. this._currentRenderId = this.getScene().getRenderId();
  17036. this._isDirty = false;
  17037. // Scaling
  17038. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17039. // Rotation
  17040. //rotate, if quaternion is set and rotation was used
  17041. if (this.rotationQuaternion) {
  17042. var len = this.rotation.length();
  17043. if (len) {
  17044. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17045. this.rotation.copyFromFloats(0, 0, 0);
  17046. }
  17047. }
  17048. if (this.rotationQuaternion) {
  17049. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17050. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17051. }
  17052. else {
  17053. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17054. this._cache.rotation.copyFrom(this.rotation);
  17055. }
  17056. // Translation
  17057. var camera = this.getScene().activeCamera;
  17058. if (this.infiniteDistance && !this.parent && camera) {
  17059. var cameraWorldMatrix = camera.getWorldMatrix();
  17060. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17061. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17062. }
  17063. else {
  17064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17065. }
  17066. // Composing transformations
  17067. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17068. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17069. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17070. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17071. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17072. // Need to decompose each rotation here
  17073. var currentPosition = BABYLON.Tmp.Vector3[3];
  17074. if (this.parent && this.parent.getWorldMatrix) {
  17075. if (this._transformToBoneReferal) {
  17076. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17077. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17078. }
  17079. else {
  17080. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17081. }
  17082. }
  17083. else {
  17084. currentPosition.copyFrom(this.position);
  17085. }
  17086. currentPosition.subtractInPlace(camera.globalPosition);
  17087. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17088. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17089. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17090. }
  17091. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17092. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17093. }
  17094. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17095. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17096. }
  17097. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17098. }
  17099. else {
  17100. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17101. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17102. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17103. }
  17104. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17105. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17106. }
  17107. // Local world
  17108. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17109. // Parent
  17110. if (this.parent && this.parent.getWorldMatrix) {
  17111. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17112. if (this._transformToBoneReferal) {
  17113. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17114. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17115. }
  17116. else {
  17117. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17118. }
  17119. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17120. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17121. this._worldMatrix.copyFrom(this._localWorld);
  17122. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17123. }
  17124. else {
  17125. if (this._transformToBoneReferal) {
  17126. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17127. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17128. }
  17129. else {
  17130. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17131. }
  17132. }
  17133. this._markSyncedWithParent();
  17134. }
  17135. else {
  17136. this._worldMatrix.copyFrom(this._localWorld);
  17137. }
  17138. // Post multiply inverse of pivotMatrix
  17139. if (this._postMultiplyPivotMatrix) {
  17140. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17141. }
  17142. // Normal matrix
  17143. if (this.scaling.isNonUniform) {
  17144. this._updateNonUniformScalingState(true);
  17145. }
  17146. else if (this.parent && this.parent._nonUniformScaling) {
  17147. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17148. }
  17149. else {
  17150. this._updateNonUniformScalingState(false);
  17151. }
  17152. this._afterComputeWorldMatrix();
  17153. // Absolute position
  17154. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17155. // Callbacks
  17156. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17157. if (!this._poseMatrix) {
  17158. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17159. }
  17160. // Cache the determinant
  17161. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17162. return this._worldMatrix;
  17163. };
  17164. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17165. };
  17166. /**
  17167. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17168. * @param func: callback function to add
  17169. *
  17170. * Returns the TransformNode.
  17171. */
  17172. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17173. this.onAfterWorldMatrixUpdateObservable.add(func);
  17174. return this;
  17175. };
  17176. /**
  17177. * Removes a registered callback function.
  17178. * Returns the TransformNode.
  17179. */
  17180. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17181. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17182. return this;
  17183. };
  17184. /**
  17185. * Clone the current transform node
  17186. * Returns the new transform node
  17187. * @param name Name of the new clone
  17188. * @param newParent New parent for the clone
  17189. * @param doNotCloneChildren Do not clone children hierarchy
  17190. */
  17191. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17192. var _this = this;
  17193. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17194. result.name = name;
  17195. result.id = name;
  17196. if (newParent) {
  17197. result.parent = newParent;
  17198. }
  17199. if (!doNotCloneChildren) {
  17200. // Children
  17201. var directDescendants = this.getDescendants(true);
  17202. for (var index = 0; index < directDescendants.length; index++) {
  17203. var child = directDescendants[index];
  17204. if (child.clone) {
  17205. child.clone(name + "." + child.name, result);
  17206. }
  17207. }
  17208. }
  17209. return result;
  17210. };
  17211. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17212. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17213. serializationObject.type = this.getClassName();
  17214. // Parent
  17215. if (this.parent) {
  17216. serializationObject.parentId = this.parent.id;
  17217. }
  17218. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17219. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17220. }
  17221. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17222. serializationObject.isEnabled = this.isEnabled();
  17223. // Parent
  17224. if (this.parent) {
  17225. serializationObject.parentId = this.parent.id;
  17226. }
  17227. return serializationObject;
  17228. };
  17229. // Statics
  17230. /**
  17231. * Returns a new TransformNode object parsed from the source provided.
  17232. * The parameter `parsedMesh` is the source.
  17233. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17234. */
  17235. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17236. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17237. if (BABYLON.Tags) {
  17238. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17239. }
  17240. if (parsedTransformNode.localMatrix) {
  17241. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17242. }
  17243. else if (parsedTransformNode.pivotMatrix) {
  17244. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17245. }
  17246. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17247. // Parent
  17248. if (parsedTransformNode.parentId) {
  17249. transformNode._waitingParentId = parsedTransformNode.parentId;
  17250. }
  17251. return transformNode;
  17252. };
  17253. /**
  17254. * Releases resources associated with this transform node.
  17255. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17256. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17257. */
  17258. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17260. // Animations
  17261. this.getScene().stopAnimation(this);
  17262. // Remove from scene
  17263. this.getScene().removeTransformNode(this);
  17264. this.onAfterWorldMatrixUpdateObservable.clear();
  17265. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17266. };
  17267. // Statics
  17268. TransformNode.BILLBOARDMODE_NONE = 0;
  17269. TransformNode.BILLBOARDMODE_X = 1;
  17270. TransformNode.BILLBOARDMODE_Y = 2;
  17271. TransformNode.BILLBOARDMODE_Z = 4;
  17272. TransformNode.BILLBOARDMODE_ALL = 7;
  17273. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17274. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17275. __decorate([
  17276. BABYLON.serializeAsVector3()
  17277. ], TransformNode.prototype, "_rotation", void 0);
  17278. __decorate([
  17279. BABYLON.serializeAsQuaternion()
  17280. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17281. __decorate([
  17282. BABYLON.serializeAsVector3()
  17283. ], TransformNode.prototype, "_scaling", void 0);
  17284. __decorate([
  17285. BABYLON.serialize()
  17286. ], TransformNode.prototype, "billboardMode", void 0);
  17287. __decorate([
  17288. BABYLON.serialize()
  17289. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17290. __decorate([
  17291. BABYLON.serialize()
  17292. ], TransformNode.prototype, "infiniteDistance", void 0);
  17293. __decorate([
  17294. BABYLON.serializeAsVector3()
  17295. ], TransformNode.prototype, "position", void 0);
  17296. return TransformNode;
  17297. }(BABYLON.Node));
  17298. BABYLON.TransformNode = TransformNode;
  17299. })(BABYLON || (BABYLON = {}));
  17300. //# sourceMappingURL=babylon.transformNode.js.map
  17301. var BABYLON;
  17302. (function (BABYLON) {
  17303. var AbstractMesh = /** @class */ (function (_super) {
  17304. __extends(AbstractMesh, _super);
  17305. // Constructor
  17306. function AbstractMesh(name, scene) {
  17307. if (scene === void 0) { scene = null; }
  17308. var _this = _super.call(this, name, scene, false) || this;
  17309. _this._facetNb = 0; // facet number
  17310. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17311. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17312. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17313. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17314. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17315. _this._subDiv = {
  17316. max: 1,
  17317. X: 1,
  17318. Y: 1,
  17319. Z: 1
  17320. };
  17321. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17322. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17323. // Events
  17324. /**
  17325. * An event triggered when this mesh collides with another one
  17326. * @type {BABYLON.Observable}
  17327. */
  17328. _this.onCollideObservable = new BABYLON.Observable();
  17329. /**
  17330. * An event triggered when the collision's position changes
  17331. * @type {BABYLON.Observable}
  17332. */
  17333. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17334. /**
  17335. * An event triggered when material is changed
  17336. * @type {BABYLON.Observable}
  17337. */
  17338. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17339. // Properties
  17340. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17341. /**
  17342. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17343. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17344. * or
  17345. * 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.
  17346. * for more info check WebGl documentations
  17347. */
  17348. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17349. /**
  17350. * 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:
  17351. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17352. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17353. * 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.
  17354. */
  17355. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17356. /**
  17357. * 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.
  17358. * The default value is -1 which means don't break the query and wait till the result.
  17359. */
  17360. _this.occlusionRetryCount = -1;
  17361. _this._occlusionInternalRetryCounter = 0;
  17362. _this._isOccluded = false;
  17363. _this._isOcclusionQueryInProgress = false;
  17364. _this._visibility = 1.0;
  17365. _this.alphaIndex = Number.MAX_VALUE;
  17366. _this.isVisible = true;
  17367. _this.isPickable = true;
  17368. _this.showBoundingBox = false;
  17369. _this.showSubMeshesBoundingBox = false;
  17370. _this.isBlocker = false;
  17371. _this.enablePointerMoveEvents = false;
  17372. _this.renderingGroupId = 0;
  17373. _this._receiveShadows = false;
  17374. _this.renderOutline = false;
  17375. _this.outlineColor = BABYLON.Color3.Red();
  17376. _this.outlineWidth = 0.02;
  17377. _this.renderOverlay = false;
  17378. _this.overlayColor = BABYLON.Color3.Red();
  17379. _this.overlayAlpha = 0.5;
  17380. _this._hasVertexAlpha = false;
  17381. _this._useVertexColors = true;
  17382. _this._computeBonesUsingShaders = true;
  17383. _this._numBoneInfluencers = 4;
  17384. _this._applyFog = true;
  17385. _this.useOctreeForRenderingSelection = true;
  17386. _this.useOctreeForPicking = true;
  17387. _this.useOctreeForCollisions = true;
  17388. _this._layerMask = 0x0FFFFFFF;
  17389. /**
  17390. * True if the mesh must be rendered in any case.
  17391. */
  17392. _this.alwaysSelectAsActiveMesh = false;
  17393. /**
  17394. * This scene's action manager
  17395. * @type {BABYLON.ActionManager}
  17396. */
  17397. _this.actionManager = null;
  17398. // Physics
  17399. _this.physicsImpostor = null;
  17400. // Collisions
  17401. _this._checkCollisions = false;
  17402. _this._collisionMask = -1;
  17403. _this._collisionGroup = -1;
  17404. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17405. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17406. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17407. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17408. // Edges
  17409. _this.edgesWidth = 1;
  17410. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17411. // Cache
  17412. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17413. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17414. _this._renderId = 0;
  17415. _this._intersectionsInProgress = new Array();
  17416. _this._unIndexed = false;
  17417. _this._lightSources = new Array();
  17418. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17419. if (collidedMesh === void 0) { collidedMesh = null; }
  17420. //TODO move this to the collision coordinator!
  17421. if (_this.getScene().workerCollisions)
  17422. newPosition.multiplyInPlace(_this._collider._radius);
  17423. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17424. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17425. _this.position.addInPlace(_this._diffPositionForCollisions);
  17426. }
  17427. if (collidedMesh) {
  17428. _this.onCollideObservable.notifyObservers(collidedMesh);
  17429. }
  17430. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17431. };
  17432. _this.getScene().addMesh(_this);
  17433. _this._resyncLightSources();
  17434. return _this;
  17435. }
  17436. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17437. get: function () {
  17438. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17444. get: function () {
  17445. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17446. },
  17447. enumerable: true,
  17448. configurable: true
  17449. });
  17450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17451. get: function () {
  17452. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17458. get: function () {
  17459. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17460. },
  17461. enumerable: true,
  17462. configurable: true
  17463. });
  17464. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17465. get: function () {
  17466. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17472. /**
  17473. * Read-only : the number of facets in the mesh
  17474. */
  17475. get: function () {
  17476. return this._facetNb;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17482. /**
  17483. * The number (integer) of subdivisions per axis in the partioning space
  17484. */
  17485. get: function () {
  17486. return this._partitioningSubdivisions;
  17487. },
  17488. set: function (nb) {
  17489. this._partitioningSubdivisions = nb;
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17495. /**
  17496. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17497. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17498. */
  17499. get: function () {
  17500. return this._partitioningBBoxRatio;
  17501. },
  17502. set: function (ratio) {
  17503. this._partitioningBBoxRatio = ratio;
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17509. /**
  17510. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17511. * Works only for updatable meshes.
  17512. * Doesn't work with multi-materials.
  17513. */
  17514. get: function () {
  17515. return this._facetDepthSort;
  17516. },
  17517. set: function (sort) {
  17518. this._facetDepthSort = sort;
  17519. },
  17520. enumerable: true,
  17521. configurable: true
  17522. });
  17523. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17524. /**
  17525. * The location (Vector3) where the facet depth sort must be computed from.
  17526. * By default, the active camera position.
  17527. * Used only when facet depth sort is enabled.
  17528. */
  17529. get: function () {
  17530. return this._facetDepthSortFrom;
  17531. },
  17532. set: function (location) {
  17533. this._facetDepthSortFrom = location;
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17539. /**
  17540. * Read-only boolean : is the feature facetData enabled ?
  17541. */
  17542. get: function () {
  17543. return this._facetDataEnabled;
  17544. },
  17545. enumerable: true,
  17546. configurable: true
  17547. });
  17548. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17549. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17550. return false;
  17551. }
  17552. this._markSubMeshesAsMiscDirty();
  17553. return true;
  17554. };
  17555. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17556. set: function (callback) {
  17557. if (this._onCollideObserver) {
  17558. this.onCollideObservable.remove(this._onCollideObserver);
  17559. }
  17560. this._onCollideObserver = this.onCollideObservable.add(callback);
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17566. set: function (callback) {
  17567. if (this._onCollisionPositionChangeObserver) {
  17568. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17569. }
  17570. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17571. },
  17572. enumerable: true,
  17573. configurable: true
  17574. });
  17575. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17576. /**
  17577. * 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.
  17578. */
  17579. get: function () {
  17580. return this._isOccluded;
  17581. },
  17582. set: function (value) {
  17583. this._isOccluded = value;
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17589. /**
  17590. * Flag to check the progress status of the query
  17591. */
  17592. get: function () {
  17593. return this._isOcclusionQueryInProgress;
  17594. },
  17595. enumerable: true,
  17596. configurable: true
  17597. });
  17598. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17599. /**
  17600. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17601. */
  17602. get: function () {
  17603. return this._visibility;
  17604. },
  17605. /**
  17606. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17607. */
  17608. set: function (value) {
  17609. if (this._visibility === value) {
  17610. return;
  17611. }
  17612. this._visibility = value;
  17613. this._markSubMeshesAsMiscDirty();
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh.prototype, "material", {
  17619. get: function () {
  17620. return this._material;
  17621. },
  17622. set: function (value) {
  17623. if (this._material === value) {
  17624. return;
  17625. }
  17626. this._material = value;
  17627. if (this.onMaterialChangedObservable.hasObservers) {
  17628. this.onMaterialChangedObservable.notifyObservers(this);
  17629. }
  17630. if (!this.subMeshes) {
  17631. return;
  17632. }
  17633. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17634. var subMesh = _a[_i];
  17635. subMesh.setEffect(null);
  17636. }
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17642. get: function () {
  17643. return this._receiveShadows;
  17644. },
  17645. set: function (value) {
  17646. if (this._receiveShadows === value) {
  17647. return;
  17648. }
  17649. this._receiveShadows = value;
  17650. this._markSubMeshesAsLightDirty();
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17656. get: function () {
  17657. return this._hasVertexAlpha;
  17658. },
  17659. set: function (value) {
  17660. if (this._hasVertexAlpha === value) {
  17661. return;
  17662. }
  17663. this._hasVertexAlpha = value;
  17664. this._markSubMeshesAsAttributesDirty();
  17665. this._markSubMeshesAsMiscDirty();
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17671. get: function () {
  17672. return this._useVertexColors;
  17673. },
  17674. set: function (value) {
  17675. if (this._useVertexColors === value) {
  17676. return;
  17677. }
  17678. this._useVertexColors = value;
  17679. this._markSubMeshesAsAttributesDirty();
  17680. },
  17681. enumerable: true,
  17682. configurable: true
  17683. });
  17684. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17685. get: function () {
  17686. return this._computeBonesUsingShaders;
  17687. },
  17688. set: function (value) {
  17689. if (this._computeBonesUsingShaders === value) {
  17690. return;
  17691. }
  17692. this._computeBonesUsingShaders = value;
  17693. this._markSubMeshesAsAttributesDirty();
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17699. get: function () {
  17700. return this._numBoneInfluencers;
  17701. },
  17702. set: function (value) {
  17703. if (this._numBoneInfluencers === value) {
  17704. return;
  17705. }
  17706. this._numBoneInfluencers = value;
  17707. this._markSubMeshesAsAttributesDirty();
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17713. get: function () {
  17714. return this._applyFog;
  17715. },
  17716. set: function (value) {
  17717. if (this._applyFog === value) {
  17718. return;
  17719. }
  17720. this._applyFog = value;
  17721. this._markSubMeshesAsMiscDirty();
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17727. get: function () {
  17728. return this._layerMask;
  17729. },
  17730. set: function (value) {
  17731. if (value === this._layerMask) {
  17732. return;
  17733. }
  17734. this._layerMask = value;
  17735. this._resyncLightSources();
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17741. get: function () {
  17742. return this._collisionMask;
  17743. },
  17744. set: function (mask) {
  17745. this._collisionMask = !isNaN(mask) ? mask : -1;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17751. get: function () {
  17752. return this._collisionGroup;
  17753. },
  17754. set: function (mask) {
  17755. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17761. get: function () {
  17762. return null;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17768. get: function () {
  17769. return this._skeleton;
  17770. },
  17771. set: function (value) {
  17772. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17773. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17774. }
  17775. if (value && value.needInitialSkinMatrix) {
  17776. value._registerMeshWithPoseMatrix(this);
  17777. }
  17778. this._skeleton = value;
  17779. if (!this._skeleton) {
  17780. this._bonesTransformMatrices = null;
  17781. }
  17782. this._markSubMeshesAsAttributesDirty();
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. /**
  17788. * Returns the string "AbstractMesh"
  17789. */
  17790. AbstractMesh.prototype.getClassName = function () {
  17791. return "AbstractMesh";
  17792. };
  17793. /**
  17794. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17795. */
  17796. AbstractMesh.prototype.toString = function (fullDetails) {
  17797. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17798. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17799. if (this._skeleton) {
  17800. ret += ", skeleton: " + this._skeleton.name;
  17801. }
  17802. if (fullDetails) {
  17803. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17804. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17805. }
  17806. return ret;
  17807. };
  17808. AbstractMesh.prototype._rebuild = function () {
  17809. if (this._occlusionQuery) {
  17810. this._occlusionQuery = null;
  17811. }
  17812. if (this._edgesRenderer) {
  17813. this._edgesRenderer._rebuild();
  17814. }
  17815. if (!this.subMeshes) {
  17816. return;
  17817. }
  17818. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17819. var subMesh = _a[_i];
  17820. subMesh._rebuild();
  17821. }
  17822. };
  17823. AbstractMesh.prototype._resyncLightSources = function () {
  17824. this._lightSources.length = 0;
  17825. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17826. var light = _a[_i];
  17827. if (!light.isEnabled()) {
  17828. continue;
  17829. }
  17830. if (light.canAffectMesh(this)) {
  17831. this._lightSources.push(light);
  17832. }
  17833. }
  17834. this._markSubMeshesAsLightDirty();
  17835. };
  17836. AbstractMesh.prototype._resyncLighSource = function (light) {
  17837. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17838. var index = this._lightSources.indexOf(light);
  17839. if (index === -1) {
  17840. if (!isIn) {
  17841. return;
  17842. }
  17843. this._lightSources.push(light);
  17844. }
  17845. else {
  17846. if (isIn) {
  17847. return;
  17848. }
  17849. this._lightSources.splice(index, 1);
  17850. }
  17851. this._markSubMeshesAsLightDirty();
  17852. };
  17853. AbstractMesh.prototype._removeLightSource = function (light) {
  17854. var index = this._lightSources.indexOf(light);
  17855. if (index === -1) {
  17856. return;
  17857. }
  17858. this._lightSources.splice(index, 1);
  17859. this._markSubMeshesAsLightDirty();
  17860. };
  17861. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17862. if (!this.subMeshes) {
  17863. return;
  17864. }
  17865. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17866. var subMesh = _a[_i];
  17867. if (subMesh._materialDefines) {
  17868. func(subMesh._materialDefines);
  17869. }
  17870. }
  17871. };
  17872. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17873. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17874. };
  17875. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17876. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17877. };
  17878. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17879. if (!this.subMeshes) {
  17880. return;
  17881. }
  17882. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17883. var subMesh = _a[_i];
  17884. var material = subMesh.getMaterial();
  17885. if (material) {
  17886. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17887. }
  17888. }
  17889. };
  17890. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17891. /**
  17892. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17893. * Default : (1.0, 1.0, 1.0)
  17894. */
  17895. get: function () {
  17896. return this._scaling;
  17897. },
  17898. /**
  17899. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17900. * Default : (1.0, 1.0, 1.0)
  17901. */
  17902. set: function (newScaling) {
  17903. this._scaling = newScaling;
  17904. if (this.physicsImpostor) {
  17905. this.physicsImpostor.forceUpdate();
  17906. }
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. // Methods
  17912. /**
  17913. * Disables the mesh edger rendering mode.
  17914. * Returns the AbstractMesh.
  17915. */
  17916. AbstractMesh.prototype.disableEdgesRendering = function () {
  17917. if (this._edgesRenderer) {
  17918. this._edgesRenderer.dispose();
  17919. this._edgesRenderer = null;
  17920. }
  17921. return this;
  17922. };
  17923. /**
  17924. * Enables the edge rendering mode on the mesh.
  17925. * This mode makes the mesh edges visible.
  17926. * Returns the AbstractMesh.
  17927. */
  17928. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17929. if (epsilon === void 0) { epsilon = 0.95; }
  17930. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17931. this.disableEdgesRendering();
  17932. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17933. return this;
  17934. };
  17935. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17936. /**
  17937. * Returns true if the mesh is blocked. Used by the class Mesh.
  17938. * Returns the boolean `false` by default.
  17939. */
  17940. get: function () {
  17941. return false;
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. /**
  17947. * Returns the mesh itself by default, used by the class Mesh.
  17948. * Returned type : AbstractMesh
  17949. */
  17950. AbstractMesh.prototype.getLOD = function (camera) {
  17951. return this;
  17952. };
  17953. /**
  17954. * Returns 0 by default, used by the class Mesh.
  17955. * Returns an integer.
  17956. */
  17957. AbstractMesh.prototype.getTotalVertices = function () {
  17958. return 0;
  17959. };
  17960. /**
  17961. * Returns null by default, used by the class Mesh.
  17962. * Returned type : integer array
  17963. */
  17964. AbstractMesh.prototype.getIndices = function () {
  17965. return null;
  17966. };
  17967. /**
  17968. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17969. * Returned type : float array or Float32Array
  17970. */
  17971. AbstractMesh.prototype.getVerticesData = function (kind) {
  17972. return null;
  17973. };
  17974. /**
  17975. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17976. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17977. * The `data` are either a numeric array either a Float32Array.
  17978. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17979. * 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).
  17980. * Note that a new underlying VertexBuffer object is created each call.
  17981. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17982. *
  17983. * Possible `kind` values :
  17984. * - BABYLON.VertexBuffer.PositionKind
  17985. * - BABYLON.VertexBuffer.UVKind
  17986. * - BABYLON.VertexBuffer.UV2Kind
  17987. * - BABYLON.VertexBuffer.UV3Kind
  17988. * - BABYLON.VertexBuffer.UV4Kind
  17989. * - BABYLON.VertexBuffer.UV5Kind
  17990. * - BABYLON.VertexBuffer.UV6Kind
  17991. * - BABYLON.VertexBuffer.ColorKind
  17992. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17993. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17994. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17995. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17996. *
  17997. * Returns the Mesh.
  17998. */
  17999. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18000. return this;
  18001. };
  18002. /**
  18003. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18004. * If the mesh has no geometry, it is simply returned as it is.
  18005. * The `data` are either a numeric array either a Float32Array.
  18006. * No new underlying VertexBuffer object is created.
  18007. * 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.
  18008. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18009. *
  18010. * Possible `kind` values :
  18011. * - BABYLON.VertexBuffer.PositionKind
  18012. * - BABYLON.VertexBuffer.UVKind
  18013. * - BABYLON.VertexBuffer.UV2Kind
  18014. * - BABYLON.VertexBuffer.UV3Kind
  18015. * - BABYLON.VertexBuffer.UV4Kind
  18016. * - BABYLON.VertexBuffer.UV5Kind
  18017. * - BABYLON.VertexBuffer.UV6Kind
  18018. * - BABYLON.VertexBuffer.ColorKind
  18019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18023. *
  18024. * Returns the Mesh.
  18025. */
  18026. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18027. return this;
  18028. };
  18029. /**
  18030. * Sets the mesh indices.
  18031. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18032. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18033. * This method creates a new index buffer each call.
  18034. * Returns the Mesh.
  18035. */
  18036. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18037. return this;
  18038. };
  18039. /** Returns false by default, used by the class Mesh.
  18040. * Returns a boolean
  18041. */
  18042. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18043. return false;
  18044. };
  18045. /**
  18046. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18047. * Returns a BoundingInfo
  18048. */
  18049. AbstractMesh.prototype.getBoundingInfo = function () {
  18050. if (this._masterMesh) {
  18051. return this._masterMesh.getBoundingInfo();
  18052. }
  18053. if (!this._boundingInfo) {
  18054. // this._boundingInfo is being created here
  18055. this._updateBoundingInfo();
  18056. }
  18057. // cannot be null.
  18058. return this._boundingInfo;
  18059. };
  18060. /**
  18061. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18062. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18063. */
  18064. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18065. if (includeDescendants === void 0) { includeDescendants = true; }
  18066. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18067. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18068. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18069. if (maxDimension === 0) {
  18070. return this;
  18071. }
  18072. var scale = 1 / maxDimension;
  18073. this.scaling.scaleInPlace(scale);
  18074. return this;
  18075. };
  18076. /**
  18077. * Sets a mesh new object BoundingInfo.
  18078. * Returns the AbstractMesh.
  18079. */
  18080. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18081. this._boundingInfo = boundingInfo;
  18082. return this;
  18083. };
  18084. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18085. get: function () {
  18086. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18087. },
  18088. enumerable: true,
  18089. configurable: true
  18090. });
  18091. AbstractMesh.prototype._preActivate = function () {
  18092. };
  18093. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18094. };
  18095. AbstractMesh.prototype._activate = function (renderId) {
  18096. this._renderId = renderId;
  18097. };
  18098. /**
  18099. * Returns the latest update of the World matrix
  18100. * Returns a Matrix.
  18101. */
  18102. AbstractMesh.prototype.getWorldMatrix = function () {
  18103. if (this._masterMesh) {
  18104. return this._masterMesh.getWorldMatrix();
  18105. }
  18106. return _super.prototype.getWorldMatrix.call(this);
  18107. };
  18108. /**
  18109. * Returns the latest update of the World matrix determinant.
  18110. */
  18111. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18112. if (this._masterMesh) {
  18113. return this._masterMesh._getWorldMatrixDeterminant();
  18114. }
  18115. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18116. };
  18117. // ================================== Point of View Movement =================================
  18118. /**
  18119. * Perform relative position change from the point of view of behind the front of the mesh.
  18120. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18121. * Supports definition of mesh facing forward or backward.
  18122. * @param {number} amountRight
  18123. * @param {number} amountUp
  18124. * @param {number} amountForward
  18125. *
  18126. * Returns the AbstractMesh.
  18127. */
  18128. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18129. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18130. return this;
  18131. };
  18132. /**
  18133. * Calculate relative position change from the point of view of behind the front of the mesh.
  18134. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18135. * Supports definition of mesh facing forward or backward.
  18136. * @param {number} amountRight
  18137. * @param {number} amountUp
  18138. * @param {number} amountForward
  18139. *
  18140. * Returns a new Vector3.
  18141. */
  18142. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18143. var rotMatrix = new BABYLON.Matrix();
  18144. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18145. rotQuaternion.toRotationMatrix(rotMatrix);
  18146. var translationDelta = BABYLON.Vector3.Zero();
  18147. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18149. return translationDelta;
  18150. };
  18151. // ================================== Point of View Rotation =================================
  18152. /**
  18153. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18154. * Supports definition of mesh facing forward or backward.
  18155. * @param {number} flipBack
  18156. * @param {number} twirlClockwise
  18157. * @param {number} tiltRight
  18158. *
  18159. * Returns the AbstractMesh.
  18160. */
  18161. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18162. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18163. return this;
  18164. };
  18165. /**
  18166. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18167. * Supports definition of mesh facing forward or backward.
  18168. * @param {number} flipBack
  18169. * @param {number} twirlClockwise
  18170. * @param {number} tiltRight
  18171. *
  18172. * Returns a new Vector3.
  18173. */
  18174. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18175. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18176. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18177. };
  18178. /**
  18179. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18180. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18181. */
  18182. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18183. if (includeDescendants === void 0) { includeDescendants = true; }
  18184. this.computeWorldMatrix(true);
  18185. var min;
  18186. var max;
  18187. var boundingInfo = this.getBoundingInfo();
  18188. if (!this.subMeshes) {
  18189. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18190. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18191. }
  18192. else {
  18193. min = boundingInfo.boundingBox.minimumWorld;
  18194. max = boundingInfo.boundingBox.maximumWorld;
  18195. }
  18196. if (includeDescendants) {
  18197. var descendants = this.getDescendants(false);
  18198. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18199. var descendant = descendants_1[_i];
  18200. var childMesh = descendant;
  18201. childMesh.computeWorldMatrix(true);
  18202. //make sure we have the needed params to get mix and max
  18203. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18204. continue;
  18205. }
  18206. var childBoundingInfo = childMesh.getBoundingInfo();
  18207. var boundingBox = childBoundingInfo.boundingBox;
  18208. var minBox = boundingBox.minimumWorld;
  18209. var maxBox = boundingBox.maximumWorld;
  18210. BABYLON.Tools.CheckExtends(minBox, min, max);
  18211. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18212. }
  18213. }
  18214. return {
  18215. min: min,
  18216. max: max
  18217. };
  18218. };
  18219. /**
  18220. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18221. * Returns the AbstractMesh.
  18222. */
  18223. AbstractMesh.prototype._updateBoundingInfo = function () {
  18224. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18225. this._boundingInfo.update(this.worldMatrixFromCache);
  18226. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18227. return this;
  18228. };
  18229. /**
  18230. * Update a mesh's children BoundingInfo objects only.
  18231. * Returns the AbstractMesh.
  18232. */
  18233. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18234. if (!this.subMeshes) {
  18235. return this;
  18236. }
  18237. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18238. var subMesh = this.subMeshes[subIndex];
  18239. if (!subMesh.IsGlobal) {
  18240. subMesh.updateBoundingInfo(matrix);
  18241. }
  18242. }
  18243. return this;
  18244. };
  18245. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18246. // Bounding info
  18247. this._updateBoundingInfo();
  18248. };
  18249. /**
  18250. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18251. * A mesh is in the frustum if its bounding box intersects the frustum.
  18252. * Boolean returned.
  18253. */
  18254. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18255. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18256. };
  18257. /**
  18258. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18259. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18260. * Boolean returned.
  18261. */
  18262. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18263. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18264. ;
  18265. };
  18266. /**
  18267. * True if the mesh intersects another mesh or a SolidParticle object.
  18268. * 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)
  18269. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18270. * Returns a boolean.
  18271. */
  18272. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18273. if (precise === void 0) { precise = false; }
  18274. if (!this._boundingInfo || !mesh._boundingInfo) {
  18275. return false;
  18276. }
  18277. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18278. return true;
  18279. }
  18280. if (includeDescendants) {
  18281. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18282. var child = _a[_i];
  18283. if (child.intersectsMesh(mesh, precise, true)) {
  18284. return true;
  18285. }
  18286. }
  18287. }
  18288. return false;
  18289. };
  18290. /**
  18291. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18292. * Returns a boolean.
  18293. */
  18294. AbstractMesh.prototype.intersectsPoint = function (point) {
  18295. if (!this._boundingInfo) {
  18296. return false;
  18297. }
  18298. return this._boundingInfo.intersectsPoint(point);
  18299. };
  18300. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18301. return this.physicsImpostor;
  18302. };
  18303. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18304. if (camera === void 0) { camera = null; }
  18305. if (!camera) {
  18306. camera = this.getScene().activeCamera;
  18307. }
  18308. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18309. };
  18310. /**
  18311. * Returns the distance from the mesh to the active camera.
  18312. * Returns a float.
  18313. */
  18314. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18315. if (camera === void 0) { camera = null; }
  18316. if (!camera) {
  18317. camera = this.getScene().activeCamera;
  18318. }
  18319. return this.absolutePosition.subtract(camera.position).length();
  18320. };
  18321. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18322. if (!this.physicsImpostor) {
  18323. return this;
  18324. }
  18325. this.physicsImpostor.applyImpulse(force, contactPoint);
  18326. return this;
  18327. };
  18328. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18329. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18330. return this;
  18331. }
  18332. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18333. mainPivot: pivot1,
  18334. connectedPivot: pivot2,
  18335. nativeParams: options
  18336. });
  18337. return this;
  18338. };
  18339. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18340. // Collisions
  18341. /**
  18342. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18343. * Default `false`.
  18344. */
  18345. get: function () {
  18346. return this._checkCollisions;
  18347. },
  18348. set: function (collisionEnabled) {
  18349. this._checkCollisions = collisionEnabled;
  18350. if (this.getScene().workerCollisions) {
  18351. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18352. }
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18358. /**
  18359. * Gets Collider object used to compute collisions (not physics)
  18360. */
  18361. get: function () {
  18362. return this._collider;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18368. var globalPosition = this.getAbsolutePosition();
  18369. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18370. if (!this._collider) {
  18371. this._collider = new BABYLON.Collider();
  18372. }
  18373. this._collider._radius = this.ellipsoid;
  18374. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18375. return this;
  18376. };
  18377. // Submeshes octree
  18378. /**
  18379. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18380. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18381. * Returns an Octree of submeshes.
  18382. */
  18383. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18384. if (maxCapacity === void 0) { maxCapacity = 64; }
  18385. if (maxDepth === void 0) { maxDepth = 2; }
  18386. if (!this._submeshesOctree) {
  18387. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18388. }
  18389. this.computeWorldMatrix(true);
  18390. var boundingInfo = this.getBoundingInfo();
  18391. // Update octree
  18392. var bbox = boundingInfo.boundingBox;
  18393. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18394. return this._submeshesOctree;
  18395. };
  18396. // Collisions
  18397. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18398. this._generatePointsArray();
  18399. if (!this._positions) {
  18400. return this;
  18401. }
  18402. // Transformation
  18403. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18404. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18405. subMesh._lastColliderWorldVertices = [];
  18406. subMesh._trianglePlanes = [];
  18407. var start = subMesh.verticesStart;
  18408. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18409. for (var i = start; i < end; i++) {
  18410. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18411. }
  18412. }
  18413. // Collide
  18414. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18415. if (collider.collisionFound) {
  18416. collider.collidedMesh = this;
  18417. }
  18418. return this;
  18419. };
  18420. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18421. var subMeshes;
  18422. var len;
  18423. // Octrees
  18424. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18425. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18426. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18427. len = intersections.length;
  18428. subMeshes = intersections.data;
  18429. }
  18430. else {
  18431. subMeshes = this.subMeshes;
  18432. len = subMeshes.length;
  18433. }
  18434. for (var index = 0; index < len; index++) {
  18435. var subMesh = subMeshes[index];
  18436. // Bounding test
  18437. if (len > 1 && !subMesh._checkCollision(collider))
  18438. continue;
  18439. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18440. }
  18441. return this;
  18442. };
  18443. AbstractMesh.prototype._checkCollision = function (collider) {
  18444. // Bounding box test
  18445. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18446. return this;
  18447. // Transformation matrix
  18448. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18449. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18450. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18451. return this;
  18452. };
  18453. // Picking
  18454. AbstractMesh.prototype._generatePointsArray = function () {
  18455. return false;
  18456. };
  18457. /**
  18458. * Checks if the passed Ray intersects with the mesh.
  18459. * Returns an object PickingInfo.
  18460. */
  18461. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18462. var pickingInfo = new BABYLON.PickingInfo();
  18463. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18464. return pickingInfo;
  18465. }
  18466. if (!this._generatePointsArray()) {
  18467. return pickingInfo;
  18468. }
  18469. var intersectInfo = null;
  18470. // Octrees
  18471. var subMeshes;
  18472. var len;
  18473. if (this._submeshesOctree && this.useOctreeForPicking) {
  18474. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18475. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18476. len = intersections.length;
  18477. subMeshes = intersections.data;
  18478. }
  18479. else {
  18480. subMeshes = this.subMeshes;
  18481. len = subMeshes.length;
  18482. }
  18483. for (var index = 0; index < len; index++) {
  18484. var subMesh = subMeshes[index];
  18485. // Bounding test
  18486. if (len > 1 && !subMesh.canIntersects(ray))
  18487. continue;
  18488. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18489. if (currentIntersectInfo) {
  18490. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18491. intersectInfo = currentIntersectInfo;
  18492. intersectInfo.subMeshId = index;
  18493. if (fastCheck) {
  18494. break;
  18495. }
  18496. }
  18497. }
  18498. }
  18499. if (intersectInfo) {
  18500. // Get picked point
  18501. var world = this.getWorldMatrix();
  18502. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18503. var direction = ray.direction.clone();
  18504. direction = direction.scale(intersectInfo.distance);
  18505. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18506. var pickedPoint = worldOrigin.add(worldDirection);
  18507. // Return result
  18508. pickingInfo.hit = true;
  18509. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18510. pickingInfo.pickedPoint = pickedPoint;
  18511. pickingInfo.pickedMesh = this;
  18512. pickingInfo.bu = intersectInfo.bu || 0;
  18513. pickingInfo.bv = intersectInfo.bv || 0;
  18514. pickingInfo.faceId = intersectInfo.faceId;
  18515. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18516. return pickingInfo;
  18517. }
  18518. return pickingInfo;
  18519. };
  18520. /**
  18521. * Clones the mesh, used by the class Mesh.
  18522. * Just returns `null` for an AbstractMesh.
  18523. */
  18524. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18525. return null;
  18526. };
  18527. /**
  18528. * Disposes all the mesh submeshes.
  18529. * Returns the AbstractMesh.
  18530. */
  18531. AbstractMesh.prototype.releaseSubMeshes = function () {
  18532. if (this.subMeshes) {
  18533. while (this.subMeshes.length) {
  18534. this.subMeshes[0].dispose();
  18535. }
  18536. }
  18537. else {
  18538. this.subMeshes = new Array();
  18539. }
  18540. return this;
  18541. };
  18542. /**
  18543. * Releases resources associated with this abstract mesh.
  18544. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18545. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18546. */
  18547. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18548. var _this = this;
  18549. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18550. var index;
  18551. // Smart Array Retainers.
  18552. this.getScene().freeActiveMeshes();
  18553. this.getScene().freeRenderingGroups();
  18554. // Action manager
  18555. if (this.actionManager !== undefined && this.actionManager !== null) {
  18556. this.actionManager.dispose();
  18557. this.actionManager = null;
  18558. }
  18559. // Skeleton
  18560. this.skeleton = null;
  18561. // Physics
  18562. if (this.physicsImpostor) {
  18563. this.physicsImpostor.dispose();
  18564. }
  18565. // Intersections in progress
  18566. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18567. var other = this._intersectionsInProgress[index];
  18568. var pos = other._intersectionsInProgress.indexOf(this);
  18569. other._intersectionsInProgress.splice(pos, 1);
  18570. }
  18571. this._intersectionsInProgress = [];
  18572. // Lights
  18573. var lights = this.getScene().lights;
  18574. lights.forEach(function (light) {
  18575. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18576. if (meshIndex !== -1) {
  18577. light.includedOnlyMeshes.splice(meshIndex, 1);
  18578. }
  18579. meshIndex = light.excludedMeshes.indexOf(_this);
  18580. if (meshIndex !== -1) {
  18581. light.excludedMeshes.splice(meshIndex, 1);
  18582. }
  18583. // Shadow generators
  18584. var generator = light.getShadowGenerator();
  18585. if (generator) {
  18586. var shadowMap = generator.getShadowMap();
  18587. if (shadowMap && shadowMap.renderList) {
  18588. meshIndex = shadowMap.renderList.indexOf(_this);
  18589. if (meshIndex !== -1) {
  18590. shadowMap.renderList.splice(meshIndex, 1);
  18591. }
  18592. }
  18593. }
  18594. });
  18595. // Edges
  18596. if (this._edgesRenderer) {
  18597. this._edgesRenderer.dispose();
  18598. this._edgesRenderer = null;
  18599. }
  18600. // SubMeshes
  18601. if (this.getClassName() !== "InstancedMesh") {
  18602. this.releaseSubMeshes();
  18603. }
  18604. // Octree
  18605. var sceneOctree = this.getScene().selectionOctree;
  18606. if (sceneOctree !== undefined && sceneOctree !== null) {
  18607. var index = sceneOctree.dynamicContent.indexOf(this);
  18608. if (index !== -1) {
  18609. sceneOctree.dynamicContent.splice(index, 1);
  18610. }
  18611. }
  18612. // Query
  18613. var engine = this.getScene().getEngine();
  18614. if (this._occlusionQuery) {
  18615. this._isOcclusionQueryInProgress = false;
  18616. engine.deleteQuery(this._occlusionQuery);
  18617. this._occlusionQuery = null;
  18618. }
  18619. // Engine
  18620. engine.wipeCaches();
  18621. // Remove from scene
  18622. this.getScene().removeMesh(this);
  18623. if (disposeMaterialAndTextures) {
  18624. if (this.material) {
  18625. this.material.dispose(false, true);
  18626. }
  18627. }
  18628. if (!doNotRecurse) {
  18629. // Particles
  18630. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18631. if (this.getScene().particleSystems[index].emitter === this) {
  18632. this.getScene().particleSystems[index].dispose();
  18633. index--;
  18634. }
  18635. }
  18636. }
  18637. // facet data
  18638. if (this._facetDataEnabled) {
  18639. this.disableFacetData();
  18640. }
  18641. this.onAfterWorldMatrixUpdateObservable.clear();
  18642. this.onCollideObservable.clear();
  18643. this.onCollisionPositionChangeObservable.clear();
  18644. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18645. };
  18646. /**
  18647. * Adds the passed mesh as a child to the current mesh.
  18648. * Returns the AbstractMesh.
  18649. */
  18650. AbstractMesh.prototype.addChild = function (mesh) {
  18651. mesh.setParent(this);
  18652. return this;
  18653. };
  18654. /**
  18655. * Removes the passed mesh from the current mesh children list.
  18656. * Returns the AbstractMesh.
  18657. */
  18658. AbstractMesh.prototype.removeChild = function (mesh) {
  18659. mesh.setParent(null);
  18660. return this;
  18661. };
  18662. // Facet data
  18663. /**
  18664. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18665. * Returns the AbstractMesh.
  18666. */
  18667. AbstractMesh.prototype._initFacetData = function () {
  18668. if (!this._facetNormals) {
  18669. this._facetNormals = new Array();
  18670. }
  18671. if (!this._facetPositions) {
  18672. this._facetPositions = new Array();
  18673. }
  18674. if (!this._facetPartitioning) {
  18675. this._facetPartitioning = new Array();
  18676. }
  18677. this._facetNb = (this.getIndices().length / 3) | 0;
  18678. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18679. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18680. for (var f = 0; f < this._facetNb; f++) {
  18681. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18682. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18683. }
  18684. this._facetDataEnabled = true;
  18685. return this;
  18686. };
  18687. /**
  18688. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18689. * This method can be called within the render loop.
  18690. * 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.
  18691. * Returns the AbstractMesh.
  18692. */
  18693. AbstractMesh.prototype.updateFacetData = function () {
  18694. if (!this._facetDataEnabled) {
  18695. this._initFacetData();
  18696. }
  18697. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18698. var indices = this.getIndices();
  18699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18700. var bInfo = this.getBoundingInfo();
  18701. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18702. // init arrays, matrix and sort function on first call
  18703. this._facetDepthSortEnabled = true;
  18704. if (indices instanceof Uint16Array) {
  18705. this._depthSortedIndices = new Uint16Array(indices);
  18706. }
  18707. else if (indices instanceof Uint32Array) {
  18708. this._depthSortedIndices = new Uint32Array(indices);
  18709. }
  18710. else {
  18711. var needs32bits = false;
  18712. for (var i = 0; i < indices.length; i++) {
  18713. if (indices[i] > 65535) {
  18714. needs32bits = true;
  18715. break;
  18716. }
  18717. }
  18718. if (needs32bits) {
  18719. this._depthSortedIndices = new Uint32Array(indices);
  18720. }
  18721. else {
  18722. this._depthSortedIndices = new Uint16Array(indices);
  18723. }
  18724. }
  18725. this._facetDepthSortFunction = function (f1, f2) {
  18726. return (f2.sqDistance - f1.sqDistance);
  18727. };
  18728. if (!this._facetDepthSortFrom) {
  18729. var camera = this.getScene().activeCamera;
  18730. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18731. }
  18732. this._depthSortedFacets = [];
  18733. for (var f = 0; f < this._facetNb; f++) {
  18734. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18735. this._depthSortedFacets.push(depthSortedFacet);
  18736. }
  18737. this._invertedMatrix = BABYLON.Matrix.Identity();
  18738. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18739. }
  18740. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18741. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18742. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18743. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18744. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18745. this._subDiv.max = this._partitioningSubdivisions;
  18746. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18747. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18748. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18749. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18750. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18751. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18752. // set the parameters for ComputeNormals()
  18753. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18754. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18755. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18756. this._facetParameters.bInfo = bInfo;
  18757. this._facetParameters.bbSize = this._bbSize;
  18758. this._facetParameters.subDiv = this._subDiv;
  18759. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18760. this._facetParameters.depthSort = this._facetDepthSort;
  18761. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18762. this.computeWorldMatrix(true);
  18763. this._worldMatrix.invertToRef(this._invertedMatrix);
  18764. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18765. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18766. }
  18767. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18768. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18769. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18770. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18771. var l = (this._depthSortedIndices.length / 3) | 0;
  18772. for (var f = 0; f < l; f++) {
  18773. var sind = this._depthSortedFacets[f].ind;
  18774. this._depthSortedIndices[f * 3] = indices[sind];
  18775. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18776. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18777. }
  18778. this.updateIndices(this._depthSortedIndices);
  18779. }
  18780. return this;
  18781. };
  18782. /**
  18783. * Returns the facetLocalNormals array.
  18784. * The normals are expressed in the mesh local space.
  18785. */
  18786. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18787. if (!this._facetNormals) {
  18788. this.updateFacetData();
  18789. }
  18790. return this._facetNormals;
  18791. };
  18792. /**
  18793. * Returns the facetLocalPositions array.
  18794. * The facet positions are expressed in the mesh local space.
  18795. */
  18796. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18797. if (!this._facetPositions) {
  18798. this.updateFacetData();
  18799. }
  18800. return this._facetPositions;
  18801. };
  18802. /**
  18803. * Returns the facetLocalPartioning array.
  18804. */
  18805. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18806. if (!this._facetPartitioning) {
  18807. this.updateFacetData();
  18808. }
  18809. return this._facetPartitioning;
  18810. };
  18811. /**
  18812. * Returns the i-th facet position in the world system.
  18813. * This method allocates a new Vector3 per call.
  18814. */
  18815. AbstractMesh.prototype.getFacetPosition = function (i) {
  18816. var pos = BABYLON.Vector3.Zero();
  18817. this.getFacetPositionToRef(i, pos);
  18818. return pos;
  18819. };
  18820. /**
  18821. * Sets the reference Vector3 with the i-th facet position in the world system.
  18822. * Returns the AbstractMesh.
  18823. */
  18824. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18825. var localPos = (this.getFacetLocalPositions())[i];
  18826. var world = this.getWorldMatrix();
  18827. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18828. return this;
  18829. };
  18830. /**
  18831. * Returns the i-th facet normal in the world system.
  18832. * This method allocates a new Vector3 per call.
  18833. */
  18834. AbstractMesh.prototype.getFacetNormal = function (i) {
  18835. var norm = BABYLON.Vector3.Zero();
  18836. this.getFacetNormalToRef(i, norm);
  18837. return norm;
  18838. };
  18839. /**
  18840. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18841. * Returns the AbstractMesh.
  18842. */
  18843. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18844. var localNorm = (this.getFacetLocalNormals())[i];
  18845. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18846. return this;
  18847. };
  18848. /**
  18849. * 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).
  18850. */
  18851. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18852. var bInfo = this.getBoundingInfo();
  18853. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18854. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18855. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18856. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18857. return null;
  18858. }
  18859. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18860. };
  18861. /**
  18862. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18863. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18864. * 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.
  18865. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18866. * 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.
  18867. */
  18868. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18869. if (checkFace === void 0) { checkFace = false; }
  18870. if (facing === void 0) { facing = true; }
  18871. var world = this.getWorldMatrix();
  18872. var invMat = BABYLON.Tmp.Matrix[5];
  18873. world.invertToRef(invMat);
  18874. var invVect = BABYLON.Tmp.Vector3[8];
  18875. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18876. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18877. if (projected) {
  18878. // tranform the local computed projected vector to world coordinates
  18879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18880. }
  18881. return closest;
  18882. };
  18883. /**
  18884. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18885. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18886. * 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.
  18887. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18888. * 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.
  18889. */
  18890. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18891. if (checkFace === void 0) { checkFace = false; }
  18892. if (facing === void 0) { facing = true; }
  18893. var closest = null;
  18894. var tmpx = 0.0;
  18895. var tmpy = 0.0;
  18896. var tmpz = 0.0;
  18897. var d = 0.0; // tmp dot facet normal * facet position
  18898. var t0 = 0.0;
  18899. var projx = 0.0;
  18900. var projy = 0.0;
  18901. var projz = 0.0;
  18902. // Get all the facets in the same partitioning block than (x, y, z)
  18903. var facetPositions = this.getFacetLocalPositions();
  18904. var facetNormals = this.getFacetLocalNormals();
  18905. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18906. if (!facetsInBlock) {
  18907. return null;
  18908. }
  18909. // Get the closest facet to (x, y, z)
  18910. var shortest = Number.MAX_VALUE; // init distance vars
  18911. var tmpDistance = shortest;
  18912. var fib; // current facet in the block
  18913. var norm; // current facet normal
  18914. var p0; // current facet barycenter position
  18915. // loop on all the facets in the current partitioning block
  18916. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18917. fib = facetsInBlock[idx];
  18918. norm = facetNormals[fib];
  18919. p0 = facetPositions[fib];
  18920. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18921. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18922. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18923. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18924. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18925. projx = x + norm.x * t0;
  18926. projy = y + norm.y * t0;
  18927. projz = z + norm.z * t0;
  18928. tmpx = projx - x;
  18929. tmpy = projy - y;
  18930. tmpz = projz - z;
  18931. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18932. if (tmpDistance < shortest) {
  18933. shortest = tmpDistance;
  18934. closest = fib;
  18935. if (projected) {
  18936. projected.x = projx;
  18937. projected.y = projy;
  18938. projected.z = projz;
  18939. }
  18940. }
  18941. }
  18942. }
  18943. return closest;
  18944. };
  18945. /**
  18946. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18947. */
  18948. AbstractMesh.prototype.getFacetDataParameters = function () {
  18949. return this._facetParameters;
  18950. };
  18951. /**
  18952. * Disables the feature FacetData and frees the related memory.
  18953. * Returns the AbstractMesh.
  18954. */
  18955. AbstractMesh.prototype.disableFacetData = function () {
  18956. if (this._facetDataEnabled) {
  18957. this._facetDataEnabled = false;
  18958. this._facetPositions = new Array();
  18959. this._facetNormals = new Array();
  18960. this._facetPartitioning = new Array();
  18961. this._facetParameters = null;
  18962. this._depthSortedIndices = new Uint32Array(0);
  18963. }
  18964. return this;
  18965. };
  18966. /**
  18967. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18968. * Returns the mesh.
  18969. */
  18970. AbstractMesh.prototype.updateIndices = function (indices) {
  18971. return this;
  18972. };
  18973. /**
  18974. * The mesh Geometry. Actually used by the Mesh object.
  18975. * Returns a blank geometry object.
  18976. */
  18977. /**
  18978. * Creates new normals data for the mesh.
  18979. * @param updatable.
  18980. */
  18981. AbstractMesh.prototype.createNormals = function (updatable) {
  18982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18983. var indices = this.getIndices();
  18984. var normals;
  18985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18986. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18987. }
  18988. else {
  18989. normals = [];
  18990. }
  18991. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18992. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18993. };
  18994. /**
  18995. * Align the mesh with a normal.
  18996. * Returns the mesh.
  18997. */
  18998. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18999. if (!upDirection) {
  19000. upDirection = BABYLON.Axis.Y;
  19001. }
  19002. var axisX = BABYLON.Tmp.Vector3[0];
  19003. var axisZ = BABYLON.Tmp.Vector3[1];
  19004. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19005. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19006. if (this.rotationQuaternion) {
  19007. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19008. }
  19009. else {
  19010. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19011. }
  19012. return this;
  19013. };
  19014. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19015. var engine = this.getEngine();
  19016. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19017. this._isOccluded = false;
  19018. return;
  19019. }
  19020. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19021. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19022. if (isOcclusionQueryAvailable) {
  19023. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19024. this._isOcclusionQueryInProgress = false;
  19025. this._occlusionInternalRetryCounter = 0;
  19026. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19027. }
  19028. else {
  19029. this._occlusionInternalRetryCounter++;
  19030. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19031. this._isOcclusionQueryInProgress = false;
  19032. this._occlusionInternalRetryCounter = 0;
  19033. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19034. // if strict continue the last state of the object.
  19035. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19036. }
  19037. else {
  19038. return;
  19039. }
  19040. }
  19041. }
  19042. var scene = this.getScene();
  19043. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19044. if (!this._occlusionQuery) {
  19045. this._occlusionQuery = engine.createQuery();
  19046. }
  19047. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19048. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19049. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19050. this._isOcclusionQueryInProgress = true;
  19051. };
  19052. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19053. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19054. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19055. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19056. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19057. return AbstractMesh;
  19058. }(BABYLON.TransformNode));
  19059. BABYLON.AbstractMesh = AbstractMesh;
  19060. })(BABYLON || (BABYLON = {}));
  19061. //# sourceMappingURL=babylon.abstractMesh.js.map
  19062. var BABYLON;
  19063. (function (BABYLON) {
  19064. /**
  19065. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19066. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19067. * 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.
  19068. */
  19069. var Light = /** @class */ (function (_super) {
  19070. __extends(Light, _super);
  19071. /**
  19072. * Creates a Light object in the scene.
  19073. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19074. * @param name The firendly name of the light
  19075. * @param scene The scene the light belongs too
  19076. */
  19077. function Light(name, scene) {
  19078. var _this = _super.call(this, name, scene) || this;
  19079. /**
  19080. * Diffuse gives the basic color to an object.
  19081. */
  19082. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19083. /**
  19084. * Specular produces a highlight color on an object.
  19085. * Note: This is note affecting PBR materials.
  19086. */
  19087. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19088. /**
  19089. * Strength of the light.
  19090. * Note: By default it is define in the framework own unit.
  19091. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19092. */
  19093. _this.intensity = 1.0;
  19094. /**
  19095. * Defines how far from the source the light is impacting in scene units.
  19096. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19097. */
  19098. _this.range = Number.MAX_VALUE;
  19099. /**
  19100. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19101. * of light.
  19102. */
  19103. _this._photometricScale = 1.0;
  19104. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19105. _this._radius = 0.00001;
  19106. /**
  19107. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19108. * exceeding the number allowed of the materials.
  19109. */
  19110. _this.renderPriority = 0;
  19111. /**
  19112. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19113. * the current shadow generator.
  19114. */
  19115. _this.shadowEnabled = true;
  19116. _this._excludeWithLayerMask = 0;
  19117. _this._includeOnlyWithLayerMask = 0;
  19118. _this._lightmapMode = 0;
  19119. /**
  19120. * @ignore Internal use only.
  19121. */
  19122. _this._excludedMeshesIds = new Array();
  19123. /**
  19124. * @ignore Internal use only.
  19125. */
  19126. _this._includedOnlyMeshesIds = new Array();
  19127. _this.getScene().addLight(_this);
  19128. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19129. _this._buildUniformLayout();
  19130. _this.includedOnlyMeshes = new Array();
  19131. _this.excludedMeshes = new Array();
  19132. _this._resyncMeshes();
  19133. return _this;
  19134. }
  19135. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19136. /**
  19137. * If every light affecting the material is in this lightmapMode,
  19138. * material.lightmapTexture adds or multiplies
  19139. * (depends on material.useLightmapAsShadowmap)
  19140. * after every other light calculations.
  19141. */
  19142. get: function () {
  19143. return Light._LIGHTMAP_DEFAULT;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19149. /**
  19150. * material.lightmapTexture as only diffuse lighting from this light
  19151. * adds only specular lighting from this light
  19152. * adds dynamic shadows
  19153. */
  19154. get: function () {
  19155. return Light._LIGHTMAP_SPECULAR;
  19156. },
  19157. enumerable: true,
  19158. configurable: true
  19159. });
  19160. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19161. /**
  19162. * material.lightmapTexture as only lighting
  19163. * no light calculation from this light
  19164. * only adds dynamic shadows from this light
  19165. */
  19166. get: function () {
  19167. return Light._LIGHTMAP_SHADOWSONLY;
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19173. /**
  19174. * Each light type uses the default quantity according to its type:
  19175. * point/spot lights use luminous intensity
  19176. * directional lights use illuminance
  19177. */
  19178. get: function () {
  19179. return Light._INTENSITYMODE_AUTOMATIC;
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19185. /**
  19186. * lumen (lm)
  19187. */
  19188. get: function () {
  19189. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19190. },
  19191. enumerable: true,
  19192. configurable: true
  19193. });
  19194. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19195. /**
  19196. * candela (lm/sr)
  19197. */
  19198. get: function () {
  19199. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19200. },
  19201. enumerable: true,
  19202. configurable: true
  19203. });
  19204. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19205. /**
  19206. * lux (lm/m^2)
  19207. */
  19208. get: function () {
  19209. return Light._INTENSITYMODE_ILLUMINANCE;
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19215. /**
  19216. * nit (cd/m^2)
  19217. */
  19218. get: function () {
  19219. return Light._INTENSITYMODE_LUMINANCE;
  19220. },
  19221. enumerable: true,
  19222. configurable: true
  19223. });
  19224. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19225. /**
  19226. * Light type const id of the point light.
  19227. */
  19228. get: function () {
  19229. return Light._LIGHTTYPEID_POINTLIGHT;
  19230. },
  19231. enumerable: true,
  19232. configurable: true
  19233. });
  19234. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19235. /**
  19236. * Light type const id of the directional light.
  19237. */
  19238. get: function () {
  19239. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19240. },
  19241. enumerable: true,
  19242. configurable: true
  19243. });
  19244. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19245. /**
  19246. * Light type const id of the spot light.
  19247. */
  19248. get: function () {
  19249. return Light._LIGHTTYPEID_SPOTLIGHT;
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19255. /**
  19256. * Light type const id of the hemispheric light.
  19257. */
  19258. get: function () {
  19259. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19260. },
  19261. enumerable: true,
  19262. configurable: true
  19263. });
  19264. Object.defineProperty(Light.prototype, "intensityMode", {
  19265. /**
  19266. * Gets the photometric scale used to interpret the intensity.
  19267. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19268. */
  19269. get: function () {
  19270. return this._intensityMode;
  19271. },
  19272. /**
  19273. * Sets the photometric scale used to interpret the intensity.
  19274. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19275. */
  19276. set: function (value) {
  19277. this._intensityMode = value;
  19278. this._computePhotometricScale();
  19279. },
  19280. enumerable: true,
  19281. configurable: true
  19282. });
  19283. ;
  19284. ;
  19285. Object.defineProperty(Light.prototype, "radius", {
  19286. /**
  19287. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19288. */
  19289. get: function () {
  19290. return this._radius;
  19291. },
  19292. /**
  19293. * sets the light radius used by PBR Materials to simulate soft area lights.
  19294. */
  19295. set: function (value) {
  19296. this._radius = value;
  19297. this._computePhotometricScale();
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. ;
  19303. ;
  19304. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19305. /**
  19306. * Gets the only meshes impacted by this light.
  19307. */
  19308. get: function () {
  19309. return this._includedOnlyMeshes;
  19310. },
  19311. /**
  19312. * Sets the only meshes impacted by this light.
  19313. */
  19314. set: function (value) {
  19315. this._includedOnlyMeshes = value;
  19316. this._hookArrayForIncludedOnly(value);
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19322. /**
  19323. * Gets the meshes not impacted by this light.
  19324. */
  19325. get: function () {
  19326. return this._excludedMeshes;
  19327. },
  19328. /**
  19329. * Sets the meshes not impacted by this light.
  19330. */
  19331. set: function (value) {
  19332. this._excludedMeshes = value;
  19333. this._hookArrayForExcluded(value);
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19339. /**
  19340. * Gets the layer id use to find what meshes are not impacted by the light.
  19341. * Inactive if 0
  19342. */
  19343. get: function () {
  19344. return this._excludeWithLayerMask;
  19345. },
  19346. /**
  19347. * Sets the layer id use to find what meshes are not impacted by the light.
  19348. * Inactive if 0
  19349. */
  19350. set: function (value) {
  19351. this._excludeWithLayerMask = value;
  19352. this._resyncMeshes();
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19358. /**
  19359. * Gets the layer id use to find what meshes are impacted by the light.
  19360. * Inactive if 0
  19361. */
  19362. get: function () {
  19363. return this._includeOnlyWithLayerMask;
  19364. },
  19365. /**
  19366. * Sets the layer id use to find what meshes are impacted by the light.
  19367. * Inactive if 0
  19368. */
  19369. set: function (value) {
  19370. this._includeOnlyWithLayerMask = value;
  19371. this._resyncMeshes();
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Light.prototype, "lightmapMode", {
  19377. /**
  19378. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19379. */
  19380. get: function () {
  19381. return this._lightmapMode;
  19382. },
  19383. /**
  19384. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19385. */
  19386. set: function (value) {
  19387. if (this._lightmapMode === value) {
  19388. return;
  19389. }
  19390. this._lightmapMode = value;
  19391. this._markMeshesAsLightDirty();
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. /**
  19397. * Returns the string "Light".
  19398. * @returns the class name
  19399. */
  19400. Light.prototype.getClassName = function () {
  19401. return "Light";
  19402. };
  19403. /**
  19404. * Converts the light information to a readable string for debug purpose.
  19405. * @param fullDetails Supports for multiple levels of logging within scene loading
  19406. * @returns the human readable light info
  19407. */
  19408. Light.prototype.toString = function (fullDetails) {
  19409. var ret = "Name: " + this.name;
  19410. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19411. if (this.animations) {
  19412. for (var i = 0; i < this.animations.length; i++) {
  19413. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19414. }
  19415. }
  19416. if (fullDetails) {
  19417. }
  19418. return ret;
  19419. };
  19420. /**
  19421. * Set the enabled state of this node.
  19422. * @param value - the new enabled state
  19423. * @see isEnabled
  19424. */
  19425. Light.prototype.setEnabled = function (value) {
  19426. _super.prototype.setEnabled.call(this, value);
  19427. this._resyncMeshes();
  19428. };
  19429. /**
  19430. * Returns the Light associated shadow generator if any.
  19431. * @return the associated shadow generator.
  19432. */
  19433. Light.prototype.getShadowGenerator = function () {
  19434. return this._shadowGenerator;
  19435. };
  19436. /**
  19437. * Returns a Vector3, the absolute light position in the World.
  19438. * @returns the world space position of the light
  19439. */
  19440. Light.prototype.getAbsolutePosition = function () {
  19441. return BABYLON.Vector3.Zero();
  19442. };
  19443. /**
  19444. * Specifies if the light will affect the passed mesh.
  19445. * @param mesh The mesh to test against the light
  19446. * @return true the mesh is affected otherwise, false.
  19447. */
  19448. Light.prototype.canAffectMesh = function (mesh) {
  19449. if (!mesh) {
  19450. return true;
  19451. }
  19452. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19453. return false;
  19454. }
  19455. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19456. return false;
  19457. }
  19458. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19459. return false;
  19460. }
  19461. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19462. return false;
  19463. }
  19464. return true;
  19465. };
  19466. /**
  19467. * Computes and Returns the light World matrix.
  19468. * @returns the world matrix
  19469. */
  19470. Light.prototype.getWorldMatrix = function () {
  19471. this._currentRenderId = this.getScene().getRenderId();
  19472. var worldMatrix = this._getWorldMatrix();
  19473. if (this.parent && this.parent.getWorldMatrix) {
  19474. if (!this._parentedWorldMatrix) {
  19475. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19476. }
  19477. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19478. this._markSyncedWithParent();
  19479. return this._parentedWorldMatrix;
  19480. }
  19481. return worldMatrix;
  19482. };
  19483. /**
  19484. * Sort function to order lights for rendering.
  19485. * @param a First Light object to compare to second.
  19486. * @param b Second Light object to compare first.
  19487. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19488. */
  19489. Light.CompareLightsPriority = function (a, b) {
  19490. //shadow-casting lights have priority over non-shadow-casting lights
  19491. //the renderPrioirty is a secondary sort criterion
  19492. if (a.shadowEnabled !== b.shadowEnabled) {
  19493. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19494. }
  19495. return b.renderPriority - a.renderPriority;
  19496. };
  19497. /**
  19498. * Releases resources associated with this node.
  19499. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19500. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19501. */
  19502. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19504. if (this._shadowGenerator) {
  19505. this._shadowGenerator.dispose();
  19506. this._shadowGenerator = null;
  19507. }
  19508. // Animations
  19509. this.getScene().stopAnimation(this);
  19510. // Remove from meshes
  19511. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19512. var mesh = _a[_i];
  19513. mesh._removeLightSource(this);
  19514. }
  19515. this._uniformBuffer.dispose();
  19516. // Remove from scene
  19517. this.getScene().removeLight(this);
  19518. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19519. };
  19520. /**
  19521. * Returns the light type ID (integer).
  19522. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19523. */
  19524. Light.prototype.getTypeID = function () {
  19525. return 0;
  19526. };
  19527. /**
  19528. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19529. * @returns the scaled intensity in intensity mode unit
  19530. */
  19531. Light.prototype.getScaledIntensity = function () {
  19532. return this._photometricScale * this.intensity;
  19533. };
  19534. /**
  19535. * Returns a new Light object, named "name", from the current one.
  19536. * @param name The name of the cloned light
  19537. * @returns the new created light
  19538. */
  19539. Light.prototype.clone = function (name) {
  19540. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19541. if (!constructor) {
  19542. return null;
  19543. }
  19544. return BABYLON.SerializationHelper.Clone(constructor, this);
  19545. };
  19546. /**
  19547. * Serializes the current light into a Serialization object.
  19548. * @returns the serialized object.
  19549. */
  19550. Light.prototype.serialize = function () {
  19551. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19552. // Type
  19553. serializationObject.type = this.getTypeID();
  19554. // Parent
  19555. if (this.parent) {
  19556. serializationObject.parentId = this.parent.id;
  19557. }
  19558. // Inclusion / exclusions
  19559. if (this.excludedMeshes.length > 0) {
  19560. serializationObject.excludedMeshesIds = [];
  19561. this.excludedMeshes.forEach(function (mesh) {
  19562. serializationObject.excludedMeshesIds.push(mesh.id);
  19563. });
  19564. }
  19565. if (this.includedOnlyMeshes.length > 0) {
  19566. serializationObject.includedOnlyMeshesIds = [];
  19567. this.includedOnlyMeshes.forEach(function (mesh) {
  19568. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19569. });
  19570. }
  19571. // Animations
  19572. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19573. serializationObject.ranges = this.serializeAnimationRanges();
  19574. return serializationObject;
  19575. };
  19576. /**
  19577. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19578. * This new light is named "name" and added to the passed scene.
  19579. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19580. * @param name The friendly name of the light
  19581. * @param scene The scene the new light will belong to
  19582. * @returns the constructor function
  19583. */
  19584. Light.GetConstructorFromName = function (type, name, scene) {
  19585. switch (type) {
  19586. case 0:
  19587. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19588. case 1:
  19589. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19590. case 2:
  19591. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19592. case 3:
  19593. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19594. }
  19595. return null;
  19596. };
  19597. /**
  19598. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19599. * @param parsedLight The JSON representation of the light
  19600. * @param scene The scene to create the parsed light in
  19601. * @returns the created light after parsing
  19602. */
  19603. Light.Parse = function (parsedLight, scene) {
  19604. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19605. if (!constructor) {
  19606. return null;
  19607. }
  19608. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19609. // Inclusion / exclusions
  19610. if (parsedLight.excludedMeshesIds) {
  19611. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19612. }
  19613. if (parsedLight.includedOnlyMeshesIds) {
  19614. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19615. }
  19616. // Parent
  19617. if (parsedLight.parentId) {
  19618. light._waitingParentId = parsedLight.parentId;
  19619. }
  19620. // Animations
  19621. if (parsedLight.animations) {
  19622. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19623. var parsedAnimation = parsedLight.animations[animationIndex];
  19624. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19625. }
  19626. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19627. }
  19628. if (parsedLight.autoAnimate) {
  19629. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19630. }
  19631. return light;
  19632. };
  19633. Light.prototype._hookArrayForExcluded = function (array) {
  19634. var _this = this;
  19635. var oldPush = array.push;
  19636. array.push = function () {
  19637. var items = [];
  19638. for (var _i = 0; _i < arguments.length; _i++) {
  19639. items[_i] = arguments[_i];
  19640. }
  19641. var result = oldPush.apply(array, items);
  19642. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19643. var item = items_1[_a];
  19644. item._resyncLighSource(_this);
  19645. }
  19646. return result;
  19647. };
  19648. var oldSplice = array.splice;
  19649. array.splice = function (index, deleteCount) {
  19650. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19651. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19652. var item = deleted_1[_i];
  19653. item._resyncLighSource(_this);
  19654. }
  19655. return deleted;
  19656. };
  19657. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19658. var item = array_1[_i];
  19659. item._resyncLighSource(this);
  19660. }
  19661. };
  19662. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19663. var _this = this;
  19664. var oldPush = array.push;
  19665. array.push = function () {
  19666. var items = [];
  19667. for (var _i = 0; _i < arguments.length; _i++) {
  19668. items[_i] = arguments[_i];
  19669. }
  19670. var result = oldPush.apply(array, items);
  19671. _this._resyncMeshes();
  19672. return result;
  19673. };
  19674. var oldSplice = array.splice;
  19675. array.splice = function (index, deleteCount) {
  19676. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19677. _this._resyncMeshes();
  19678. return deleted;
  19679. };
  19680. this._resyncMeshes();
  19681. };
  19682. Light.prototype._resyncMeshes = function () {
  19683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19684. var mesh = _a[_i];
  19685. mesh._resyncLighSource(this);
  19686. }
  19687. };
  19688. /**
  19689. * Forces the meshes to update their light related information in their rendering used effects
  19690. * @ignore Internal Use Only
  19691. */
  19692. Light.prototype._markMeshesAsLightDirty = function () {
  19693. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19694. var mesh = _a[_i];
  19695. if (mesh._lightSources.indexOf(this) !== -1) {
  19696. mesh._markSubMeshesAsLightDirty();
  19697. }
  19698. }
  19699. };
  19700. /**
  19701. * Recomputes the cached photometric scale if needed.
  19702. */
  19703. Light.prototype._computePhotometricScale = function () {
  19704. this._photometricScale = this._getPhotometricScale();
  19705. this.getScene().resetCachedMaterial();
  19706. };
  19707. /**
  19708. * Returns the Photometric Scale according to the light type and intensity mode.
  19709. */
  19710. Light.prototype._getPhotometricScale = function () {
  19711. var photometricScale = 0.0;
  19712. var lightTypeID = this.getTypeID();
  19713. //get photometric mode
  19714. var photometricMode = this.intensityMode;
  19715. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19716. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19717. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19718. }
  19719. else {
  19720. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19721. }
  19722. }
  19723. //compute photometric scale
  19724. switch (lightTypeID) {
  19725. case Light.LIGHTTYPEID_POINTLIGHT:
  19726. case Light.LIGHTTYPEID_SPOTLIGHT:
  19727. switch (photometricMode) {
  19728. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19729. photometricScale = 1.0 / (4.0 * Math.PI);
  19730. break;
  19731. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19732. photometricScale = 1.0;
  19733. break;
  19734. case Light.INTENSITYMODE_LUMINANCE:
  19735. photometricScale = this.radius * this.radius;
  19736. break;
  19737. }
  19738. break;
  19739. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19740. switch (photometricMode) {
  19741. case Light.INTENSITYMODE_ILLUMINANCE:
  19742. photometricScale = 1.0;
  19743. break;
  19744. case Light.INTENSITYMODE_LUMINANCE:
  19745. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19746. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19747. var apexAngleRadians = this.radius;
  19748. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19749. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19750. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19751. photometricScale = solidAngle;
  19752. break;
  19753. }
  19754. break;
  19755. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19756. // No fall off in hemisperic light.
  19757. photometricScale = 1.0;
  19758. break;
  19759. }
  19760. return photometricScale;
  19761. };
  19762. /**
  19763. * Reorder the light in the scene according to their defined priority.
  19764. * @ignore Internal Use Only
  19765. */
  19766. Light.prototype._reorderLightsInScene = function () {
  19767. var scene = this.getScene();
  19768. if (this._renderPriority != 0) {
  19769. scene.requireLightSorting = true;
  19770. }
  19771. this.getScene().sortLightsByPriority();
  19772. };
  19773. //lightmapMode Consts
  19774. Light._LIGHTMAP_DEFAULT = 0;
  19775. Light._LIGHTMAP_SPECULAR = 1;
  19776. Light._LIGHTMAP_SHADOWSONLY = 2;
  19777. // Intensity Mode Consts
  19778. Light._INTENSITYMODE_AUTOMATIC = 0;
  19779. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19780. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19781. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19782. Light._INTENSITYMODE_LUMINANCE = 4;
  19783. // Light types ids const.
  19784. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19785. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19786. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19787. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19788. __decorate([
  19789. BABYLON.serializeAsColor3()
  19790. ], Light.prototype, "diffuse", void 0);
  19791. __decorate([
  19792. BABYLON.serializeAsColor3()
  19793. ], Light.prototype, "specular", void 0);
  19794. __decorate([
  19795. BABYLON.serialize()
  19796. ], Light.prototype, "intensity", void 0);
  19797. __decorate([
  19798. BABYLON.serialize()
  19799. ], Light.prototype, "range", void 0);
  19800. __decorate([
  19801. BABYLON.serialize()
  19802. ], Light.prototype, "intensityMode", null);
  19803. __decorate([
  19804. BABYLON.serialize()
  19805. ], Light.prototype, "radius", null);
  19806. __decorate([
  19807. BABYLON.serialize()
  19808. ], Light.prototype, "_renderPriority", void 0);
  19809. __decorate([
  19810. BABYLON.expandToProperty("_reorderLightsInScene")
  19811. ], Light.prototype, "renderPriority", void 0);
  19812. __decorate([
  19813. BABYLON.serialize()
  19814. ], Light.prototype, "shadowEnabled", void 0);
  19815. __decorate([
  19816. BABYLON.serialize("excludeWithLayerMask")
  19817. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19818. __decorate([
  19819. BABYLON.serialize("includeOnlyWithLayerMask")
  19820. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19821. __decorate([
  19822. BABYLON.serialize("lightmapMode")
  19823. ], Light.prototype, "_lightmapMode", void 0);
  19824. return Light;
  19825. }(BABYLON.Node));
  19826. BABYLON.Light = Light;
  19827. })(BABYLON || (BABYLON = {}));
  19828. //# sourceMappingURL=babylon.light.js.map
  19829. var BABYLON;
  19830. (function (BABYLON) {
  19831. var Camera = /** @class */ (function (_super) {
  19832. __extends(Camera, _super);
  19833. function Camera(name, position, scene) {
  19834. var _this = _super.call(this, name, scene) || this;
  19835. /**
  19836. * The vector the camera should consider as up.
  19837. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19838. */
  19839. _this.upVector = BABYLON.Vector3.Up();
  19840. _this.orthoLeft = null;
  19841. _this.orthoRight = null;
  19842. _this.orthoBottom = null;
  19843. _this.orthoTop = null;
  19844. /**
  19845. * FOV is set in Radians. (default is 0.8)
  19846. */
  19847. _this.fov = 0.8;
  19848. _this.minZ = 1;
  19849. _this.maxZ = 10000.0;
  19850. _this.inertia = 0.9;
  19851. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19852. _this.isIntermediate = false;
  19853. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19854. /**
  19855. * Restricts the camera to viewing objects with the same layerMask.
  19856. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19857. */
  19858. _this.layerMask = 0x0FFFFFFF;
  19859. /**
  19860. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19861. */
  19862. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19863. // Camera rig members
  19864. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19865. _this._rigCameras = new Array();
  19866. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19867. _this._skipRendering = false;
  19868. _this.customRenderTargets = new Array();
  19869. // Observables
  19870. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19871. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19872. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19873. _this.onRestoreStateObservable = new BABYLON.Observable();
  19874. // Cache
  19875. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19876. _this._projectionMatrix = new BABYLON.Matrix();
  19877. _this._doNotComputeProjectionMatrix = false;
  19878. _this._postProcesses = new Array();
  19879. _this._transformMatrix = BABYLON.Matrix.Zero();
  19880. _this._activeMeshes = new BABYLON.SmartArray(256);
  19881. _this._globalPosition = BABYLON.Vector3.Zero();
  19882. _this._refreshFrustumPlanes = true;
  19883. _this.getScene().addCamera(_this);
  19884. if (!_this.getScene().activeCamera) {
  19885. _this.getScene().activeCamera = _this;
  19886. }
  19887. _this.position = position;
  19888. return _this;
  19889. }
  19890. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19891. get: function () {
  19892. return Camera._PERSPECTIVE_CAMERA;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19898. get: function () {
  19899. return Camera._ORTHOGRAPHIC_CAMERA;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19905. /**
  19906. * This is the default FOV mode for perspective cameras.
  19907. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19908. *
  19909. */
  19910. get: function () {
  19911. return Camera._FOVMODE_VERTICAL_FIXED;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19917. /**
  19918. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19919. *
  19920. */
  19921. get: function () {
  19922. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19928. get: function () {
  19929. return Camera._RIG_MODE_NONE;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19935. get: function () {
  19936. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19942. get: function () {
  19943. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19949. get: function () {
  19950. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19956. get: function () {
  19957. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19963. get: function () {
  19964. return Camera._RIG_MODE_VR;
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19970. get: function () {
  19971. return Camera._RIG_MODE_WEBVR;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. /**
  19977. * Store current camera state (fov, position, etc..)
  19978. */
  19979. Camera.prototype.storeState = function () {
  19980. this._stateStored = true;
  19981. this._storedFov = this.fov;
  19982. return this;
  19983. };
  19984. /**
  19985. * Restores the camera state values if it has been stored. You must call storeState() first
  19986. */
  19987. Camera.prototype._restoreStateValues = function () {
  19988. if (!this._stateStored) {
  19989. return false;
  19990. }
  19991. this.fov = this._storedFov;
  19992. return true;
  19993. };
  19994. /**
  19995. * Restored camera state. You must call storeState() first
  19996. */
  19997. Camera.prototype.restoreState = function () {
  19998. if (this._restoreStateValues()) {
  19999. this.onRestoreStateObservable.notifyObservers(this);
  20000. return true;
  20001. }
  20002. return false;
  20003. };
  20004. Camera.prototype.getClassName = function () {
  20005. return "Camera";
  20006. };
  20007. /**
  20008. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20009. */
  20010. Camera.prototype.toString = function (fullDetails) {
  20011. var ret = "Name: " + this.name;
  20012. ret += ", type: " + this.getClassName();
  20013. if (this.animations) {
  20014. for (var i = 0; i < this.animations.length; i++) {
  20015. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20016. }
  20017. }
  20018. if (fullDetails) {
  20019. }
  20020. return ret;
  20021. };
  20022. Object.defineProperty(Camera.prototype, "globalPosition", {
  20023. get: function () {
  20024. return this._globalPosition;
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Camera.prototype.getActiveMeshes = function () {
  20030. return this._activeMeshes;
  20031. };
  20032. Camera.prototype.isActiveMesh = function (mesh) {
  20033. return (this._activeMeshes.indexOf(mesh) !== -1);
  20034. };
  20035. //Cache
  20036. Camera.prototype._initCache = function () {
  20037. _super.prototype._initCache.call(this);
  20038. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20039. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20040. this._cache.mode = undefined;
  20041. this._cache.minZ = undefined;
  20042. this._cache.maxZ = undefined;
  20043. this._cache.fov = undefined;
  20044. this._cache.fovMode = undefined;
  20045. this._cache.aspectRatio = undefined;
  20046. this._cache.orthoLeft = undefined;
  20047. this._cache.orthoRight = undefined;
  20048. this._cache.orthoBottom = undefined;
  20049. this._cache.orthoTop = undefined;
  20050. this._cache.renderWidth = undefined;
  20051. this._cache.renderHeight = undefined;
  20052. };
  20053. Camera.prototype._updateCache = function (ignoreParentClass) {
  20054. if (!ignoreParentClass) {
  20055. _super.prototype._updateCache.call(this);
  20056. }
  20057. this._cache.position.copyFrom(this.position);
  20058. this._cache.upVector.copyFrom(this.upVector);
  20059. };
  20060. // Synchronized
  20061. Camera.prototype._isSynchronized = function () {
  20062. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20063. };
  20064. Camera.prototype._isSynchronizedViewMatrix = function () {
  20065. if (!_super.prototype._isSynchronized.call(this))
  20066. return false;
  20067. return this._cache.position.equals(this.position)
  20068. && this._cache.upVector.equals(this.upVector)
  20069. && this.isSynchronizedWithParent();
  20070. };
  20071. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20072. var check = this._cache.mode === this.mode
  20073. && this._cache.minZ === this.minZ
  20074. && this._cache.maxZ === this.maxZ;
  20075. if (!check) {
  20076. return false;
  20077. }
  20078. var engine = this.getEngine();
  20079. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20080. check = this._cache.fov === this.fov
  20081. && this._cache.fovMode === this.fovMode
  20082. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20083. }
  20084. else {
  20085. check = this._cache.orthoLeft === this.orthoLeft
  20086. && this._cache.orthoRight === this.orthoRight
  20087. && this._cache.orthoBottom === this.orthoBottom
  20088. && this._cache.orthoTop === this.orthoTop
  20089. && this._cache.renderWidth === engine.getRenderWidth()
  20090. && this._cache.renderHeight === engine.getRenderHeight();
  20091. }
  20092. return check;
  20093. };
  20094. // Controls
  20095. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20096. };
  20097. Camera.prototype.detachControl = function (element) {
  20098. };
  20099. Camera.prototype.update = function () {
  20100. this._checkInputs();
  20101. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20102. this._updateRigCameras();
  20103. }
  20104. };
  20105. Camera.prototype._checkInputs = function () {
  20106. this.onAfterCheckInputsObservable.notifyObservers(this);
  20107. };
  20108. Object.defineProperty(Camera.prototype, "rigCameras", {
  20109. get: function () {
  20110. return this._rigCameras;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20116. get: function () {
  20117. return this._rigPostProcess;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. /**
  20123. * Internal, gets the first post proces.
  20124. * @returns the first post process to be run on this camera.
  20125. */
  20126. Camera.prototype._getFirstPostProcess = function () {
  20127. for (var pp in this._postProcesses) {
  20128. if (this._postProcesses[pp] !== null) {
  20129. return this._postProcesses[pp];
  20130. }
  20131. }
  20132. return null;
  20133. };
  20134. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20135. // invalidate framebuffer
  20136. var firstPostProcess = this._getFirstPostProcess();
  20137. if (firstPostProcess) {
  20138. firstPostProcess.markTextureDirty();
  20139. }
  20140. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20141. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20142. var cam = this._rigCameras[i];
  20143. var rigPostProcess = cam._rigPostProcess;
  20144. // for VR rig, there does not have to be a post process
  20145. if (rigPostProcess) {
  20146. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20147. if (isPass) {
  20148. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20149. cam.isIntermediate = this._postProcesses.length === 0;
  20150. }
  20151. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20152. rigPostProcess.markTextureDirty();
  20153. }
  20154. else {
  20155. cam._postProcesses = this._postProcesses.slice(0);
  20156. }
  20157. }
  20158. };
  20159. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20160. if (insertAt === void 0) { insertAt = null; }
  20161. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20162. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20163. return 0;
  20164. }
  20165. if (insertAt == null || insertAt < 0) {
  20166. this._postProcesses.push(postProcess);
  20167. }
  20168. else if (this._postProcesses[insertAt] === null) {
  20169. this._postProcesses[insertAt] = postProcess;
  20170. }
  20171. else {
  20172. this._postProcesses.splice(insertAt, 0, postProcess);
  20173. }
  20174. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20175. return this._postProcesses.indexOf(postProcess);
  20176. };
  20177. Camera.prototype.detachPostProcess = function (postProcess) {
  20178. var idx = this._postProcesses.indexOf(postProcess);
  20179. if (idx !== -1) {
  20180. this._postProcesses[idx] = null;
  20181. }
  20182. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20183. };
  20184. Camera.prototype.getWorldMatrix = function () {
  20185. if (!this._worldMatrix) {
  20186. this._worldMatrix = BABYLON.Matrix.Identity();
  20187. }
  20188. var viewMatrix = this.getViewMatrix();
  20189. viewMatrix.invertToRef(this._worldMatrix);
  20190. return this._worldMatrix;
  20191. };
  20192. Camera.prototype._getViewMatrix = function () {
  20193. return BABYLON.Matrix.Identity();
  20194. };
  20195. Camera.prototype.getViewMatrix = function (force) {
  20196. if (!force && this._isSynchronizedViewMatrix()) {
  20197. return this._computedViewMatrix;
  20198. }
  20199. this.updateCache();
  20200. this._computedViewMatrix = this._getViewMatrix();
  20201. this._currentRenderId = this.getScene().getRenderId();
  20202. this._refreshFrustumPlanes = true;
  20203. if (!this.parent || !this.parent.getWorldMatrix) {
  20204. this._globalPosition.copyFrom(this.position);
  20205. }
  20206. else {
  20207. if (!this._worldMatrix) {
  20208. this._worldMatrix = BABYLON.Matrix.Identity();
  20209. }
  20210. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20211. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20212. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20213. this._computedViewMatrix.invert();
  20214. this._markSyncedWithParent();
  20215. }
  20216. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20217. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20218. }
  20219. this.onViewMatrixChangedObservable.notifyObservers(this);
  20220. return this._computedViewMatrix;
  20221. };
  20222. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20223. this._doNotComputeProjectionMatrix = true;
  20224. if (projection !== undefined) {
  20225. this._projectionMatrix = projection;
  20226. }
  20227. };
  20228. ;
  20229. Camera.prototype.unfreezeProjectionMatrix = function () {
  20230. this._doNotComputeProjectionMatrix = false;
  20231. };
  20232. ;
  20233. Camera.prototype.getProjectionMatrix = function (force) {
  20234. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20235. return this._projectionMatrix;
  20236. }
  20237. // Cache
  20238. this._cache.mode = this.mode;
  20239. this._cache.minZ = this.minZ;
  20240. this._cache.maxZ = this.maxZ;
  20241. // Matrix
  20242. this._refreshFrustumPlanes = true;
  20243. var engine = this.getEngine();
  20244. var scene = this.getScene();
  20245. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20246. this._cache.fov = this.fov;
  20247. this._cache.fovMode = this.fovMode;
  20248. this._cache.aspectRatio = engine.getAspectRatio(this);
  20249. if (this.minZ <= 0) {
  20250. this.minZ = 0.1;
  20251. }
  20252. if (scene.useRightHandedSystem) {
  20253. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20254. }
  20255. else {
  20256. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20257. }
  20258. }
  20259. else {
  20260. var halfWidth = engine.getRenderWidth() / 2.0;
  20261. var halfHeight = engine.getRenderHeight() / 2.0;
  20262. if (scene.useRightHandedSystem) {
  20263. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20264. }
  20265. else {
  20266. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20267. }
  20268. this._cache.orthoLeft = this.orthoLeft;
  20269. this._cache.orthoRight = this.orthoRight;
  20270. this._cache.orthoBottom = this.orthoBottom;
  20271. this._cache.orthoTop = this.orthoTop;
  20272. this._cache.renderWidth = engine.getRenderWidth();
  20273. this._cache.renderHeight = engine.getRenderHeight();
  20274. }
  20275. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20276. return this._projectionMatrix;
  20277. };
  20278. Camera.prototype.getTranformationMatrix = function () {
  20279. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20280. return this._transformMatrix;
  20281. };
  20282. Camera.prototype.updateFrustumPlanes = function () {
  20283. if (!this._refreshFrustumPlanes) {
  20284. return;
  20285. }
  20286. this.getTranformationMatrix();
  20287. if (!this._frustumPlanes) {
  20288. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20289. }
  20290. else {
  20291. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20292. }
  20293. this._refreshFrustumPlanes = false;
  20294. };
  20295. Camera.prototype.isInFrustum = function (target) {
  20296. this.updateFrustumPlanes();
  20297. return target.isInFrustum(this._frustumPlanes);
  20298. };
  20299. Camera.prototype.isCompletelyInFrustum = function (target) {
  20300. this.updateFrustumPlanes();
  20301. return target.isCompletelyInFrustum(this._frustumPlanes);
  20302. };
  20303. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20304. if (length === void 0) { length = 100; }
  20305. if (!transform) {
  20306. transform = this.getWorldMatrix();
  20307. }
  20308. if (!origin) {
  20309. origin = this.position;
  20310. }
  20311. var forward = new BABYLON.Vector3(0, 0, 1);
  20312. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20313. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20314. return new BABYLON.Ray(origin, direction, length);
  20315. };
  20316. /**
  20317. * Releases resources associated with this node.
  20318. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20319. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20320. */
  20321. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20322. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20323. // Observables
  20324. this.onViewMatrixChangedObservable.clear();
  20325. this.onProjectionMatrixChangedObservable.clear();
  20326. this.onAfterCheckInputsObservable.clear();
  20327. this.onRestoreStateObservable.clear();
  20328. // Inputs
  20329. if (this.inputs) {
  20330. this.inputs.clear();
  20331. }
  20332. // Animations
  20333. this.getScene().stopAnimation(this);
  20334. // Remove from scene
  20335. this.getScene().removeCamera(this);
  20336. while (this._rigCameras.length > 0) {
  20337. var camera = this._rigCameras.pop();
  20338. if (camera) {
  20339. camera.dispose();
  20340. }
  20341. }
  20342. // Postprocesses
  20343. if (this._rigPostProcess) {
  20344. this._rigPostProcess.dispose(this);
  20345. this._rigPostProcess = null;
  20346. this._postProcesses = [];
  20347. }
  20348. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20349. this._rigPostProcess = null;
  20350. this._postProcesses = [];
  20351. }
  20352. else {
  20353. var i = this._postProcesses.length;
  20354. while (--i >= 0) {
  20355. var postProcess = this._postProcesses[i];
  20356. if (postProcess) {
  20357. postProcess.dispose(this);
  20358. }
  20359. }
  20360. }
  20361. // Render targets
  20362. var i = this.customRenderTargets.length;
  20363. while (--i >= 0) {
  20364. this.customRenderTargets[i].dispose();
  20365. }
  20366. this.customRenderTargets = [];
  20367. // Active Meshes
  20368. this._activeMeshes.dispose();
  20369. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20370. };
  20371. Object.defineProperty(Camera.prototype, "leftCamera", {
  20372. // ---- Camera rigs section ----
  20373. get: function () {
  20374. if (this._rigCameras.length < 1) {
  20375. return null;
  20376. }
  20377. return this._rigCameras[0];
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. Object.defineProperty(Camera.prototype, "rightCamera", {
  20383. get: function () {
  20384. if (this._rigCameras.length < 2) {
  20385. return null;
  20386. }
  20387. return this._rigCameras[1];
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. Camera.prototype.getLeftTarget = function () {
  20393. if (this._rigCameras.length < 1) {
  20394. return null;
  20395. }
  20396. return this._rigCameras[0].getTarget();
  20397. };
  20398. Camera.prototype.getRightTarget = function () {
  20399. if (this._rigCameras.length < 2) {
  20400. return null;
  20401. }
  20402. return this._rigCameras[1].getTarget();
  20403. };
  20404. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20405. if (this.cameraRigMode === mode) {
  20406. return;
  20407. }
  20408. while (this._rigCameras.length > 0) {
  20409. var camera = this._rigCameras.pop();
  20410. if (camera) {
  20411. camera.dispose();
  20412. }
  20413. }
  20414. this.cameraRigMode = mode;
  20415. this._cameraRigParams = {};
  20416. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20417. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20418. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20419. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20420. // create the rig cameras, unless none
  20421. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20422. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20423. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20424. if (leftCamera && rightCamera) {
  20425. this._rigCameras.push(leftCamera);
  20426. this._rigCameras.push(rightCamera);
  20427. }
  20428. }
  20429. switch (this.cameraRigMode) {
  20430. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20431. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20432. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20433. break;
  20434. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20435. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20436. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20437. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20438. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20439. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20440. break;
  20441. case Camera.RIG_MODE_VR:
  20442. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20443. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20444. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20445. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20446. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20447. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20448. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20449. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20450. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20451. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20452. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20453. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20454. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20455. if (metrics.compensateDistortion) {
  20456. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20457. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20458. }
  20459. break;
  20460. case Camera.RIG_MODE_WEBVR:
  20461. if (rigParams.vrDisplay) {
  20462. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20463. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20464. //Left eye
  20465. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20466. this._rigCameras[0].setCameraRigParameter("left", true);
  20467. //leaving this for future reference
  20468. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20469. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20470. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20471. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20472. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20473. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20474. this._rigCameras[0].parent = this;
  20475. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20476. //Right eye
  20477. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20478. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20479. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20480. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20481. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20482. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20483. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20484. this._rigCameras[1].parent = this;
  20485. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20486. if (Camera.UseAlternateWebVRRendering) {
  20487. this._rigCameras[1]._skipRendering = true;
  20488. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20489. }
  20490. }
  20491. break;
  20492. }
  20493. this._cascadePostProcessesToRigCams();
  20494. this.update();
  20495. };
  20496. Camera.prototype._getVRProjectionMatrix = function () {
  20497. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20498. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20499. return this._projectionMatrix;
  20500. };
  20501. Camera.prototype._updateCameraRotationMatrix = function () {
  20502. //Here for WebVR
  20503. };
  20504. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20505. //Here for WebVR
  20506. };
  20507. /**
  20508. * This function MUST be overwritten by the different WebVR cameras available.
  20509. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20510. */
  20511. Camera.prototype._getWebVRProjectionMatrix = function () {
  20512. return BABYLON.Matrix.Identity();
  20513. };
  20514. /**
  20515. * This function MUST be overwritten by the different WebVR cameras available.
  20516. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20517. */
  20518. Camera.prototype._getWebVRViewMatrix = function () {
  20519. return BABYLON.Matrix.Identity();
  20520. };
  20521. Camera.prototype.setCameraRigParameter = function (name, value) {
  20522. if (!this._cameraRigParams) {
  20523. this._cameraRigParams = {};
  20524. }
  20525. this._cameraRigParams[name] = value;
  20526. //provisionnally:
  20527. if (name === "interaxialDistance") {
  20528. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20529. }
  20530. };
  20531. /**
  20532. * needs to be overridden by children so sub has required properties to be copied
  20533. */
  20534. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20535. return null;
  20536. };
  20537. /**
  20538. * May need to be overridden by children
  20539. */
  20540. Camera.prototype._updateRigCameras = function () {
  20541. for (var i = 0; i < this._rigCameras.length; i++) {
  20542. this._rigCameras[i].minZ = this.minZ;
  20543. this._rigCameras[i].maxZ = this.maxZ;
  20544. this._rigCameras[i].fov = this.fov;
  20545. }
  20546. // only update viewport when ANAGLYPH
  20547. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20548. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20549. }
  20550. };
  20551. Camera.prototype._setupInputs = function () {
  20552. };
  20553. Camera.prototype.serialize = function () {
  20554. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20555. // Type
  20556. serializationObject.type = this.getClassName();
  20557. // Parent
  20558. if (this.parent) {
  20559. serializationObject.parentId = this.parent.id;
  20560. }
  20561. if (this.inputs) {
  20562. this.inputs.serialize(serializationObject);
  20563. }
  20564. // Animations
  20565. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20566. serializationObject.ranges = this.serializeAnimationRanges();
  20567. return serializationObject;
  20568. };
  20569. Camera.prototype.clone = function (name) {
  20570. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20571. };
  20572. Camera.prototype.getDirection = function (localAxis) {
  20573. var result = BABYLON.Vector3.Zero();
  20574. this.getDirectionToRef(localAxis, result);
  20575. return result;
  20576. };
  20577. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20578. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20579. };
  20580. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20581. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20582. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20583. switch (type) {
  20584. case "ArcRotateCamera":
  20585. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20586. case "DeviceOrientationCamera":
  20587. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20588. case "FollowCamera":
  20589. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20590. case "ArcFollowCamera":
  20591. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20592. case "GamepadCamera":
  20593. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20594. case "TouchCamera":
  20595. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20596. case "VirtualJoysticksCamera":
  20597. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20598. case "WebVRFreeCamera":
  20599. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20600. case "WebVRGamepadCamera":
  20601. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20602. case "VRDeviceOrientationFreeCamera":
  20603. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20604. case "VRDeviceOrientationGamepadCamera":
  20605. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20606. case "AnaglyphArcRotateCamera":
  20607. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20608. case "AnaglyphFreeCamera":
  20609. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20610. case "AnaglyphGamepadCamera":
  20611. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20612. case "AnaglyphUniversalCamera":
  20613. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20614. case "StereoscopicArcRotateCamera":
  20615. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20616. case "StereoscopicFreeCamera":
  20617. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20618. case "StereoscopicGamepadCamera":
  20619. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20620. case "StereoscopicUniversalCamera":
  20621. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20622. case "FreeCamera":// Forcing Universal here
  20623. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20624. default:// Universal Camera is the default value
  20625. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20626. }
  20627. };
  20628. Camera.prototype.computeWorldMatrix = function () {
  20629. return this.getWorldMatrix();
  20630. };
  20631. Camera.Parse = function (parsedCamera, scene) {
  20632. var type = parsedCamera.type;
  20633. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20634. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20635. // Parent
  20636. if (parsedCamera.parentId) {
  20637. camera._waitingParentId = parsedCamera.parentId;
  20638. }
  20639. //If camera has an input manager, let it parse inputs settings
  20640. if (camera.inputs) {
  20641. camera.inputs.parse(parsedCamera);
  20642. camera._setupInputs();
  20643. }
  20644. if (camera.setPosition) {
  20645. camera.position.copyFromFloats(0, 0, 0);
  20646. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20647. }
  20648. // Target
  20649. if (parsedCamera.target) {
  20650. if (camera.setTarget) {
  20651. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20652. }
  20653. }
  20654. // Apply 3d rig, when found
  20655. if (parsedCamera.cameraRigMode) {
  20656. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20657. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20658. }
  20659. // Animations
  20660. if (parsedCamera.animations) {
  20661. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20662. var parsedAnimation = parsedCamera.animations[animationIndex];
  20663. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20664. }
  20665. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20666. }
  20667. if (parsedCamera.autoAnimate) {
  20668. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20669. }
  20670. return camera;
  20671. };
  20672. // Statics
  20673. Camera._PERSPECTIVE_CAMERA = 0;
  20674. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20675. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20676. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20677. Camera._RIG_MODE_NONE = 0;
  20678. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20679. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20680. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20681. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20682. Camera._RIG_MODE_VR = 20;
  20683. Camera._RIG_MODE_WEBVR = 21;
  20684. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20685. Camera.UseAlternateWebVRRendering = false;
  20686. __decorate([
  20687. BABYLON.serializeAsVector3()
  20688. ], Camera.prototype, "position", void 0);
  20689. __decorate([
  20690. BABYLON.serializeAsVector3()
  20691. ], Camera.prototype, "upVector", void 0);
  20692. __decorate([
  20693. BABYLON.serialize()
  20694. ], Camera.prototype, "orthoLeft", void 0);
  20695. __decorate([
  20696. BABYLON.serialize()
  20697. ], Camera.prototype, "orthoRight", void 0);
  20698. __decorate([
  20699. BABYLON.serialize()
  20700. ], Camera.prototype, "orthoBottom", void 0);
  20701. __decorate([
  20702. BABYLON.serialize()
  20703. ], Camera.prototype, "orthoTop", void 0);
  20704. __decorate([
  20705. BABYLON.serialize()
  20706. ], Camera.prototype, "fov", void 0);
  20707. __decorate([
  20708. BABYLON.serialize()
  20709. ], Camera.prototype, "minZ", void 0);
  20710. __decorate([
  20711. BABYLON.serialize()
  20712. ], Camera.prototype, "maxZ", void 0);
  20713. __decorate([
  20714. BABYLON.serialize()
  20715. ], Camera.prototype, "inertia", void 0);
  20716. __decorate([
  20717. BABYLON.serialize()
  20718. ], Camera.prototype, "mode", void 0);
  20719. __decorate([
  20720. BABYLON.serialize()
  20721. ], Camera.prototype, "layerMask", void 0);
  20722. __decorate([
  20723. BABYLON.serialize()
  20724. ], Camera.prototype, "fovMode", void 0);
  20725. __decorate([
  20726. BABYLON.serialize()
  20727. ], Camera.prototype, "cameraRigMode", void 0);
  20728. __decorate([
  20729. BABYLON.serialize()
  20730. ], Camera.prototype, "interaxialDistance", void 0);
  20731. __decorate([
  20732. BABYLON.serialize()
  20733. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20734. return Camera;
  20735. }(BABYLON.Node));
  20736. BABYLON.Camera = Camera;
  20737. })(BABYLON || (BABYLON = {}));
  20738. //# sourceMappingURL=babylon.camera.js.map
  20739. var BABYLON;
  20740. (function (BABYLON) {
  20741. var RenderingManager = /** @class */ (function () {
  20742. function RenderingManager(scene) {
  20743. this._renderingGroups = new Array();
  20744. this._autoClearDepthStencil = {};
  20745. this._customOpaqueSortCompareFn = {};
  20746. this._customAlphaTestSortCompareFn = {};
  20747. this._customTransparentSortCompareFn = {};
  20748. this._renderinGroupInfo = null;
  20749. this._scene = scene;
  20750. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20751. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20752. }
  20753. }
  20754. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20755. if (depth === void 0) { depth = true; }
  20756. if (stencil === void 0) { stencil = true; }
  20757. if (this._depthStencilBufferAlreadyCleaned) {
  20758. return;
  20759. }
  20760. this._scene.getEngine().clear(null, false, depth, stencil);
  20761. this._depthStencilBufferAlreadyCleaned = true;
  20762. };
  20763. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20764. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20765. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20766. var info = null;
  20767. if (observable) {
  20768. if (!this._renderinGroupInfo) {
  20769. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20770. }
  20771. info = this._renderinGroupInfo;
  20772. info.scene = this._scene;
  20773. info.camera = this._scene.activeCamera;
  20774. }
  20775. // Dispatch sprites
  20776. if (renderSprites) {
  20777. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20778. var manager = this._scene.spriteManagers[index];
  20779. this.dispatchSprites(manager);
  20780. }
  20781. }
  20782. // Render
  20783. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20784. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20785. var renderingGroup = this._renderingGroups[index];
  20786. if (!renderingGroup && !observable)
  20787. continue;
  20788. var renderingGroupMask = 0;
  20789. // Fire PRECLEAR stage
  20790. if (observable && info) {
  20791. renderingGroupMask = Math.pow(2, index);
  20792. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20793. info.renderingGroupId = index;
  20794. observable.notifyObservers(info, renderingGroupMask);
  20795. }
  20796. // Clear depth/stencil if needed
  20797. if (RenderingManager.AUTOCLEAR) {
  20798. var autoClear = this._autoClearDepthStencil[index];
  20799. if (autoClear && autoClear.autoClear) {
  20800. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20801. }
  20802. }
  20803. if (observable && info) {
  20804. // Fire PREOPAQUE stage
  20805. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20806. observable.notifyObservers(info, renderingGroupMask);
  20807. // Fire PRETRANSPARENT stage
  20808. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20809. observable.notifyObservers(info, renderingGroupMask);
  20810. }
  20811. if (renderingGroup)
  20812. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20813. // Fire POSTTRANSPARENT stage
  20814. if (observable && info) {
  20815. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20816. observable.notifyObservers(info, renderingGroupMask);
  20817. }
  20818. }
  20819. };
  20820. RenderingManager.prototype.reset = function () {
  20821. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20822. var renderingGroup = this._renderingGroups[index];
  20823. if (renderingGroup) {
  20824. renderingGroup.prepare();
  20825. }
  20826. }
  20827. };
  20828. RenderingManager.prototype.dispose = function () {
  20829. this.freeRenderingGroups();
  20830. this._renderingGroups.length = 0;
  20831. };
  20832. /**
  20833. * Clear the info related to rendering groups preventing retention points during dispose.
  20834. */
  20835. RenderingManager.prototype.freeRenderingGroups = function () {
  20836. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20837. var renderingGroup = this._renderingGroups[index];
  20838. if (renderingGroup) {
  20839. renderingGroup.dispose();
  20840. }
  20841. }
  20842. };
  20843. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20844. if (this._renderingGroups[renderingGroupId] === undefined) {
  20845. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20846. }
  20847. };
  20848. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20849. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20850. this._prepareRenderingGroup(renderingGroupId);
  20851. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20852. };
  20853. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20854. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20855. this._prepareRenderingGroup(renderingGroupId);
  20856. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20857. };
  20858. /**
  20859. * @param subMesh The submesh to dispatch
  20860. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20861. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20862. */
  20863. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20864. if (mesh === undefined) {
  20865. mesh = subMesh.getMesh();
  20866. }
  20867. var renderingGroupId = mesh.renderingGroupId || 0;
  20868. this._prepareRenderingGroup(renderingGroupId);
  20869. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20870. };
  20871. /**
  20872. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20873. * This allowed control for front to back rendering or reversly depending of the special needs.
  20874. *
  20875. * @param renderingGroupId The rendering group id corresponding to its index
  20876. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20877. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20878. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20879. */
  20880. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20881. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20882. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20883. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20884. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20885. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20886. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20887. if (this._renderingGroups[renderingGroupId]) {
  20888. var group = this._renderingGroups[renderingGroupId];
  20889. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20890. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20891. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20892. }
  20893. };
  20894. /**
  20895. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20896. *
  20897. * @param renderingGroupId The rendering group id corresponding to its index
  20898. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20899. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20900. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20901. */
  20902. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20903. if (depth === void 0) { depth = true; }
  20904. if (stencil === void 0) { stencil = true; }
  20905. this._autoClearDepthStencil[renderingGroupId] = {
  20906. autoClear: autoClearDepthStencil,
  20907. depth: depth,
  20908. stencil: stencil
  20909. };
  20910. };
  20911. /**
  20912. * The max id used for rendering groups (not included)
  20913. */
  20914. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20915. /**
  20916. * The min id used for rendering groups (included)
  20917. */
  20918. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20919. /**
  20920. * Used to globally prevent autoclearing scenes.
  20921. */
  20922. RenderingManager.AUTOCLEAR = true;
  20923. return RenderingManager;
  20924. }());
  20925. BABYLON.RenderingManager = RenderingManager;
  20926. })(BABYLON || (BABYLON = {}));
  20927. //# sourceMappingURL=babylon.renderingManager.js.map
  20928. var BABYLON;
  20929. (function (BABYLON) {
  20930. var RenderingGroup = /** @class */ (function () {
  20931. /**
  20932. * Creates a new rendering group.
  20933. * @param index The rendering group index
  20934. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20935. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20936. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20937. */
  20938. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20939. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20940. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20941. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20942. this.index = index;
  20943. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20944. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20945. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20946. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20947. this._particleSystems = new BABYLON.SmartArray(256);
  20948. this._spriteManagers = new BABYLON.SmartArray(256);
  20949. this._edgesRenderers = new BABYLON.SmartArray(16);
  20950. this._scene = scene;
  20951. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20952. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20953. this.transparentSortCompareFn = transparentSortCompareFn;
  20954. }
  20955. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20956. /**
  20957. * Set the opaque sort comparison function.
  20958. * If null the sub meshes will be render in the order they were created
  20959. */
  20960. set: function (value) {
  20961. this._opaqueSortCompareFn = value;
  20962. if (value) {
  20963. this._renderOpaque = this.renderOpaqueSorted;
  20964. }
  20965. else {
  20966. this._renderOpaque = RenderingGroup.renderUnsorted;
  20967. }
  20968. },
  20969. enumerable: true,
  20970. configurable: true
  20971. });
  20972. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20973. /**
  20974. * Set the alpha test sort comparison function.
  20975. * If null the sub meshes will be render in the order they were created
  20976. */
  20977. set: function (value) {
  20978. this._alphaTestSortCompareFn = value;
  20979. if (value) {
  20980. this._renderAlphaTest = this.renderAlphaTestSorted;
  20981. }
  20982. else {
  20983. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20984. }
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20990. /**
  20991. * Set the transparent sort comparison function.
  20992. * If null the sub meshes will be render in the order they were created
  20993. */
  20994. set: function (value) {
  20995. if (value) {
  20996. this._transparentSortCompareFn = value;
  20997. }
  20998. else {
  20999. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21000. }
  21001. this._renderTransparent = this.renderTransparentSorted;
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. /**
  21007. * Render all the sub meshes contained in the group.
  21008. * @param customRenderFunction Used to override the default render behaviour of the group.
  21009. * @returns true if rendered some submeshes.
  21010. */
  21011. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21012. if (customRenderFunction) {
  21013. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21014. return;
  21015. }
  21016. var engine = this._scene.getEngine();
  21017. // Depth only
  21018. if (this._depthOnlySubMeshes.length !== 0) {
  21019. engine.setColorWrite(false);
  21020. this._renderAlphaTest(this._depthOnlySubMeshes);
  21021. engine.setColorWrite(true);
  21022. }
  21023. // Opaque
  21024. if (this._opaqueSubMeshes.length !== 0) {
  21025. this._renderOpaque(this._opaqueSubMeshes);
  21026. }
  21027. // Alpha test
  21028. if (this._alphaTestSubMeshes.length !== 0) {
  21029. this._renderAlphaTest(this._alphaTestSubMeshes);
  21030. }
  21031. var stencilState = engine.getStencilBuffer();
  21032. engine.setStencilBuffer(false);
  21033. // Sprites
  21034. if (renderSprites) {
  21035. this._renderSprites();
  21036. }
  21037. // Particles
  21038. if (renderParticles) {
  21039. this._renderParticles(activeMeshes);
  21040. }
  21041. if (this.onBeforeTransparentRendering) {
  21042. this.onBeforeTransparentRendering();
  21043. }
  21044. // Transparent
  21045. if (this._transparentSubMeshes.length !== 0) {
  21046. this._renderTransparent(this._transparentSubMeshes);
  21047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21048. }
  21049. // Set back stencil to false in case it changes before the edge renderer.
  21050. engine.setStencilBuffer(false);
  21051. // Edges
  21052. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21053. this._edgesRenderers.data[edgesRendererIndex].render();
  21054. }
  21055. // Restore Stencil state.
  21056. engine.setStencilBuffer(stencilState);
  21057. };
  21058. /**
  21059. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21060. * @param subMeshes The submeshes to render
  21061. */
  21062. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21063. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21064. };
  21065. /**
  21066. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21067. * @param subMeshes The submeshes to render
  21068. */
  21069. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21070. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21071. };
  21072. /**
  21073. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21074. * @param subMeshes The submeshes to render
  21075. */
  21076. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21077. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21078. };
  21079. /**
  21080. * Renders the submeshes in a specified order.
  21081. * @param subMeshes The submeshes to sort before render
  21082. * @param sortCompareFn The comparison function use to sort
  21083. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21084. * @param transparent Specifies to activate blending if true
  21085. */
  21086. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21087. var subIndex = 0;
  21088. var subMesh;
  21089. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21090. for (; subIndex < subMeshes.length; subIndex++) {
  21091. subMesh = subMeshes.data[subIndex];
  21092. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21093. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21094. }
  21095. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21096. if (sortCompareFn) {
  21097. sortedArray.sort(sortCompareFn);
  21098. }
  21099. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21100. subMesh = sortedArray[subIndex];
  21101. if (transparent) {
  21102. var material = subMesh.getMaterial();
  21103. if (material && material.needDepthPrePass) {
  21104. var engine = material.getScene().getEngine();
  21105. engine.setColorWrite(false);
  21106. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21107. subMesh.render(false);
  21108. engine.setColorWrite(true);
  21109. }
  21110. }
  21111. subMesh.render(transparent);
  21112. }
  21113. };
  21114. /**
  21115. * Renders the submeshes in the order they were dispatched (no sort applied).
  21116. * @param subMeshes The submeshes to render
  21117. */
  21118. RenderingGroup.renderUnsorted = function (subMeshes) {
  21119. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21120. var submesh = subMeshes.data[subIndex];
  21121. submesh.render(false);
  21122. }
  21123. };
  21124. /**
  21125. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21126. * are rendered back to front if in the same alpha index.
  21127. *
  21128. * @param a The first submesh
  21129. * @param b The second submesh
  21130. * @returns The result of the comparison
  21131. */
  21132. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21133. // Alpha index first
  21134. if (a._alphaIndex > b._alphaIndex) {
  21135. return 1;
  21136. }
  21137. if (a._alphaIndex < b._alphaIndex) {
  21138. return -1;
  21139. }
  21140. // Then distance to camera
  21141. return RenderingGroup.backToFrontSortCompare(a, b);
  21142. };
  21143. /**
  21144. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21145. * are rendered back to front.
  21146. *
  21147. * @param a The first submesh
  21148. * @param b The second submesh
  21149. * @returns The result of the comparison
  21150. */
  21151. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21152. // Then distance to camera
  21153. if (a._distanceToCamera < b._distanceToCamera) {
  21154. return 1;
  21155. }
  21156. if (a._distanceToCamera > b._distanceToCamera) {
  21157. return -1;
  21158. }
  21159. return 0;
  21160. };
  21161. /**
  21162. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21163. * are rendered front to back (prevent overdraw).
  21164. *
  21165. * @param a The first submesh
  21166. * @param b The second submesh
  21167. * @returns The result of the comparison
  21168. */
  21169. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21170. // Then distance to camera
  21171. if (a._distanceToCamera < b._distanceToCamera) {
  21172. return -1;
  21173. }
  21174. if (a._distanceToCamera > b._distanceToCamera) {
  21175. return 1;
  21176. }
  21177. return 0;
  21178. };
  21179. /**
  21180. * Resets the different lists of submeshes to prepare a new frame.
  21181. */
  21182. RenderingGroup.prototype.prepare = function () {
  21183. this._opaqueSubMeshes.reset();
  21184. this._transparentSubMeshes.reset();
  21185. this._alphaTestSubMeshes.reset();
  21186. this._depthOnlySubMeshes.reset();
  21187. this._particleSystems.reset();
  21188. this._spriteManagers.reset();
  21189. this._edgesRenderers.reset();
  21190. };
  21191. RenderingGroup.prototype.dispose = function () {
  21192. this._opaqueSubMeshes.dispose();
  21193. this._transparentSubMeshes.dispose();
  21194. this._alphaTestSubMeshes.dispose();
  21195. this._depthOnlySubMeshes.dispose();
  21196. this._particleSystems.dispose();
  21197. this._spriteManagers.dispose();
  21198. this._edgesRenderers.dispose();
  21199. };
  21200. /**
  21201. * Inserts the submesh in its correct queue depending on its material.
  21202. * @param subMesh The submesh to dispatch
  21203. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21204. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21205. */
  21206. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21207. // Get mesh and materials if not provided
  21208. if (mesh === undefined) {
  21209. mesh = subMesh.getMesh();
  21210. }
  21211. if (material === undefined) {
  21212. material = subMesh.getMaterial();
  21213. }
  21214. if (material === null || material === undefined) {
  21215. return;
  21216. }
  21217. if (material.needAlphaBlendingForMesh(mesh)) {
  21218. this._transparentSubMeshes.push(subMesh);
  21219. }
  21220. else if (material.needAlphaTesting()) {
  21221. if (material.needDepthPrePass) {
  21222. this._depthOnlySubMeshes.push(subMesh);
  21223. }
  21224. this._alphaTestSubMeshes.push(subMesh);
  21225. }
  21226. else {
  21227. if (material.needDepthPrePass) {
  21228. this._depthOnlySubMeshes.push(subMesh);
  21229. }
  21230. this._opaqueSubMeshes.push(subMesh); // Opaque
  21231. }
  21232. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21233. this._edgesRenderers.push(mesh._edgesRenderer);
  21234. }
  21235. };
  21236. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21237. this._spriteManagers.push(spriteManager);
  21238. };
  21239. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21240. this._particleSystems.push(particleSystem);
  21241. };
  21242. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21243. if (this._particleSystems.length === 0) {
  21244. return;
  21245. }
  21246. // Particles
  21247. var activeCamera = this._scene.activeCamera;
  21248. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21249. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21250. var particleSystem = this._particleSystems.data[particleIndex];
  21251. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21252. continue;
  21253. }
  21254. var emitter = particleSystem.emitter;
  21255. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21256. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21257. }
  21258. }
  21259. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21260. };
  21261. RenderingGroup.prototype._renderSprites = function () {
  21262. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21263. return;
  21264. }
  21265. // Sprites
  21266. var activeCamera = this._scene.activeCamera;
  21267. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21268. for (var id = 0; id < this._spriteManagers.length; id++) {
  21269. var spriteManager = this._spriteManagers.data[id];
  21270. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21271. spriteManager.render();
  21272. }
  21273. }
  21274. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21275. };
  21276. return RenderingGroup;
  21277. }());
  21278. BABYLON.RenderingGroup = RenderingGroup;
  21279. })(BABYLON || (BABYLON = {}));
  21280. //# sourceMappingURL=babylon.renderingGroup.js.map
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. var ClickInfo = /** @class */ (function () {
  21284. function ClickInfo() {
  21285. this._singleClick = false;
  21286. this._doubleClick = false;
  21287. this._hasSwiped = false;
  21288. this._ignore = false;
  21289. }
  21290. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21291. get: function () {
  21292. return this._singleClick;
  21293. },
  21294. set: function (b) {
  21295. this._singleClick = b;
  21296. },
  21297. enumerable: true,
  21298. configurable: true
  21299. });
  21300. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21301. get: function () {
  21302. return this._doubleClick;
  21303. },
  21304. set: function (b) {
  21305. this._doubleClick = b;
  21306. },
  21307. enumerable: true,
  21308. configurable: true
  21309. });
  21310. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21311. get: function () {
  21312. return this._hasSwiped;
  21313. },
  21314. set: function (b) {
  21315. this._hasSwiped = b;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21321. get: function () {
  21322. return this._ignore;
  21323. },
  21324. set: function (b) {
  21325. this._ignore = b;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. return ClickInfo;
  21331. }());
  21332. /**
  21333. * This class is used by the onRenderingGroupObservable
  21334. */
  21335. var RenderingGroupInfo = /** @class */ (function () {
  21336. function RenderingGroupInfo() {
  21337. }
  21338. /**
  21339. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21340. * This stage will be fired no matter what
  21341. */
  21342. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21343. /**
  21344. * Called before opaque object are rendered.
  21345. * This stage will be fired only if there's 3D Opaque content to render
  21346. */
  21347. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21348. /**
  21349. * Called after the opaque objects are rendered and before the transparent ones
  21350. * This stage will be fired only if there's 3D transparent content to render
  21351. */
  21352. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21353. /**
  21354. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21355. * This stage will be fired no matter what
  21356. */
  21357. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21358. return RenderingGroupInfo;
  21359. }());
  21360. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21361. /**
  21362. * Represents a scene to be rendered by the engine.
  21363. * @see http://doc.babylonjs.com/page.php?p=21911
  21364. */
  21365. var Scene = /** @class */ (function () {
  21366. /**
  21367. * @constructor
  21368. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21369. */
  21370. function Scene(engine) {
  21371. // Members
  21372. this.autoClear = true;
  21373. this.autoClearDepthAndStencil = true;
  21374. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21375. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21376. this.forceWireframe = false;
  21377. this._forcePointsCloud = false;
  21378. this.forceShowBoundingBoxes = false;
  21379. this.animationsEnabled = true;
  21380. this.useConstantAnimationDeltaTime = false;
  21381. this.constantlyUpdateMeshUnderPointer = false;
  21382. this.hoverCursor = "pointer";
  21383. this.defaultCursor = "";
  21384. /**
  21385. * This is used to call preventDefault() on pointer down
  21386. * in order to block unwanted artifacts like system double clicks
  21387. */
  21388. this.preventDefaultOnPointerDown = true;
  21389. // Metadata
  21390. this.metadata = null;
  21391. /**
  21392. * An event triggered when the scene is disposed.
  21393. * @type {BABYLON.Observable}
  21394. */
  21395. this.onDisposeObservable = new BABYLON.Observable();
  21396. /**
  21397. * An event triggered before rendering the scene (right after animations and physics)
  21398. * @type {BABYLON.Observable}
  21399. */
  21400. this.onBeforeRenderObservable = new BABYLON.Observable();
  21401. /**
  21402. * An event triggered after rendering the scene
  21403. * @type {BABYLON.Observable}
  21404. */
  21405. this.onAfterRenderObservable = new BABYLON.Observable();
  21406. /**
  21407. * An event triggered before animating the scene
  21408. * @type {BABYLON.Observable}
  21409. */
  21410. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21411. /**
  21412. * An event triggered after animations processing
  21413. * @type {BABYLON.Observable}
  21414. */
  21415. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21416. /**
  21417. * An event triggered before draw calls are ready to be sent
  21418. * @type {BABYLON.Observable}
  21419. */
  21420. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21421. /**
  21422. * An event triggered after draw calls have been sent
  21423. * @type {BABYLON.Observable}
  21424. */
  21425. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21426. /**
  21427. * An event triggered when physic simulation is about to be run
  21428. * @type {BABYLON.Observable}
  21429. */
  21430. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21431. /**
  21432. * An event triggered when physic simulation has been done
  21433. * @type {BABYLON.Observable}
  21434. */
  21435. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21436. /**
  21437. * An event triggered when the scene is ready
  21438. * @type {BABYLON.Observable}
  21439. */
  21440. this.onReadyObservable = new BABYLON.Observable();
  21441. /**
  21442. * An event triggered before rendering a camera
  21443. * @type {BABYLON.Observable}
  21444. */
  21445. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21446. /**
  21447. * An event triggered after rendering a camera
  21448. * @type {BABYLON.Observable}
  21449. */
  21450. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21451. /**
  21452. * An event triggered when active meshes evaluation is about to start
  21453. * @type {BABYLON.Observable}
  21454. */
  21455. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21456. /**
  21457. * An event triggered when active meshes evaluation is done
  21458. * @type {BABYLON.Observable}
  21459. */
  21460. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21461. /**
  21462. * An event triggered when particles rendering is about to start
  21463. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21464. * @type {BABYLON.Observable}
  21465. */
  21466. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21467. /**
  21468. * An event triggered when particles rendering is done
  21469. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21470. * @type {BABYLON.Observable}
  21471. */
  21472. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21473. /**
  21474. * An event triggered when sprites rendering is about to start
  21475. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21476. * @type {BABYLON.Observable}
  21477. */
  21478. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21479. /**
  21480. * An event triggered when sprites rendering is done
  21481. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21482. * @type {BABYLON.Observable}
  21483. */
  21484. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21485. /**
  21486. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21487. * @type {BABYLON.Observable}
  21488. */
  21489. this.onDataLoadedObservable = new BABYLON.Observable();
  21490. /**
  21491. * An event triggered when a camera is created
  21492. * @type {BABYLON.Observable}
  21493. */
  21494. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21495. /**
  21496. * An event triggered when a camera is removed
  21497. * @type {BABYLON.Observable}
  21498. */
  21499. this.onCameraRemovedObservable = new BABYLON.Observable();
  21500. /**
  21501. * An event triggered when a light is created
  21502. * @type {BABYLON.Observable}
  21503. */
  21504. this.onNewLightAddedObservable = new BABYLON.Observable();
  21505. /**
  21506. * An event triggered when a light is removed
  21507. * @type {BABYLON.Observable}
  21508. */
  21509. this.onLightRemovedObservable = new BABYLON.Observable();
  21510. /**
  21511. * An event triggered when a geometry is created
  21512. * @type {BABYLON.Observable}
  21513. */
  21514. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21515. /**
  21516. * An event triggered when a geometry is removed
  21517. * @type {BABYLON.Observable}
  21518. */
  21519. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21520. /**
  21521. * An event triggered when a transform node is created
  21522. * @type {BABYLON.Observable}
  21523. */
  21524. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21525. /**
  21526. * An event triggered when a transform node is removed
  21527. * @type {BABYLON.Observable}
  21528. */
  21529. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21530. /**
  21531. * An event triggered when a mesh is created
  21532. * @type {BABYLON.Observable}
  21533. */
  21534. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21535. /**
  21536. * An event triggered when a mesh is removed
  21537. * @type {BABYLON.Observable}
  21538. */
  21539. this.onMeshRemovedObservable = new BABYLON.Observable();
  21540. /**
  21541. * An event triggered when render targets are about to be rendered
  21542. * Can happen multiple times per frame.
  21543. * @type {BABYLON.Observable}
  21544. */
  21545. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21546. /**
  21547. * An event triggered when render targets were rendered.
  21548. * Can happen multiple times per frame.
  21549. * @type {BABYLON.Observable}
  21550. */
  21551. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21552. /**
  21553. * An event triggered before calculating deterministic simulation step
  21554. * @type {BABYLON.Observable}
  21555. */
  21556. this.onBeforeStepObservable = new BABYLON.Observable();
  21557. /**
  21558. * An event triggered after calculating deterministic simulation step
  21559. * @type {BABYLON.Observable}
  21560. */
  21561. this.onAfterStepObservable = new BABYLON.Observable();
  21562. /**
  21563. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21564. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21565. * 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)
  21566. */
  21567. this.onRenderingGroupObservable = new BABYLON.Observable();
  21568. // Animations
  21569. this.animations = [];
  21570. /**
  21571. * 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).
  21572. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21573. */
  21574. this.onPrePointerObservable = new BABYLON.Observable();
  21575. /**
  21576. * Observable event triggered each time an input event is received from the rendering canvas
  21577. */
  21578. this.onPointerObservable = new BABYLON.Observable();
  21579. this._meshPickProceed = false;
  21580. this._currentPickResult = null;
  21581. this._previousPickResult = null;
  21582. this._totalPointersPressed = 0;
  21583. this._doubleClickOccured = false;
  21584. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21585. this.cameraToUseForPointers = null;
  21586. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21587. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21588. this._startingPointerTime = 0;
  21589. this._previousStartingPointerTime = 0;
  21590. // Deterministic lockstep
  21591. this._timeAccumulator = 0;
  21592. this._currentStepId = 0;
  21593. this._currentInternalStep = 0;
  21594. // Keyboard
  21595. /**
  21596. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21597. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21598. */
  21599. this.onPreKeyboardObservable = new BABYLON.Observable();
  21600. /**
  21601. * Observable event triggered each time an keyboard event is received from the hosting window
  21602. */
  21603. this.onKeyboardObservable = new BABYLON.Observable();
  21604. // Coordinate system
  21605. /**
  21606. * use right-handed coordinate system on this scene.
  21607. * @type {boolean}
  21608. */
  21609. this._useRightHandedSystem = false;
  21610. // Fog
  21611. this._fogEnabled = true;
  21612. this._fogMode = Scene.FOGMODE_NONE;
  21613. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21614. this.fogDensity = 0.1;
  21615. this.fogStart = 0;
  21616. this.fogEnd = 1000.0;
  21617. // Lights
  21618. /**
  21619. * is shadow enabled on this scene.
  21620. * @type {boolean}
  21621. */
  21622. this._shadowsEnabled = true;
  21623. /**
  21624. * is light enabled on this scene.
  21625. * @type {boolean}
  21626. */
  21627. this._lightsEnabled = true;
  21628. /**
  21629. * All of the lights added to this scene.
  21630. * @see BABYLON.Light
  21631. * @type {BABYLON.Light[]}
  21632. */
  21633. this.lights = new Array();
  21634. // Cameras
  21635. /** All of the cameras added to this scene. */
  21636. this.cameras = new Array();
  21637. /** All of the active cameras added to this scene. */
  21638. this.activeCameras = new Array();
  21639. // Meshes
  21640. /**
  21641. * All of the tranform nodes added to this scene.
  21642. * @see BABYLON.TransformNode
  21643. * @type {BABYLON.TransformNode[]}
  21644. */
  21645. this.transformNodes = new Array();
  21646. /**
  21647. * All of the (abstract) meshes added to this scene.
  21648. * @see BABYLON.AbstractMesh
  21649. * @type {BABYLON.AbstractMesh[]}
  21650. */
  21651. this.meshes = new Array();
  21652. /**
  21653. * All of the animation groups added to this scene.
  21654. * @see BABYLON.AnimationGroup
  21655. * @type {BABYLON.AnimationGroup[]}
  21656. */
  21657. this.animationGroups = new Array();
  21658. // Geometries
  21659. this._geometries = new Array();
  21660. this.materials = new Array();
  21661. this.multiMaterials = new Array();
  21662. // Textures
  21663. this._texturesEnabled = true;
  21664. this.textures = new Array();
  21665. // Particles
  21666. this.particlesEnabled = true;
  21667. this.particleSystems = new Array();
  21668. // Sprites
  21669. this.spritesEnabled = true;
  21670. this.spriteManagers = new Array();
  21671. /**
  21672. * The list of layers (background and foreground) of the scene.
  21673. */
  21674. this.layers = new Array();
  21675. /**
  21676. * The list of effect layers (highlights/glow) contained in the scene.
  21677. */
  21678. this.effectLayers = new Array();
  21679. // Skeletons
  21680. this._skeletonsEnabled = true;
  21681. this.skeletons = new Array();
  21682. // Morph targets
  21683. this.morphTargetManagers = new Array();
  21684. // Lens flares
  21685. this.lensFlaresEnabled = true;
  21686. this.lensFlareSystems = new Array();
  21687. // Collisions
  21688. this.collisionsEnabled = true;
  21689. /** Defines the gravity applied to this scene */
  21690. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21691. // Postprocesses
  21692. this.postProcesses = new Array();
  21693. this.postProcessesEnabled = true;
  21694. // Customs render targets
  21695. this.renderTargetsEnabled = true;
  21696. this.dumpNextRenderTargets = false;
  21697. this.customRenderTargets = new Array();
  21698. // Imported meshes
  21699. this.importedMeshesFiles = new Array();
  21700. // Probes
  21701. this.probesEnabled = true;
  21702. this.reflectionProbes = new Array();
  21703. this._actionManagers = new Array();
  21704. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21705. // Procedural textures
  21706. this.proceduralTexturesEnabled = true;
  21707. this._proceduralTextures = new Array();
  21708. this.soundTracks = new Array();
  21709. this._audioEnabled = true;
  21710. this._headphone = false;
  21711. // Performance counters
  21712. this._totalVertices = new BABYLON.PerfCounter();
  21713. this._activeIndices = new BABYLON.PerfCounter();
  21714. this._activeParticles = new BABYLON.PerfCounter();
  21715. this._activeBones = new BABYLON.PerfCounter();
  21716. this._animationTime = 0;
  21717. this.animationTimeScale = 1;
  21718. this._renderId = 0;
  21719. this._executeWhenReadyTimeoutId = -1;
  21720. this._intermediateRendering = false;
  21721. this._viewUpdateFlag = -1;
  21722. this._projectionUpdateFlag = -1;
  21723. this._alternateViewUpdateFlag = -1;
  21724. this._alternateProjectionUpdateFlag = -1;
  21725. this._toBeDisposed = new BABYLON.SmartArray(256);
  21726. this._activeRequests = new Array();
  21727. this._pendingData = new Array();
  21728. this._isDisposed = false;
  21729. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21730. this._activeMeshes = new BABYLON.SmartArray(256);
  21731. this._processedMaterials = new BABYLON.SmartArray(256);
  21732. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21733. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21734. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21735. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21736. this._activeAnimatables = new Array();
  21737. this._transformMatrix = BABYLON.Matrix.Zero();
  21738. this._useAlternateCameraConfiguration = false;
  21739. this._alternateRendering = false;
  21740. this.requireLightSorting = false;
  21741. this._depthRenderer = {};
  21742. this._activeMeshesFrozen = false;
  21743. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21744. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21745. this._engine.scenes.push(this);
  21746. this._uid = null;
  21747. this._renderingManager = new BABYLON.RenderingManager(this);
  21748. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21749. if (BABYLON.OutlineRenderer) {
  21750. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21751. }
  21752. if (BABYLON.Tools.IsWindowObjectExist()) {
  21753. this.attachControl();
  21754. }
  21755. //simplification queue
  21756. if (BABYLON.SimplificationQueue) {
  21757. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21758. }
  21759. //collision coordinator initialization. For now legacy per default.
  21760. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21761. // Uniform Buffer
  21762. this._createUbo();
  21763. // Default Image processing definition.
  21764. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21765. }
  21766. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21767. /** The fog is deactivated */
  21768. get: function () {
  21769. return Scene._FOGMODE_NONE;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21775. /** The fog density is following an exponential function */
  21776. get: function () {
  21777. return Scene._FOGMODE_EXP;
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21783. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21784. get: function () {
  21785. return Scene._FOGMODE_EXP2;
  21786. },
  21787. enumerable: true,
  21788. configurable: true
  21789. });
  21790. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21791. /** The fog density is following a linear function. */
  21792. get: function () {
  21793. return Scene._FOGMODE_LINEAR;
  21794. },
  21795. enumerable: true,
  21796. configurable: true
  21797. });
  21798. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21799. /**
  21800. * Texture used in all pbr material as the reflection texture.
  21801. * As in the majority of the scene they are the same (exception for multi room and so on),
  21802. * this is easier to reference from here than from all the materials.
  21803. */
  21804. get: function () {
  21805. return this._environmentTexture;
  21806. },
  21807. /**
  21808. * Texture used in all pbr material as the reflection texture.
  21809. * As in the majority of the scene they are the same (exception for multi room and so on),
  21810. * this is easier to set here than in all the materials.
  21811. */
  21812. set: function (value) {
  21813. if (this._environmentTexture === value) {
  21814. return;
  21815. }
  21816. this._environmentTexture = value;
  21817. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21818. },
  21819. enumerable: true,
  21820. configurable: true
  21821. });
  21822. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21823. /**
  21824. * Default image processing configuration used either in the rendering
  21825. * Forward main pass or through the imageProcessingPostProcess if present.
  21826. * As in the majority of the scene they are the same (exception for multi camera),
  21827. * this is easier to reference from here than from all the materials and post process.
  21828. *
  21829. * No setter as we it is a shared configuration, you can set the values instead.
  21830. */
  21831. get: function () {
  21832. return this._imageProcessingConfiguration;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21838. get: function () {
  21839. return this._forcePointsCloud;
  21840. },
  21841. set: function (value) {
  21842. if (this._forcePointsCloud === value) {
  21843. return;
  21844. }
  21845. this._forcePointsCloud = value;
  21846. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(Scene.prototype, "onDispose", {
  21852. /** A function to be executed when this scene is disposed. */
  21853. set: function (callback) {
  21854. if (this._onDisposeObserver) {
  21855. this.onDisposeObservable.remove(this._onDisposeObserver);
  21856. }
  21857. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. Object.defineProperty(Scene.prototype, "beforeRender", {
  21863. /** A function to be executed before rendering this scene */
  21864. set: function (callback) {
  21865. if (this._onBeforeRenderObserver) {
  21866. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21867. }
  21868. if (callback) {
  21869. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21870. }
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Scene.prototype, "afterRender", {
  21876. /** A function to be executed after rendering this scene */
  21877. set: function (callback) {
  21878. if (this._onAfterRenderObserver) {
  21879. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21880. }
  21881. if (callback) {
  21882. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21883. }
  21884. },
  21885. enumerable: true,
  21886. configurable: true
  21887. });
  21888. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21889. set: function (callback) {
  21890. if (this._onBeforeCameraRenderObserver) {
  21891. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21892. }
  21893. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21899. set: function (callback) {
  21900. if (this._onAfterCameraRenderObserver) {
  21901. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21902. }
  21903. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21909. get: function () {
  21910. if (!this._gamepadManager) {
  21911. this._gamepadManager = new BABYLON.GamepadManager(this);
  21912. }
  21913. return this._gamepadManager;
  21914. },
  21915. enumerable: true,
  21916. configurable: true
  21917. });
  21918. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21919. get: function () {
  21920. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21926. get: function () {
  21927. return this._useRightHandedSystem;
  21928. },
  21929. set: function (value) {
  21930. if (this._useRightHandedSystem === value) {
  21931. return;
  21932. }
  21933. this._useRightHandedSystem = value;
  21934. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Scene.prototype.setStepId = function (newStepId) {
  21940. this._currentStepId = newStepId;
  21941. };
  21942. ;
  21943. Scene.prototype.getStepId = function () {
  21944. return this._currentStepId;
  21945. };
  21946. ;
  21947. Scene.prototype.getInternalStep = function () {
  21948. return this._currentInternalStep;
  21949. };
  21950. ;
  21951. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21952. get: function () {
  21953. return this._fogEnabled;
  21954. },
  21955. /**
  21956. * is fog enabled on this scene.
  21957. */
  21958. set: function (value) {
  21959. if (this._fogEnabled === value) {
  21960. return;
  21961. }
  21962. this._fogEnabled = value;
  21963. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. Object.defineProperty(Scene.prototype, "fogMode", {
  21969. get: function () {
  21970. return this._fogMode;
  21971. },
  21972. set: function (value) {
  21973. if (this._fogMode === value) {
  21974. return;
  21975. }
  21976. this._fogMode = value;
  21977. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21983. get: function () {
  21984. return this._shadowsEnabled;
  21985. },
  21986. set: function (value) {
  21987. if (this._shadowsEnabled === value) {
  21988. return;
  21989. }
  21990. this._shadowsEnabled = value;
  21991. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21997. get: function () {
  21998. return this._lightsEnabled;
  21999. },
  22000. set: function (value) {
  22001. if (this._lightsEnabled === value) {
  22002. return;
  22003. }
  22004. this._lightsEnabled = value;
  22005. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22011. /** The default material used on meshes when no material is affected */
  22012. get: function () {
  22013. if (!this._defaultMaterial) {
  22014. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22015. }
  22016. return this._defaultMaterial;
  22017. },
  22018. /** The default material used on meshes when no material is affected */
  22019. set: function (value) {
  22020. this._defaultMaterial = value;
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22026. get: function () {
  22027. return this._texturesEnabled;
  22028. },
  22029. set: function (value) {
  22030. if (this._texturesEnabled === value) {
  22031. return;
  22032. }
  22033. this._texturesEnabled = value;
  22034. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22040. get: function () {
  22041. return this._skeletonsEnabled;
  22042. },
  22043. set: function (value) {
  22044. if (this._skeletonsEnabled === value) {
  22045. return;
  22046. }
  22047. this._skeletonsEnabled = value;
  22048. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22054. get: function () {
  22055. if (!this._postProcessRenderPipelineManager) {
  22056. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22057. }
  22058. return this._postProcessRenderPipelineManager;
  22059. },
  22060. enumerable: true,
  22061. configurable: true
  22062. });
  22063. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22064. get: function () {
  22065. if (!this._mainSoundTrack) {
  22066. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22067. }
  22068. return this._mainSoundTrack;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22074. get: function () {
  22075. return this._alternateRendering;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22081. get: function () {
  22082. return this._frustumPlanes;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22088. /**
  22089. * Gets the current geometry buffer associated to the scene.
  22090. */
  22091. get: function () {
  22092. return this._geometryBufferRenderer;
  22093. },
  22094. /**
  22095. * Sets the current geometry buffer for the scene.
  22096. */
  22097. set: function (geometryBufferRenderer) {
  22098. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22099. this._geometryBufferRenderer = geometryBufferRenderer;
  22100. }
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(Scene.prototype, "debugLayer", {
  22106. // Properties
  22107. get: function () {
  22108. if (!this._debugLayer) {
  22109. this._debugLayer = new BABYLON.DebugLayer(this);
  22110. }
  22111. return this._debugLayer;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22117. get: function () {
  22118. return this._workerCollisions;
  22119. },
  22120. set: function (enabled) {
  22121. if (!BABYLON.CollisionCoordinatorLegacy) {
  22122. return;
  22123. }
  22124. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22125. this._workerCollisions = enabled;
  22126. if (this.collisionCoordinator) {
  22127. this.collisionCoordinator.destroy();
  22128. }
  22129. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22130. this.collisionCoordinator.init(this);
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22136. get: function () {
  22137. return this._selectionOctree;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22143. /**
  22144. * The mesh that is currently under the pointer.
  22145. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22146. */
  22147. get: function () {
  22148. return this._pointerOverMesh;
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(Scene.prototype, "pointerX", {
  22154. /**
  22155. * Current on-screen X position of the pointer
  22156. * @return {number} X position of the pointer
  22157. */
  22158. get: function () {
  22159. return this._pointerX;
  22160. },
  22161. enumerable: true,
  22162. configurable: true
  22163. });
  22164. Object.defineProperty(Scene.prototype, "pointerY", {
  22165. /**
  22166. * Current on-screen Y position of the pointer
  22167. * @return {number} Y position of the pointer
  22168. */
  22169. get: function () {
  22170. return this._pointerY;
  22171. },
  22172. enumerable: true,
  22173. configurable: true
  22174. });
  22175. Scene.prototype.getCachedMaterial = function () {
  22176. return this._cachedMaterial;
  22177. };
  22178. Scene.prototype.getCachedEffect = function () {
  22179. return this._cachedEffect;
  22180. };
  22181. Scene.prototype.getCachedVisibility = function () {
  22182. return this._cachedVisibility;
  22183. };
  22184. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22185. if (visibility === void 0) { visibility = 1; }
  22186. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22187. };
  22188. Scene.prototype.getBoundingBoxRenderer = function () {
  22189. if (!this._boundingBoxRenderer) {
  22190. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22191. }
  22192. return this._boundingBoxRenderer;
  22193. };
  22194. Scene.prototype.getOutlineRenderer = function () {
  22195. return this._outlineRenderer;
  22196. };
  22197. Scene.prototype.getEngine = function () {
  22198. return this._engine;
  22199. };
  22200. Scene.prototype.getTotalVertices = function () {
  22201. return this._totalVertices.current;
  22202. };
  22203. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22204. get: function () {
  22205. return this._totalVertices;
  22206. },
  22207. enumerable: true,
  22208. configurable: true
  22209. });
  22210. Scene.prototype.getActiveIndices = function () {
  22211. return this._activeIndices.current;
  22212. };
  22213. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22214. get: function () {
  22215. return this._activeIndices;
  22216. },
  22217. enumerable: true,
  22218. configurable: true
  22219. });
  22220. Scene.prototype.getActiveParticles = function () {
  22221. return this._activeParticles.current;
  22222. };
  22223. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22224. get: function () {
  22225. return this._activeParticles;
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Scene.prototype.getActiveBones = function () {
  22231. return this._activeBones.current;
  22232. };
  22233. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22234. get: function () {
  22235. return this._activeBones;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. // Stats
  22241. Scene.prototype.getInterFramePerfCounter = function () {
  22242. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22243. return 0;
  22244. };
  22245. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22246. get: function () {
  22247. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22248. return null;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Scene.prototype.getLastFrameDuration = function () {
  22254. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22255. return 0;
  22256. };
  22257. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22258. get: function () {
  22259. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22260. return null;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22266. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22267. return 0;
  22268. };
  22269. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22270. get: function () {
  22271. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22272. return null;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Scene.prototype.getActiveMeshes = function () {
  22278. return this._activeMeshes;
  22279. };
  22280. Scene.prototype.getRenderTargetsDuration = function () {
  22281. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22282. return 0;
  22283. };
  22284. Scene.prototype.getRenderDuration = function () {
  22285. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22286. return 0;
  22287. };
  22288. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22289. get: function () {
  22290. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22291. return null;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Scene.prototype.getParticlesDuration = function () {
  22297. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22298. return 0;
  22299. };
  22300. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22301. get: function () {
  22302. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22303. return null;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Scene.prototype.getSpritesDuration = function () {
  22309. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22310. return 0;
  22311. };
  22312. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22313. get: function () {
  22314. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22315. return null;
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Scene.prototype.getAnimationRatio = function () {
  22321. return this._animationRatio;
  22322. };
  22323. Scene.prototype.getRenderId = function () {
  22324. return this._renderId;
  22325. };
  22326. Scene.prototype.incrementRenderId = function () {
  22327. this._renderId++;
  22328. };
  22329. Scene.prototype._updatePointerPosition = function (evt) {
  22330. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22331. if (!canvasRect) {
  22332. return;
  22333. }
  22334. this._pointerX = evt.clientX - canvasRect.left;
  22335. this._pointerY = evt.clientY - canvasRect.top;
  22336. this._unTranslatedPointerX = this._pointerX;
  22337. this._unTranslatedPointerY = this._pointerY;
  22338. };
  22339. Scene.prototype._createUbo = function () {
  22340. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22341. this._sceneUbo.addUniform("viewProjection", 16);
  22342. this._sceneUbo.addUniform("view", 16);
  22343. };
  22344. Scene.prototype._createAlternateUbo = function () {
  22345. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22346. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22347. this._alternateSceneUbo.addUniform("view", 16);
  22348. };
  22349. // Pointers handling
  22350. /**
  22351. * Use this method to simulate a pointer move on a mesh
  22352. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22353. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22354. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22355. */
  22356. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22357. var evt = new PointerEvent("pointermove", pointerEventInit);
  22358. return this._processPointerMove(pickResult, evt);
  22359. };
  22360. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22361. var canvas = this._engine.getRenderingCanvas();
  22362. if (!canvas) {
  22363. return this;
  22364. }
  22365. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22366. this.setPointerOverSprite(null);
  22367. this.setPointerOverMesh(pickResult.pickedMesh);
  22368. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22369. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22370. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22371. }
  22372. else {
  22373. canvas.style.cursor = this.hoverCursor;
  22374. }
  22375. }
  22376. else {
  22377. canvas.style.cursor = this.defaultCursor;
  22378. }
  22379. }
  22380. else {
  22381. this.setPointerOverMesh(null);
  22382. // Sprites
  22383. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22384. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22385. this.setPointerOverSprite(pickResult.pickedSprite);
  22386. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22387. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22388. }
  22389. else {
  22390. canvas.style.cursor = this.hoverCursor;
  22391. }
  22392. }
  22393. else {
  22394. this.setPointerOverSprite(null);
  22395. // Restore pointer
  22396. canvas.style.cursor = this.defaultCursor;
  22397. }
  22398. }
  22399. if (pickResult) {
  22400. if (this.onPointerMove) {
  22401. this.onPointerMove(evt, pickResult);
  22402. }
  22403. if (this.onPointerObservable.hasObservers()) {
  22404. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22405. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22406. this.onPointerObservable.notifyObservers(pi, type);
  22407. }
  22408. }
  22409. return this;
  22410. };
  22411. /**
  22412. * Use this method to simulate a pointer down on a mesh
  22413. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22414. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22415. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22416. */
  22417. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22418. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22419. return this._processPointerDown(pickResult, evt);
  22420. };
  22421. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22422. var _this = this;
  22423. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22424. this._pickedDownMesh = pickResult.pickedMesh;
  22425. var actionManager = pickResult.pickedMesh.actionManager;
  22426. if (actionManager) {
  22427. if (actionManager.hasPickTriggers) {
  22428. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22429. switch (evt.button) {
  22430. case 0:
  22431. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22432. break;
  22433. case 1:
  22434. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22435. break;
  22436. case 2:
  22437. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22438. break;
  22439. }
  22440. }
  22441. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22442. window.setTimeout(function () {
  22443. 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);
  22444. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22445. if (_this._totalPointersPressed !== 0 &&
  22446. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22447. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22448. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22449. _this._startingPointerTime = 0;
  22450. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22451. }
  22452. }
  22453. }, Scene.LongPressDelay);
  22454. }
  22455. }
  22456. }
  22457. if (pickResult) {
  22458. if (this.onPointerDown) {
  22459. this.onPointerDown(evt, pickResult);
  22460. }
  22461. if (this.onPointerObservable.hasObservers()) {
  22462. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22463. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22464. this.onPointerObservable.notifyObservers(pi, type);
  22465. }
  22466. }
  22467. return this;
  22468. };
  22469. /**
  22470. * Use this method to simulate a pointer up on a mesh
  22471. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22472. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22473. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22474. */
  22475. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22476. var evt = new PointerEvent("pointerup", pointerEventInit);
  22477. var clickInfo = new ClickInfo();
  22478. clickInfo.singleClick = true;
  22479. clickInfo.ignore = true;
  22480. return this._processPointerUp(pickResult, evt, clickInfo);
  22481. };
  22482. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22483. if (pickResult && pickResult && pickResult.pickedMesh) {
  22484. this._pickedUpMesh = pickResult.pickedMesh;
  22485. if (this._pickedDownMesh === this._pickedUpMesh) {
  22486. if (this.onPointerPick) {
  22487. this.onPointerPick(evt, pickResult);
  22488. }
  22489. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22490. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22491. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22492. this.onPointerObservable.notifyObservers(pi, type);
  22493. }
  22494. }
  22495. if (pickResult.pickedMesh.actionManager) {
  22496. if (clickInfo.ignore) {
  22497. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22498. }
  22499. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22500. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22501. }
  22502. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22503. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22504. }
  22505. }
  22506. }
  22507. if (this._pickedDownMesh &&
  22508. this._pickedDownMesh.actionManager &&
  22509. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22510. this._pickedDownMesh !== this._pickedUpMesh) {
  22511. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22512. }
  22513. if (this.onPointerUp) {
  22514. this.onPointerUp(evt, pickResult);
  22515. }
  22516. if (this.onPointerObservable.hasObservers()) {
  22517. if (!clickInfo.ignore) {
  22518. if (!clickInfo.hasSwiped) {
  22519. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22520. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22521. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22522. this.onPointerObservable.notifyObservers(pi, type);
  22523. }
  22524. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22525. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22526. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22527. this.onPointerObservable.notifyObservers(pi, type);
  22528. }
  22529. }
  22530. }
  22531. else {
  22532. var type = BABYLON.PointerEventTypes.POINTERUP;
  22533. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22534. this.onPointerObservable.notifyObservers(pi, type);
  22535. }
  22536. }
  22537. return this;
  22538. };
  22539. /**
  22540. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22541. * @param attachUp defines if you want to attach events to pointerup
  22542. * @param attachDown defines if you want to attach events to pointerdown
  22543. * @param attachMove defines if you want to attach events to pointermove
  22544. */
  22545. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22546. var _this = this;
  22547. if (attachUp === void 0) { attachUp = true; }
  22548. if (attachDown === void 0) { attachDown = true; }
  22549. if (attachMove === void 0) { attachMove = true; }
  22550. this._initActionManager = function (act, clickInfo) {
  22551. if (!_this._meshPickProceed) {
  22552. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22553. _this._currentPickResult = pickResult;
  22554. if (pickResult) {
  22555. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22556. }
  22557. _this._meshPickProceed = true;
  22558. }
  22559. return act;
  22560. };
  22561. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22562. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22563. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22564. btn !== _this._previousButtonPressed) {
  22565. _this._doubleClickOccured = false;
  22566. clickInfo.singleClick = true;
  22567. clickInfo.ignore = false;
  22568. cb(clickInfo, _this._currentPickResult);
  22569. }
  22570. };
  22571. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22572. var clickInfo = new ClickInfo();
  22573. _this._currentPickResult = null;
  22574. var act = null;
  22575. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22576. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22577. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22578. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22579. act = _this._initActionManager(act, clickInfo);
  22580. if (act)
  22581. checkPicking = act.hasPickTriggers;
  22582. }
  22583. if (checkPicking) {
  22584. var btn = evt.button;
  22585. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22586. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22587. if (!clickInfo.hasSwiped) {
  22588. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22589. if (!checkSingleClickImmediately) {
  22590. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22591. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22592. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22593. act = _this._initActionManager(act, clickInfo);
  22594. if (act)
  22595. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22596. }
  22597. }
  22598. if (checkSingleClickImmediately) {
  22599. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22600. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22601. btn !== _this._previousButtonPressed) {
  22602. clickInfo.singleClick = true;
  22603. cb(clickInfo, _this._currentPickResult);
  22604. }
  22605. }
  22606. else {
  22607. // wait that no double click has been raised during the double click delay
  22608. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22609. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22610. }
  22611. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22612. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22613. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22614. act = _this._initActionManager(act, clickInfo);
  22615. if (act)
  22616. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22617. }
  22618. if (checkDoubleClick) {
  22619. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22620. if (btn === _this._previousButtonPressed &&
  22621. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22622. !_this._doubleClickOccured) {
  22623. // pointer has not moved for 2 clicks, it's a double click
  22624. if (!clickInfo.hasSwiped &&
  22625. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22626. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22627. _this._previousStartingPointerTime = 0;
  22628. _this._doubleClickOccured = true;
  22629. clickInfo.doubleClick = true;
  22630. clickInfo.ignore = false;
  22631. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22632. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22633. }
  22634. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22635. cb(clickInfo, _this._currentPickResult);
  22636. }
  22637. else {
  22638. _this._doubleClickOccured = false;
  22639. _this._previousStartingPointerTime = _this._startingPointerTime;
  22640. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22641. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22642. _this._previousButtonPressed = btn;
  22643. if (Scene.ExclusiveDoubleClickMode) {
  22644. if (_this._previousDelayedSimpleClickTimeout) {
  22645. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22646. }
  22647. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22648. cb(clickInfo, _this._previousPickResult);
  22649. }
  22650. else {
  22651. cb(clickInfo, _this._currentPickResult);
  22652. }
  22653. }
  22654. }
  22655. else {
  22656. _this._doubleClickOccured = false;
  22657. _this._previousStartingPointerTime = _this._startingPointerTime;
  22658. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22659. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22660. _this._previousButtonPressed = btn;
  22661. }
  22662. }
  22663. }
  22664. }
  22665. clickInfo.ignore = true;
  22666. cb(clickInfo, _this._currentPickResult);
  22667. };
  22668. this._spritePredicate = function (sprite) {
  22669. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22670. };
  22671. this._onPointerMove = function (evt) {
  22672. _this._updatePointerPosition(evt);
  22673. // PreObservable support
  22674. if (_this.onPrePointerObservable.hasObservers()) {
  22675. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22676. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22677. _this.onPrePointerObservable.notifyObservers(pi, type);
  22678. if (pi.skipOnPointerObservable) {
  22679. return;
  22680. }
  22681. }
  22682. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22683. return;
  22684. }
  22685. if (!_this.pointerMovePredicate) {
  22686. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22687. }
  22688. // Meshes
  22689. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22690. _this._processPointerMove(pickResult, evt);
  22691. };
  22692. this._onPointerDown = function (evt) {
  22693. _this._totalPointersPressed++;
  22694. _this._pickedDownMesh = null;
  22695. _this._meshPickProceed = false;
  22696. _this._updatePointerPosition(evt);
  22697. if (_this.preventDefaultOnPointerDown && canvas) {
  22698. evt.preventDefault();
  22699. canvas.focus();
  22700. }
  22701. // PreObservable support
  22702. if (_this.onPrePointerObservable.hasObservers()) {
  22703. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22704. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22705. _this.onPrePointerObservable.notifyObservers(pi, type);
  22706. if (pi.skipOnPointerObservable) {
  22707. return;
  22708. }
  22709. }
  22710. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22711. return;
  22712. }
  22713. _this._startingPointerPosition.x = _this._pointerX;
  22714. _this._startingPointerPosition.y = _this._pointerY;
  22715. _this._startingPointerTime = new Date().getTime();
  22716. if (!_this.pointerDownPredicate) {
  22717. _this.pointerDownPredicate = function (mesh) {
  22718. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22719. };
  22720. }
  22721. // Meshes
  22722. _this._pickedDownMesh = null;
  22723. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22724. _this._processPointerDown(pickResult, evt);
  22725. // Sprites
  22726. _this._pickedDownSprite = null;
  22727. if (_this.spriteManagers.length > 0) {
  22728. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22729. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22730. if (pickResult.pickedSprite.actionManager) {
  22731. _this._pickedDownSprite = pickResult.pickedSprite;
  22732. switch (evt.button) {
  22733. case 0:
  22734. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22735. break;
  22736. case 1:
  22737. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22738. break;
  22739. case 2:
  22740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22741. break;
  22742. }
  22743. if (pickResult.pickedSprite.actionManager) {
  22744. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22745. }
  22746. }
  22747. }
  22748. }
  22749. };
  22750. this._onPointerUp = function (evt) {
  22751. if (_this._totalPointersPressed === 0) {
  22752. return; // So we need to test it the pointer down was pressed before.
  22753. }
  22754. _this._totalPointersPressed--;
  22755. _this._pickedUpMesh = null;
  22756. _this._meshPickProceed = false;
  22757. _this._updatePointerPosition(evt);
  22758. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22759. // PreObservable support
  22760. if (_this.onPrePointerObservable.hasObservers()) {
  22761. if (!clickInfo.ignore) {
  22762. if (!clickInfo.hasSwiped) {
  22763. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22764. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22765. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22766. _this.onPrePointerObservable.notifyObservers(pi, type);
  22767. if (pi.skipOnPointerObservable) {
  22768. return;
  22769. }
  22770. }
  22771. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22772. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22773. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22774. _this.onPrePointerObservable.notifyObservers(pi, type);
  22775. if (pi.skipOnPointerObservable) {
  22776. return;
  22777. }
  22778. }
  22779. }
  22780. }
  22781. else {
  22782. var type = BABYLON.PointerEventTypes.POINTERUP;
  22783. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22784. _this.onPrePointerObservable.notifyObservers(pi, type);
  22785. if (pi.skipOnPointerObservable) {
  22786. return;
  22787. }
  22788. }
  22789. }
  22790. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22791. return;
  22792. }
  22793. if (!_this.pointerUpPredicate) {
  22794. _this.pointerUpPredicate = function (mesh) {
  22795. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22796. };
  22797. }
  22798. // Meshes
  22799. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22800. _this._initActionManager(null, clickInfo);
  22801. }
  22802. if (!pickResult) {
  22803. pickResult = _this._currentPickResult;
  22804. }
  22805. _this._processPointerUp(pickResult, evt, clickInfo);
  22806. // Sprites
  22807. if (_this.spriteManagers.length > 0) {
  22808. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22809. if (spritePickResult) {
  22810. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22811. if (spritePickResult.pickedSprite.actionManager) {
  22812. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22813. if (spritePickResult.pickedSprite.actionManager) {
  22814. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22815. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22816. }
  22817. }
  22818. }
  22819. }
  22820. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22821. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22822. }
  22823. }
  22824. }
  22825. _this._previousPickResult = _this._currentPickResult;
  22826. });
  22827. };
  22828. this._onKeyDown = function (evt) {
  22829. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22830. if (_this.onPreKeyboardObservable.hasObservers()) {
  22831. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22832. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22833. if (pi.skipOnPointerObservable) {
  22834. return;
  22835. }
  22836. }
  22837. if (_this.onKeyboardObservable.hasObservers()) {
  22838. var pi = new BABYLON.KeyboardInfo(type, evt);
  22839. _this.onKeyboardObservable.notifyObservers(pi, type);
  22840. }
  22841. if (_this.actionManager) {
  22842. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22843. }
  22844. };
  22845. this._onKeyUp = function (evt) {
  22846. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22847. if (_this.onPreKeyboardObservable.hasObservers()) {
  22848. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22849. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22850. if (pi.skipOnPointerObservable) {
  22851. return;
  22852. }
  22853. }
  22854. if (_this.onKeyboardObservable.hasObservers()) {
  22855. var pi = new BABYLON.KeyboardInfo(type, evt);
  22856. _this.onKeyboardObservable.notifyObservers(pi, type);
  22857. }
  22858. if (_this.actionManager) {
  22859. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22860. }
  22861. };
  22862. var engine = this.getEngine();
  22863. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22864. if (!canvas) {
  22865. return;
  22866. }
  22867. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22868. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22869. });
  22870. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22871. if (!canvas) {
  22872. return;
  22873. }
  22874. canvas.removeEventListener("keydown", _this._onKeyDown);
  22875. canvas.removeEventListener("keyup", _this._onKeyUp);
  22876. });
  22877. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22878. var canvas = this._engine.getRenderingCanvas();
  22879. if (!canvas) {
  22880. return;
  22881. }
  22882. if (attachMove) {
  22883. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22884. // Wheel
  22885. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22886. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22887. }
  22888. if (attachDown) {
  22889. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22890. }
  22891. if (attachUp) {
  22892. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22893. }
  22894. canvas.tabIndex = 1;
  22895. };
  22896. Scene.prototype.detachControl = function () {
  22897. var engine = this.getEngine();
  22898. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22899. var canvas = engine.getRenderingCanvas();
  22900. if (!canvas) {
  22901. return;
  22902. }
  22903. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22904. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22905. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22906. if (this._onCanvasBlurObserver) {
  22907. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22908. }
  22909. if (this._onCanvasFocusObserver) {
  22910. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22911. }
  22912. // Wheel
  22913. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22914. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22915. // Keyboard
  22916. canvas.removeEventListener("keydown", this._onKeyDown);
  22917. canvas.removeEventListener("keyup", this._onKeyUp);
  22918. // Observables
  22919. this.onKeyboardObservable.clear();
  22920. this.onPreKeyboardObservable.clear();
  22921. this.onPointerObservable.clear();
  22922. this.onPrePointerObservable.clear();
  22923. };
  22924. /**
  22925. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22926. * Delay loaded resources are not taking in account
  22927. * @return true if all required resources are ready
  22928. */
  22929. Scene.prototype.isReady = function () {
  22930. if (this._isDisposed) {
  22931. return false;
  22932. }
  22933. if (this._pendingData.length > 0) {
  22934. return false;
  22935. }
  22936. var index;
  22937. var engine = this.getEngine();
  22938. // Geometries
  22939. for (index = 0; index < this._geometries.length; index++) {
  22940. var geometry = this._geometries[index];
  22941. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22942. return false;
  22943. }
  22944. }
  22945. // Meshes
  22946. for (index = 0; index < this.meshes.length; index++) {
  22947. var mesh = this.meshes[index];
  22948. if (!mesh.isEnabled()) {
  22949. continue;
  22950. }
  22951. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22952. continue;
  22953. }
  22954. if (!mesh.isReady(true)) {
  22955. return false;
  22956. }
  22957. // Effect layers
  22958. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22959. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22960. var layer = _a[_i];
  22961. if (!layer.hasMesh(mesh)) {
  22962. continue;
  22963. }
  22964. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22965. var subMesh = _c[_b];
  22966. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22967. return false;
  22968. }
  22969. }
  22970. }
  22971. }
  22972. return true;
  22973. };
  22974. Scene.prototype.resetCachedMaterial = function () {
  22975. this._cachedMaterial = null;
  22976. this._cachedEffect = null;
  22977. this._cachedVisibility = null;
  22978. };
  22979. Scene.prototype.registerBeforeRender = function (func) {
  22980. this.onBeforeRenderObservable.add(func);
  22981. };
  22982. Scene.prototype.unregisterBeforeRender = function (func) {
  22983. this.onBeforeRenderObservable.removeCallback(func);
  22984. };
  22985. Scene.prototype.registerAfterRender = function (func) {
  22986. this.onAfterRenderObservable.add(func);
  22987. };
  22988. Scene.prototype.unregisterAfterRender = function (func) {
  22989. this.onAfterRenderObservable.removeCallback(func);
  22990. };
  22991. Scene.prototype._executeOnceBeforeRender = function (func) {
  22992. var _this = this;
  22993. var execFunc = function () {
  22994. func();
  22995. setTimeout(function () {
  22996. _this.unregisterBeforeRender(execFunc);
  22997. });
  22998. };
  22999. this.registerBeforeRender(execFunc);
  23000. };
  23001. /**
  23002. * The provided function will run before render once and will be disposed afterwards.
  23003. * A timeout delay can be provided so that the function will be executed in N ms.
  23004. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23005. * @param func The function to be executed.
  23006. * @param timeout optional delay in ms
  23007. */
  23008. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23009. var _this = this;
  23010. if (timeout !== undefined) {
  23011. setTimeout(function () {
  23012. _this._executeOnceBeforeRender(func);
  23013. }, timeout);
  23014. }
  23015. else {
  23016. this._executeOnceBeforeRender(func);
  23017. }
  23018. };
  23019. Scene.prototype._addPendingData = function (data) {
  23020. this._pendingData.push(data);
  23021. };
  23022. Scene.prototype._removePendingData = function (data) {
  23023. var wasLoading = this.isLoading;
  23024. var index = this._pendingData.indexOf(data);
  23025. if (index !== -1) {
  23026. this._pendingData.splice(index, 1);
  23027. }
  23028. if (wasLoading && !this.isLoading) {
  23029. this.onDataLoadedObservable.notifyObservers(this);
  23030. }
  23031. };
  23032. Scene.prototype.getWaitingItemsCount = function () {
  23033. return this._pendingData.length;
  23034. };
  23035. Object.defineProperty(Scene.prototype, "isLoading", {
  23036. get: function () {
  23037. return this._pendingData.length > 0;
  23038. },
  23039. enumerable: true,
  23040. configurable: true
  23041. });
  23042. /**
  23043. * Registers a function to be executed when the scene is ready.
  23044. * @param {Function} func - the function to be executed.
  23045. */
  23046. Scene.prototype.executeWhenReady = function (func) {
  23047. var _this = this;
  23048. this.onReadyObservable.add(func);
  23049. if (this._executeWhenReadyTimeoutId !== -1) {
  23050. return;
  23051. }
  23052. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23053. _this._checkIsReady();
  23054. }, 150);
  23055. };
  23056. /**
  23057. * Returns a promise that resolves when the scene is ready.
  23058. * @returns A promise that resolves when the scene is ready.
  23059. */
  23060. Scene.prototype.whenReadyAsync = function () {
  23061. var _this = this;
  23062. return new Promise(function (resolve) {
  23063. _this.executeWhenReady(function () {
  23064. resolve();
  23065. });
  23066. });
  23067. };
  23068. Scene.prototype._checkIsReady = function () {
  23069. var _this = this;
  23070. if (this.isReady()) {
  23071. this.onReadyObservable.notifyObservers(this);
  23072. this.onReadyObservable.clear();
  23073. this._executeWhenReadyTimeoutId = -1;
  23074. return;
  23075. }
  23076. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23077. _this._checkIsReady();
  23078. }, 150);
  23079. };
  23080. // Animations
  23081. /**
  23082. * Will start the animation sequence of a given target
  23083. * @param target - the target
  23084. * @param {number} from - from which frame should animation start
  23085. * @param {number} to - till which frame should animation run.
  23086. * @param {boolean} [loop] - should the animation loop
  23087. * @param {number} [speedRatio] - the speed in which to run the animation
  23088. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23089. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23090. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23091. * See BABYLON.Animatable
  23092. */
  23093. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23094. if (speedRatio === void 0) { speedRatio = 1.0; }
  23095. if (from > to && speedRatio > 0) {
  23096. speedRatio *= -1;
  23097. }
  23098. this.stopAnimation(target);
  23099. if (!animatable) {
  23100. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23101. }
  23102. // Local animations
  23103. if (target.animations) {
  23104. animatable.appendAnimations(target, target.animations);
  23105. }
  23106. // Children animations
  23107. if (target.getAnimatables) {
  23108. var animatables = target.getAnimatables();
  23109. for (var index = 0; index < animatables.length; index++) {
  23110. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23111. }
  23112. }
  23113. animatable.reset();
  23114. return animatable;
  23115. };
  23116. /**
  23117. * Begin a new animation on a given node
  23118. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23119. * @param {BABYLON.Animation[]} defines the list of animations to start
  23120. * @param {number} from defines the initial value
  23121. * @param {number} to defines the final value
  23122. * @param {boolean} loop defines if you want animation to loop (off by default)
  23123. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23124. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23125. * @returns the list of created animatables
  23126. */
  23127. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23128. if (speedRatio === undefined) {
  23129. speedRatio = 1.0;
  23130. }
  23131. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23132. return animatable;
  23133. };
  23134. /**
  23135. * Begin a new animation on a given node and its hierarchy
  23136. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23137. * @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.
  23138. * @param {BABYLON.Animation[]} defines the list of animations to start
  23139. * @param {number} from defines the initial value
  23140. * @param {number} to defines the final value
  23141. * @param {boolean} loop defines if you want animation to loop (off by default)
  23142. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23143. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23144. * @returns the list of animatables created for all nodes
  23145. */
  23146. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23147. var children = target.getDescendants(directDescendantsOnly);
  23148. var result = [];
  23149. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23150. var child = children_1[_i];
  23151. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23152. }
  23153. return result;
  23154. };
  23155. Scene.prototype.getAnimatableByTarget = function (target) {
  23156. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23157. if (this._activeAnimatables[index].target === target) {
  23158. return this._activeAnimatables[index];
  23159. }
  23160. }
  23161. return null;
  23162. };
  23163. Object.defineProperty(Scene.prototype, "animatables", {
  23164. get: function () {
  23165. return this._activeAnimatables;
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. /**
  23171. * Will stop the animation of the given target
  23172. * @param target - the target
  23173. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23174. * @see beginAnimation
  23175. */
  23176. Scene.prototype.stopAnimation = function (target, animationName) {
  23177. var animatable = this.getAnimatableByTarget(target);
  23178. if (animatable) {
  23179. animatable.stop(animationName);
  23180. }
  23181. };
  23182. /**
  23183. * Stops and removes all animations that have been applied to the scene
  23184. */
  23185. Scene.prototype.stopAllAnimations = function () {
  23186. if (this._activeAnimatables) {
  23187. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23188. this._activeAnimatables[i].stop();
  23189. }
  23190. this._activeAnimatables = [];
  23191. }
  23192. };
  23193. Scene.prototype._animate = function () {
  23194. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23195. return;
  23196. }
  23197. // Getting time
  23198. var now = BABYLON.Tools.Now;
  23199. if (!this._animationTimeLast) {
  23200. if (this._pendingData.length > 0) {
  23201. return;
  23202. }
  23203. this._animationTimeLast = now;
  23204. }
  23205. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23206. this._animationTime += deltaTime;
  23207. this._animationTimeLast = now;
  23208. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23209. this._activeAnimatables[index]._animate(this._animationTime);
  23210. }
  23211. };
  23212. // Matrix
  23213. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23214. this._useAlternateCameraConfiguration = active;
  23215. };
  23216. Scene.prototype.getViewMatrix = function () {
  23217. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23218. };
  23219. Scene.prototype.getProjectionMatrix = function () {
  23220. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23221. };
  23222. Scene.prototype.getTransformMatrix = function () {
  23223. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23224. };
  23225. Scene.prototype.setTransformMatrix = function (view, projection) {
  23226. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23227. return;
  23228. }
  23229. this._viewUpdateFlag = view.updateFlag;
  23230. this._projectionUpdateFlag = projection.updateFlag;
  23231. this._viewMatrix = view;
  23232. this._projectionMatrix = projection;
  23233. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23234. // Update frustum
  23235. if (!this._frustumPlanes) {
  23236. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23237. }
  23238. else {
  23239. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23240. }
  23241. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23242. var otherCamera = this.activeCamera._alternateCamera;
  23243. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23244. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23245. }
  23246. if (this._sceneUbo.useUbo) {
  23247. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23248. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23249. this._sceneUbo.update();
  23250. }
  23251. };
  23252. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23253. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23254. return;
  23255. }
  23256. this._alternateViewUpdateFlag = view.updateFlag;
  23257. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23258. this._alternateViewMatrix = view;
  23259. this._alternateProjectionMatrix = projection;
  23260. if (!this._alternateTransformMatrix) {
  23261. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23262. }
  23263. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23264. if (!this._alternateSceneUbo) {
  23265. this._createAlternateUbo();
  23266. }
  23267. if (this._alternateSceneUbo.useUbo) {
  23268. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23269. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23270. this._alternateSceneUbo.update();
  23271. }
  23272. };
  23273. Scene.prototype.getSceneUniformBuffer = function () {
  23274. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23275. };
  23276. // Methods
  23277. Scene.prototype.getUniqueId = function () {
  23278. var result = Scene._uniqueIdCounter;
  23279. Scene._uniqueIdCounter++;
  23280. return result;
  23281. };
  23282. Scene.prototype.addMesh = function (newMesh) {
  23283. this.meshes.push(newMesh);
  23284. //notify the collision coordinator
  23285. if (this.collisionCoordinator) {
  23286. this.collisionCoordinator.onMeshAdded(newMesh);
  23287. }
  23288. newMesh._resyncLightSources();
  23289. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23290. };
  23291. Scene.prototype.removeMesh = function (toRemove) {
  23292. var index = this.meshes.indexOf(toRemove);
  23293. if (index !== -1) {
  23294. // Remove from the scene if mesh found
  23295. this.meshes.splice(index, 1);
  23296. }
  23297. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23298. return index;
  23299. };
  23300. Scene.prototype.addTransformNode = function (newTransformNode) {
  23301. this.transformNodes.push(newTransformNode);
  23302. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23303. };
  23304. Scene.prototype.removeTransformNode = function (toRemove) {
  23305. var index = this.transformNodes.indexOf(toRemove);
  23306. if (index !== -1) {
  23307. // Remove from the scene if found
  23308. this.transformNodes.splice(index, 1);
  23309. }
  23310. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23311. return index;
  23312. };
  23313. Scene.prototype.removeSkeleton = function (toRemove) {
  23314. var index = this.skeletons.indexOf(toRemove);
  23315. if (index !== -1) {
  23316. // Remove from the scene if found
  23317. this.skeletons.splice(index, 1);
  23318. }
  23319. return index;
  23320. };
  23321. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23322. var index = this.morphTargetManagers.indexOf(toRemove);
  23323. if (index !== -1) {
  23324. // Remove from the scene if found
  23325. this.morphTargetManagers.splice(index, 1);
  23326. }
  23327. return index;
  23328. };
  23329. Scene.prototype.removeLight = function (toRemove) {
  23330. var index = this.lights.indexOf(toRemove);
  23331. if (index !== -1) {
  23332. // Remove from meshes
  23333. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23334. var mesh = _a[_i];
  23335. mesh._removeLightSource(toRemove);
  23336. }
  23337. // Remove from the scene if mesh found
  23338. this.lights.splice(index, 1);
  23339. this.sortLightsByPriority();
  23340. }
  23341. this.onLightRemovedObservable.notifyObservers(toRemove);
  23342. return index;
  23343. };
  23344. Scene.prototype.removeCamera = function (toRemove) {
  23345. var index = this.cameras.indexOf(toRemove);
  23346. if (index !== -1) {
  23347. // Remove from the scene if mesh found
  23348. this.cameras.splice(index, 1);
  23349. }
  23350. // Remove from activeCameras
  23351. var index2 = this.activeCameras.indexOf(toRemove);
  23352. if (index2 !== -1) {
  23353. // Remove from the scene if mesh found
  23354. this.activeCameras.splice(index2, 1);
  23355. }
  23356. // Reset the activeCamera
  23357. if (this.activeCamera === toRemove) {
  23358. if (this.cameras.length > 0) {
  23359. this.activeCamera = this.cameras[0];
  23360. }
  23361. else {
  23362. this.activeCamera = null;
  23363. }
  23364. }
  23365. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23366. return index;
  23367. };
  23368. Scene.prototype.removeParticleSystem = function (toRemove) {
  23369. var index = this.particleSystems.indexOf(toRemove);
  23370. if (index !== -1) {
  23371. this.particleSystems.splice(index, 1);
  23372. }
  23373. return index;
  23374. };
  23375. ;
  23376. Scene.prototype.removeAnimation = function (toRemove) {
  23377. var index = this.animations.indexOf(toRemove);
  23378. if (index !== -1) {
  23379. this.animations.splice(index, 1);
  23380. }
  23381. return index;
  23382. };
  23383. ;
  23384. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23385. var index = this.multiMaterials.indexOf(toRemove);
  23386. if (index !== -1) {
  23387. this.multiMaterials.splice(index, 1);
  23388. }
  23389. return index;
  23390. };
  23391. ;
  23392. Scene.prototype.removeMaterial = function (toRemove) {
  23393. var index = this.materials.indexOf(toRemove);
  23394. if (index !== -1) {
  23395. this.materials.splice(index, 1);
  23396. }
  23397. return index;
  23398. };
  23399. ;
  23400. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23401. var index = this.lensFlareSystems.indexOf(toRemove);
  23402. if (index !== -1) {
  23403. this.lensFlareSystems.splice(index, 1);
  23404. }
  23405. return index;
  23406. };
  23407. ;
  23408. Scene.prototype.removeActionManager = function (toRemove) {
  23409. var index = this._actionManagers.indexOf(toRemove);
  23410. if (index !== -1) {
  23411. this._actionManagers.splice(index, 1);
  23412. }
  23413. return index;
  23414. };
  23415. ;
  23416. Scene.prototype.addLight = function (newLight) {
  23417. this.lights.push(newLight);
  23418. this.sortLightsByPriority();
  23419. // Add light to all meshes (To support if the light is removed and then readded)
  23420. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23421. var mesh = _a[_i];
  23422. if (mesh._lightSources.indexOf(newLight) === -1) {
  23423. mesh._lightSources.push(newLight);
  23424. mesh._resyncLightSources();
  23425. }
  23426. }
  23427. this.onNewLightAddedObservable.notifyObservers(newLight);
  23428. };
  23429. Scene.prototype.sortLightsByPriority = function () {
  23430. if (this.requireLightSorting) {
  23431. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23432. }
  23433. };
  23434. Scene.prototype.addCamera = function (newCamera) {
  23435. this.cameras.push(newCamera);
  23436. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23437. };
  23438. Scene.prototype.addSkeleton = function (newSkeleton) {
  23439. this.skeletons.push(newSkeleton);
  23440. };
  23441. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23442. this.particleSystems.push(newParticleSystem);
  23443. };
  23444. Scene.prototype.addAnimation = function (newAnimation) {
  23445. this.animations.push(newAnimation);
  23446. };
  23447. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23448. this.multiMaterials.push(newMultiMaterial);
  23449. };
  23450. Scene.prototype.addMaterial = function (newMaterial) {
  23451. this.materials.push(newMaterial);
  23452. };
  23453. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23454. this.morphTargetManagers.push(newMorphTargetManager);
  23455. };
  23456. Scene.prototype.addGeometry = function (newGeometrie) {
  23457. this._geometries.push(newGeometrie);
  23458. };
  23459. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23460. this.lensFlareSystems.push(newLensFlareSystem);
  23461. };
  23462. Scene.prototype.addActionManager = function (newActionManager) {
  23463. this._actionManagers.push(newActionManager);
  23464. };
  23465. /**
  23466. * Switch active camera
  23467. * @param {Camera} newCamera - new active camera
  23468. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23469. */
  23470. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23471. if (attachControl === void 0) { attachControl = true; }
  23472. var canvas = this._engine.getRenderingCanvas();
  23473. if (!canvas) {
  23474. return;
  23475. }
  23476. if (this.activeCamera) {
  23477. this.activeCamera.detachControl(canvas);
  23478. }
  23479. this.activeCamera = newCamera;
  23480. if (attachControl) {
  23481. newCamera.attachControl(canvas);
  23482. }
  23483. };
  23484. /**
  23485. * sets the active camera of the scene using its ID
  23486. * @param {string} id - the camera's ID
  23487. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23488. * @see activeCamera
  23489. */
  23490. Scene.prototype.setActiveCameraByID = function (id) {
  23491. var camera = this.getCameraByID(id);
  23492. if (camera) {
  23493. this.activeCamera = camera;
  23494. return camera;
  23495. }
  23496. return null;
  23497. };
  23498. /**
  23499. * sets the active camera of the scene using its name
  23500. * @param {string} name - the camera's name
  23501. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23502. * @see activeCamera
  23503. */
  23504. Scene.prototype.setActiveCameraByName = function (name) {
  23505. var camera = this.getCameraByName(name);
  23506. if (camera) {
  23507. this.activeCamera = camera;
  23508. return camera;
  23509. }
  23510. return null;
  23511. };
  23512. /**
  23513. * get an animation group using its name
  23514. * @param {string} the material's name
  23515. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23516. */
  23517. Scene.prototype.getAnimationGroupByName = function (name) {
  23518. for (var index = 0; index < this.animationGroups.length; index++) {
  23519. if (this.animationGroups[index].name === name) {
  23520. return this.animationGroups[index];
  23521. }
  23522. }
  23523. return null;
  23524. };
  23525. /**
  23526. * get a material using its id
  23527. * @param {string} the material's ID
  23528. * @return {BABYLON.Material|null} the material or null if none found.
  23529. */
  23530. Scene.prototype.getMaterialByID = function (id) {
  23531. for (var index = 0; index < this.materials.length; index++) {
  23532. if (this.materials[index].id === id) {
  23533. return this.materials[index];
  23534. }
  23535. }
  23536. return null;
  23537. };
  23538. /**
  23539. * get a material using its name
  23540. * @param {string} the material's name
  23541. * @return {BABYLON.Material|null} the material or null if none found.
  23542. */
  23543. Scene.prototype.getMaterialByName = function (name) {
  23544. for (var index = 0; index < this.materials.length; index++) {
  23545. if (this.materials[index].name === name) {
  23546. return this.materials[index];
  23547. }
  23548. }
  23549. return null;
  23550. };
  23551. Scene.prototype.getLensFlareSystemByName = function (name) {
  23552. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23553. if (this.lensFlareSystems[index].name === name) {
  23554. return this.lensFlareSystems[index];
  23555. }
  23556. }
  23557. return null;
  23558. };
  23559. Scene.prototype.getLensFlareSystemByID = function (id) {
  23560. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23561. if (this.lensFlareSystems[index].id === id) {
  23562. return this.lensFlareSystems[index];
  23563. }
  23564. }
  23565. return null;
  23566. };
  23567. Scene.prototype.getCameraByID = function (id) {
  23568. for (var index = 0; index < this.cameras.length; index++) {
  23569. if (this.cameras[index].id === id) {
  23570. return this.cameras[index];
  23571. }
  23572. }
  23573. return null;
  23574. };
  23575. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23576. for (var index = 0; index < this.cameras.length; index++) {
  23577. if (this.cameras[index].uniqueId === uniqueId) {
  23578. return this.cameras[index];
  23579. }
  23580. }
  23581. return null;
  23582. };
  23583. /**
  23584. * get a camera using its name
  23585. * @param {string} the camera's name
  23586. * @return {BABYLON.Camera|null} the camera or null if none found.
  23587. */
  23588. Scene.prototype.getCameraByName = function (name) {
  23589. for (var index = 0; index < this.cameras.length; index++) {
  23590. if (this.cameras[index].name === name) {
  23591. return this.cameras[index];
  23592. }
  23593. }
  23594. return null;
  23595. };
  23596. /**
  23597. * get a bone using its id
  23598. * @param {string} the bone's id
  23599. * @return {BABYLON.Bone|null} the bone or null if not found
  23600. */
  23601. Scene.prototype.getBoneByID = function (id) {
  23602. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23603. var skeleton = this.skeletons[skeletonIndex];
  23604. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23605. if (skeleton.bones[boneIndex].id === id) {
  23606. return skeleton.bones[boneIndex];
  23607. }
  23608. }
  23609. }
  23610. return null;
  23611. };
  23612. /**
  23613. * get a bone using its id
  23614. * @param {string} the bone's name
  23615. * @return {BABYLON.Bone|null} the bone or null if not found
  23616. */
  23617. Scene.prototype.getBoneByName = function (name) {
  23618. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23619. var skeleton = this.skeletons[skeletonIndex];
  23620. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23621. if (skeleton.bones[boneIndex].name === name) {
  23622. return skeleton.bones[boneIndex];
  23623. }
  23624. }
  23625. }
  23626. return null;
  23627. };
  23628. /**
  23629. * get a light node using its name
  23630. * @param {string} the light's name
  23631. * @return {BABYLON.Light|null} the light or null if none found.
  23632. */
  23633. Scene.prototype.getLightByName = function (name) {
  23634. for (var index = 0; index < this.lights.length; index++) {
  23635. if (this.lights[index].name === name) {
  23636. return this.lights[index];
  23637. }
  23638. }
  23639. return null;
  23640. };
  23641. /**
  23642. * get a light node using its ID
  23643. * @param {string} the light's id
  23644. * @return {BABYLON.Light|null} the light or null if none found.
  23645. */
  23646. Scene.prototype.getLightByID = function (id) {
  23647. for (var index = 0; index < this.lights.length; index++) {
  23648. if (this.lights[index].id === id) {
  23649. return this.lights[index];
  23650. }
  23651. }
  23652. return null;
  23653. };
  23654. /**
  23655. * get a light node using its scene-generated unique ID
  23656. * @param {number} the light's unique id
  23657. * @return {BABYLON.Light|null} the light or null if none found.
  23658. */
  23659. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23660. for (var index = 0; index < this.lights.length; index++) {
  23661. if (this.lights[index].uniqueId === uniqueId) {
  23662. return this.lights[index];
  23663. }
  23664. }
  23665. return null;
  23666. };
  23667. /**
  23668. * get a particle system by id
  23669. * @param id {number} the particle system id
  23670. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23671. */
  23672. Scene.prototype.getParticleSystemByID = function (id) {
  23673. for (var index = 0; index < this.particleSystems.length; index++) {
  23674. if (this.particleSystems[index].id === id) {
  23675. return this.particleSystems[index];
  23676. }
  23677. }
  23678. return null;
  23679. };
  23680. /**
  23681. * get a geometry using its ID
  23682. * @param {string} the geometry's id
  23683. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23684. */
  23685. Scene.prototype.getGeometryByID = function (id) {
  23686. for (var index = 0; index < this._geometries.length; index++) {
  23687. if (this._geometries[index].id === id) {
  23688. return this._geometries[index];
  23689. }
  23690. }
  23691. return null;
  23692. };
  23693. /**
  23694. * add a new geometry to this scene.
  23695. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23696. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23697. * @return {boolean} was the geometry added or not
  23698. */
  23699. Scene.prototype.pushGeometry = function (geometry, force) {
  23700. if (!force && this.getGeometryByID(geometry.id)) {
  23701. return false;
  23702. }
  23703. this._geometries.push(geometry);
  23704. //notify the collision coordinator
  23705. if (this.collisionCoordinator) {
  23706. this.collisionCoordinator.onGeometryAdded(geometry);
  23707. }
  23708. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23709. return true;
  23710. };
  23711. /**
  23712. * Removes an existing geometry
  23713. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23714. * @return {boolean} was the geometry removed or not
  23715. */
  23716. Scene.prototype.removeGeometry = function (geometry) {
  23717. var index = this._geometries.indexOf(geometry);
  23718. if (index > -1) {
  23719. this._geometries.splice(index, 1);
  23720. //notify the collision coordinator
  23721. if (this.collisionCoordinator) {
  23722. this.collisionCoordinator.onGeometryDeleted(geometry);
  23723. }
  23724. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23725. return true;
  23726. }
  23727. return false;
  23728. };
  23729. Scene.prototype.getGeometries = function () {
  23730. return this._geometries;
  23731. };
  23732. /**
  23733. * Get the first added mesh found of a given ID
  23734. * @param {string} id - the id to search for
  23735. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23736. */
  23737. Scene.prototype.getMeshByID = function (id) {
  23738. for (var index = 0; index < this.meshes.length; index++) {
  23739. if (this.meshes[index].id === id) {
  23740. return this.meshes[index];
  23741. }
  23742. }
  23743. return null;
  23744. };
  23745. Scene.prototype.getMeshesByID = function (id) {
  23746. return this.meshes.filter(function (m) {
  23747. return m.id === id;
  23748. });
  23749. };
  23750. /**
  23751. * Get the first added transform node found of a given ID
  23752. * @param {string} id - the id to search for
  23753. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23754. */
  23755. Scene.prototype.getTransformNodeByID = function (id) {
  23756. for (var index = 0; index < this.transformNodes.length; index++) {
  23757. if (this.transformNodes[index].id === id) {
  23758. return this.transformNodes[index];
  23759. }
  23760. }
  23761. return null;
  23762. };
  23763. Scene.prototype.getTransformNodesByID = function (id) {
  23764. return this.transformNodes.filter(function (m) {
  23765. return m.id === id;
  23766. });
  23767. };
  23768. /**
  23769. * Get a mesh with its auto-generated unique id
  23770. * @param {number} uniqueId - the unique id to search for
  23771. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23772. */
  23773. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23774. for (var index = 0; index < this.meshes.length; index++) {
  23775. if (this.meshes[index].uniqueId === uniqueId) {
  23776. return this.meshes[index];
  23777. }
  23778. }
  23779. return null;
  23780. };
  23781. /**
  23782. * Get a the last added mesh found of a given ID
  23783. * @param {string} id - the id to search for
  23784. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23785. */
  23786. Scene.prototype.getLastMeshByID = function (id) {
  23787. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23788. if (this.meshes[index].id === id) {
  23789. return this.meshes[index];
  23790. }
  23791. }
  23792. return null;
  23793. };
  23794. /**
  23795. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23796. * @param {string} id - the id to search for
  23797. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23798. */
  23799. Scene.prototype.getLastEntryByID = function (id) {
  23800. var index;
  23801. for (index = this.meshes.length - 1; index >= 0; index--) {
  23802. if (this.meshes[index].id === id) {
  23803. return this.meshes[index];
  23804. }
  23805. }
  23806. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23807. if (this.transformNodes[index].id === id) {
  23808. return this.transformNodes[index];
  23809. }
  23810. }
  23811. for (index = this.cameras.length - 1; index >= 0; index--) {
  23812. if (this.cameras[index].id === id) {
  23813. return this.cameras[index];
  23814. }
  23815. }
  23816. for (index = this.lights.length - 1; index >= 0; index--) {
  23817. if (this.lights[index].id === id) {
  23818. return this.lights[index];
  23819. }
  23820. }
  23821. return null;
  23822. };
  23823. Scene.prototype.getNodeByID = function (id) {
  23824. var mesh = this.getMeshByID(id);
  23825. if (mesh) {
  23826. return mesh;
  23827. }
  23828. var light = this.getLightByID(id);
  23829. if (light) {
  23830. return light;
  23831. }
  23832. var camera = this.getCameraByID(id);
  23833. if (camera) {
  23834. return camera;
  23835. }
  23836. var bone = this.getBoneByID(id);
  23837. return bone;
  23838. };
  23839. Scene.prototype.getNodeByName = function (name) {
  23840. var mesh = this.getMeshByName(name);
  23841. if (mesh) {
  23842. return mesh;
  23843. }
  23844. var light = this.getLightByName(name);
  23845. if (light) {
  23846. return light;
  23847. }
  23848. var camera = this.getCameraByName(name);
  23849. if (camera) {
  23850. return camera;
  23851. }
  23852. var bone = this.getBoneByName(name);
  23853. return bone;
  23854. };
  23855. Scene.prototype.getMeshByName = function (name) {
  23856. for (var index = 0; index < this.meshes.length; index++) {
  23857. if (this.meshes[index].name === name) {
  23858. return this.meshes[index];
  23859. }
  23860. }
  23861. return null;
  23862. };
  23863. Scene.prototype.getTransformNodeByName = function (name) {
  23864. for (var index = 0; index < this.transformNodes.length; index++) {
  23865. if (this.transformNodes[index].name === name) {
  23866. return this.transformNodes[index];
  23867. }
  23868. }
  23869. return null;
  23870. };
  23871. Scene.prototype.getSoundByName = function (name) {
  23872. var index;
  23873. if (BABYLON.AudioEngine) {
  23874. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23875. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23876. return this.mainSoundTrack.soundCollection[index];
  23877. }
  23878. }
  23879. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23880. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23881. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23882. return this.soundTracks[sdIndex].soundCollection[index];
  23883. }
  23884. }
  23885. }
  23886. }
  23887. return null;
  23888. };
  23889. Scene.prototype.getLastSkeletonByID = function (id) {
  23890. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23891. if (this.skeletons[index].id === id) {
  23892. return this.skeletons[index];
  23893. }
  23894. }
  23895. return null;
  23896. };
  23897. Scene.prototype.getSkeletonById = function (id) {
  23898. for (var index = 0; index < this.skeletons.length; index++) {
  23899. if (this.skeletons[index].id === id) {
  23900. return this.skeletons[index];
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. Scene.prototype.getSkeletonByName = function (name) {
  23906. for (var index = 0; index < this.skeletons.length; index++) {
  23907. if (this.skeletons[index].name === name) {
  23908. return this.skeletons[index];
  23909. }
  23910. }
  23911. return null;
  23912. };
  23913. Scene.prototype.getMorphTargetManagerById = function (id) {
  23914. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23915. if (this.morphTargetManagers[index].uniqueId === id) {
  23916. return this.morphTargetManagers[index];
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. Scene.prototype.isActiveMesh = function (mesh) {
  23922. return (this._activeMeshes.indexOf(mesh) !== -1);
  23923. };
  23924. /**
  23925. * Return a the first highlight layer of the scene with a given name.
  23926. * @param name The name of the highlight layer to look for.
  23927. * @return The highlight layer if found otherwise null.
  23928. */
  23929. Scene.prototype.getHighlightLayerByName = function (name) {
  23930. for (var index = 0; index < this.effectLayers.length; index++) {
  23931. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23932. return this.effectLayers[index];
  23933. }
  23934. }
  23935. return null;
  23936. };
  23937. /**
  23938. * Return a the first highlight layer of the scene with a given name.
  23939. * @param name The name of the highlight layer to look for.
  23940. * @return The highlight layer if found otherwise null.
  23941. */
  23942. Scene.prototype.getGlowLayerByName = function (name) {
  23943. for (var index = 0; index < this.effectLayers.length; index++) {
  23944. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23945. return this.effectLayers[index];
  23946. }
  23947. }
  23948. return null;
  23949. };
  23950. Object.defineProperty(Scene.prototype, "uid", {
  23951. /**
  23952. * Return a unique id as a string which can serve as an identifier for the scene
  23953. */
  23954. get: function () {
  23955. if (!this._uid) {
  23956. this._uid = BABYLON.Tools.RandomId();
  23957. }
  23958. return this._uid;
  23959. },
  23960. enumerable: true,
  23961. configurable: true
  23962. });
  23963. /**
  23964. * Add an externaly attached data from its key.
  23965. * This method call will fail and return false, if such key already exists.
  23966. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23967. * @param key the unique key that identifies the data
  23968. * @param data the data object to associate to the key for this Engine instance
  23969. * @return true if no such key were already present and the data was added successfully, false otherwise
  23970. */
  23971. Scene.prototype.addExternalData = function (key, data) {
  23972. if (!this._externalData) {
  23973. this._externalData = new BABYLON.StringDictionary();
  23974. }
  23975. return this._externalData.add(key, data);
  23976. };
  23977. /**
  23978. * Get an externaly attached data from its key
  23979. * @param key the unique key that identifies the data
  23980. * @return the associated data, if present (can be null), or undefined if not present
  23981. */
  23982. Scene.prototype.getExternalData = function (key) {
  23983. if (!this._externalData) {
  23984. return null;
  23985. }
  23986. return this._externalData.get(key);
  23987. };
  23988. /**
  23989. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23990. * @param key the unique key that identifies the data
  23991. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23992. * @return the associated data, can be null if the factory returned null.
  23993. */
  23994. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23995. if (!this._externalData) {
  23996. this._externalData = new BABYLON.StringDictionary();
  23997. }
  23998. return this._externalData.getOrAddWithFactory(key, factory);
  23999. };
  24000. /**
  24001. * Remove an externaly attached data from the Engine instance
  24002. * @param key the unique key that identifies the data
  24003. * @return true if the data was successfully removed, false if it doesn't exist
  24004. */
  24005. Scene.prototype.removeExternalData = function (key) {
  24006. return this._externalData.remove(key);
  24007. };
  24008. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24009. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24010. if (mesh.showSubMeshesBoundingBox) {
  24011. var boundingInfo = subMesh.getBoundingInfo();
  24012. if (boundingInfo !== null && boundingInfo !== undefined) {
  24013. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24014. }
  24015. }
  24016. var material = subMesh.getMaterial();
  24017. if (material !== null && material !== undefined) {
  24018. // Render targets
  24019. if (material.getRenderTargetTextures !== undefined) {
  24020. if (this._processedMaterials.indexOf(material) === -1) {
  24021. this._processedMaterials.push(material);
  24022. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24023. }
  24024. }
  24025. // Dispatch
  24026. this._activeIndices.addCount(subMesh.indexCount, false);
  24027. this._renderingManager.dispatch(subMesh, mesh, material);
  24028. }
  24029. }
  24030. };
  24031. /**
  24032. * Clear the processed materials smart array preventing retention point in material dispose.
  24033. */
  24034. Scene.prototype.freeProcessedMaterials = function () {
  24035. this._processedMaterials.dispose();
  24036. };
  24037. /**
  24038. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24039. */
  24040. Scene.prototype.freeActiveMeshes = function () {
  24041. this._activeMeshes.dispose();
  24042. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24043. this.activeCamera._activeMeshes.dispose();
  24044. }
  24045. if (this.activeCameras) {
  24046. for (var i = 0; i < this.activeCameras.length; i++) {
  24047. var activeCamera = this.activeCameras[i];
  24048. if (activeCamera && activeCamera._activeMeshes) {
  24049. activeCamera._activeMeshes.dispose();
  24050. }
  24051. }
  24052. }
  24053. };
  24054. /**
  24055. * Clear the info related to rendering groups preventing retention points during dispose.
  24056. */
  24057. Scene.prototype.freeRenderingGroups = function () {
  24058. if (this._renderingManager) {
  24059. this._renderingManager.freeRenderingGroups();
  24060. }
  24061. if (this.textures) {
  24062. for (var i = 0; i < this.textures.length; i++) {
  24063. var texture = this.textures[i];
  24064. if (texture && texture.isRenderTarget) {
  24065. texture.freeRenderingGroups();
  24066. }
  24067. }
  24068. }
  24069. };
  24070. Scene.prototype._isInIntermediateRendering = function () {
  24071. return this._intermediateRendering;
  24072. };
  24073. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24074. this._activeMeshCandidateProvider = provider;
  24075. };
  24076. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24077. return this._activeMeshCandidateProvider;
  24078. };
  24079. /**
  24080. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24081. */
  24082. Scene.prototype.freezeActiveMeshes = function () {
  24083. this._evaluateActiveMeshes();
  24084. this._activeMeshesFrozen = true;
  24085. return this;
  24086. };
  24087. /**
  24088. * Use this function to restart evaluating active meshes on every frame
  24089. */
  24090. Scene.prototype.unfreezeActiveMeshes = function () {
  24091. this._activeMeshesFrozen = false;
  24092. return this;
  24093. };
  24094. Scene.prototype._evaluateActiveMeshes = function () {
  24095. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24096. return;
  24097. }
  24098. if (!this.activeCamera) {
  24099. return;
  24100. }
  24101. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24102. this.activeCamera._activeMeshes.reset();
  24103. this._activeMeshes.reset();
  24104. this._renderingManager.reset();
  24105. this._processedMaterials.reset();
  24106. this._activeParticleSystems.reset();
  24107. this._activeSkeletons.reset();
  24108. this._softwareSkinnedMeshes.reset();
  24109. if (this._boundingBoxRenderer) {
  24110. this._boundingBoxRenderer.reset();
  24111. }
  24112. // Meshes
  24113. var meshes;
  24114. var len;
  24115. var checkIsEnabled = true;
  24116. // Determine mesh candidates
  24117. if (this._activeMeshCandidateProvider !== undefined) {
  24118. // Use _activeMeshCandidateProvider
  24119. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24120. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24121. if (meshes !== undefined) {
  24122. len = meshes.length;
  24123. }
  24124. else {
  24125. len = 0;
  24126. }
  24127. }
  24128. else if (this._selectionOctree !== undefined) {
  24129. // Octree
  24130. var selection = this._selectionOctree.select(this._frustumPlanes);
  24131. meshes = selection.data;
  24132. len = selection.length;
  24133. }
  24134. else {
  24135. // Full scene traversal
  24136. len = this.meshes.length;
  24137. meshes = this.meshes;
  24138. }
  24139. // Check each mesh
  24140. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24141. mesh = meshes[meshIndex];
  24142. if (mesh.isBlocked) {
  24143. continue;
  24144. }
  24145. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24146. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24147. continue;
  24148. }
  24149. mesh.computeWorldMatrix();
  24150. // Intersections
  24151. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24152. this._meshesForIntersections.pushNoDuplicate(mesh);
  24153. }
  24154. // Switch to current LOD
  24155. meshLOD = mesh.getLOD(this.activeCamera);
  24156. if (meshLOD === undefined || meshLOD === null) {
  24157. continue;
  24158. }
  24159. mesh._preActivate();
  24160. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24161. this._activeMeshes.push(mesh);
  24162. this.activeCamera._activeMeshes.push(mesh);
  24163. mesh._activate(this._renderId);
  24164. if (meshLOD !== mesh) {
  24165. meshLOD._activate(this._renderId);
  24166. }
  24167. this._activeMesh(mesh, meshLOD);
  24168. }
  24169. }
  24170. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24171. // Particle systems
  24172. if (this.particlesEnabled) {
  24173. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24174. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24175. var particleSystem = this.particleSystems[particleIndex];
  24176. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24177. continue;
  24178. }
  24179. var emitter = particleSystem.emitter;
  24180. if (!emitter.position || emitter.isEnabled()) {
  24181. this._activeParticleSystems.push(particleSystem);
  24182. particleSystem.animate();
  24183. this._renderingManager.dispatchParticles(particleSystem);
  24184. }
  24185. }
  24186. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24187. }
  24188. };
  24189. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24190. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24191. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24192. mesh.skeleton.prepare();
  24193. }
  24194. if (!mesh.computeBonesUsingShaders) {
  24195. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24196. }
  24197. }
  24198. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24199. var boundingInfo = sourceMesh.getBoundingInfo();
  24200. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24201. }
  24202. if (mesh !== undefined && mesh !== null
  24203. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24204. // Submeshes Octrees
  24205. var len;
  24206. var subMeshes;
  24207. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24208. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24209. len = intersections.length;
  24210. subMeshes = intersections.data;
  24211. }
  24212. else {
  24213. subMeshes = mesh.subMeshes;
  24214. len = subMeshes.length;
  24215. }
  24216. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24217. subMesh = subMeshes[subIndex];
  24218. this._evaluateSubMesh(subMesh, mesh);
  24219. }
  24220. }
  24221. };
  24222. Scene.prototype.updateTransformMatrix = function (force) {
  24223. if (!this.activeCamera) {
  24224. return;
  24225. }
  24226. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24227. };
  24228. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24229. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24230. };
  24231. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24232. if (camera && camera._skipRendering) {
  24233. return;
  24234. }
  24235. var engine = this._engine;
  24236. this.activeCamera = camera;
  24237. if (!this.activeCamera)
  24238. throw new Error("Active camera not set");
  24239. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24240. // Viewport
  24241. engine.setViewport(this.activeCamera.viewport);
  24242. // Camera
  24243. this.resetCachedMaterial();
  24244. this._renderId++;
  24245. this.updateTransformMatrix();
  24246. if (camera._alternateCamera) {
  24247. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24248. this._alternateRendering = true;
  24249. }
  24250. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24251. // Meshes
  24252. this._evaluateActiveMeshes();
  24253. // Software skinning
  24254. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24255. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24256. mesh.applySkeleton(mesh.skeleton);
  24257. }
  24258. // Render targets
  24259. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24260. var needsRestoreFrameBuffer = false;
  24261. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24262. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24263. }
  24264. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24265. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24266. }
  24267. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24268. this._intermediateRendering = true;
  24269. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24270. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24271. var renderTarget = this._renderTargets.data[renderIndex];
  24272. if (renderTarget._shouldRender()) {
  24273. this._renderId++;
  24274. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24275. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24276. }
  24277. }
  24278. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24279. this._intermediateRendering = false;
  24280. this._renderId++;
  24281. needsRestoreFrameBuffer = true; // Restore back buffer
  24282. }
  24283. // Render EffecttLayer Texture
  24284. var stencilState = this._engine.getStencilBuffer();
  24285. var renderEffects = false;
  24286. var needStencil = false;
  24287. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24288. this._intermediateRendering = true;
  24289. for (var i = 0; i < this.effectLayers.length; i++) {
  24290. var effectLayer = this.effectLayers[i];
  24291. if (effectLayer.shouldRender() &&
  24292. (!effectLayer.camera ||
  24293. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24294. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24295. renderEffects = true;
  24296. needStencil = needStencil || effectLayer.needStencil();
  24297. var renderTarget = effectLayer._mainTexture;
  24298. if (renderTarget._shouldRender()) {
  24299. this._renderId++;
  24300. renderTarget.render(false, false);
  24301. needsRestoreFrameBuffer = true;
  24302. }
  24303. }
  24304. }
  24305. this._intermediateRendering = false;
  24306. this._renderId++;
  24307. }
  24308. if (needsRestoreFrameBuffer) {
  24309. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24310. }
  24311. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24312. // Prepare Frame
  24313. this.postProcessManager._prepareFrame();
  24314. // Backgrounds
  24315. var layerIndex;
  24316. var layer;
  24317. if (this.layers.length) {
  24318. engine.setDepthBuffer(false);
  24319. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24320. layer = this.layers[layerIndex];
  24321. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24322. layer.render();
  24323. }
  24324. }
  24325. engine.setDepthBuffer(true);
  24326. }
  24327. // Activate effect Layer stencil
  24328. if (needStencil) {
  24329. this._engine.setStencilBuffer(true);
  24330. }
  24331. // Render
  24332. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24333. this._renderingManager.render(null, null, true, true);
  24334. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24335. // Restore effect Layer stencil
  24336. if (needStencil) {
  24337. this._engine.setStencilBuffer(stencilState);
  24338. }
  24339. // Bounding boxes
  24340. if (this._boundingBoxRenderer) {
  24341. this._boundingBoxRenderer.render();
  24342. }
  24343. // Lens flares
  24344. if (this.lensFlaresEnabled) {
  24345. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24346. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24347. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24348. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24349. lensFlareSystem.render();
  24350. }
  24351. }
  24352. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24353. }
  24354. // Foregrounds
  24355. if (this.layers.length) {
  24356. engine.setDepthBuffer(false);
  24357. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24358. layer = this.layers[layerIndex];
  24359. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24360. layer.render();
  24361. }
  24362. }
  24363. engine.setDepthBuffer(true);
  24364. }
  24365. // Effect Layer
  24366. if (renderEffects) {
  24367. engine.setDepthBuffer(false);
  24368. for (var i = 0; i < this.effectLayers.length; i++) {
  24369. if (this.effectLayers[i].shouldRender()) {
  24370. this.effectLayers[i].render();
  24371. }
  24372. }
  24373. engine.setDepthBuffer(true);
  24374. }
  24375. // Finalize frame
  24376. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24377. // Reset some special arrays
  24378. this._renderTargets.reset();
  24379. this._alternateRendering = false;
  24380. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24381. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24382. };
  24383. Scene.prototype._processSubCameras = function (camera) {
  24384. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24385. this._renderForCamera(camera);
  24386. return;
  24387. }
  24388. // rig cameras
  24389. for (var index = 0; index < camera._rigCameras.length; index++) {
  24390. this._renderForCamera(camera._rigCameras[index], camera);
  24391. }
  24392. this.activeCamera = camera;
  24393. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24394. };
  24395. Scene.prototype._checkIntersections = function () {
  24396. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24397. var sourceMesh = this._meshesForIntersections.data[index];
  24398. if (!sourceMesh.actionManager) {
  24399. continue;
  24400. }
  24401. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24402. var action = sourceMesh.actionManager.actions[actionIndex];
  24403. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24404. var parameters = action.getTriggerParameter();
  24405. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24406. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24407. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24408. if (areIntersecting && currentIntersectionInProgress === -1) {
  24409. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24410. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24411. sourceMesh._intersectionsInProgress.push(otherMesh);
  24412. }
  24413. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24414. sourceMesh._intersectionsInProgress.push(otherMesh);
  24415. }
  24416. }
  24417. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24418. //They intersected, and now they don't.
  24419. //is this trigger an exit trigger? execute an event.
  24420. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24421. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24422. }
  24423. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24424. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24425. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24426. }
  24427. }
  24428. }
  24429. }
  24430. }
  24431. };
  24432. Scene.prototype.render = function () {
  24433. if (this.isDisposed) {
  24434. return;
  24435. }
  24436. this._activeParticles.fetchNewFrame();
  24437. this._totalVertices.fetchNewFrame();
  24438. this._activeIndices.fetchNewFrame();
  24439. this._activeBones.fetchNewFrame();
  24440. this._meshesForIntersections.reset();
  24441. this.resetCachedMaterial();
  24442. this.onBeforeAnimationsObservable.notifyObservers(this);
  24443. // Actions
  24444. if (this.actionManager) {
  24445. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24446. }
  24447. //Simplification Queue
  24448. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24449. this.simplificationQueue.executeNext();
  24450. }
  24451. if (this._engine.isDeterministicLockStep()) {
  24452. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24453. var defaultFPS = (60.0 / 1000.0);
  24454. var defaultFrameTime = 1000 / 60; // frame time in MS
  24455. if (this._physicsEngine) {
  24456. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24457. }
  24458. var stepsTaken = 0;
  24459. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24460. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24461. internalSteps = Math.min(internalSteps, maxSubSteps);
  24462. do {
  24463. this.onBeforeStepObservable.notifyObservers(this);
  24464. // Animations
  24465. this._animationRatio = defaultFrameTime * defaultFPS;
  24466. this._animate();
  24467. this.onAfterAnimationsObservable.notifyObservers(this);
  24468. // Physics
  24469. if (this._physicsEngine) {
  24470. this.onBeforePhysicsObservable.notifyObservers(this);
  24471. this._physicsEngine._step(defaultFrameTime / 1000);
  24472. this.onAfterPhysicsObservable.notifyObservers(this);
  24473. }
  24474. this.onAfterStepObservable.notifyObservers(this);
  24475. this._currentStepId++;
  24476. stepsTaken++;
  24477. deltaTime -= defaultFrameTime;
  24478. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24479. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24480. }
  24481. else {
  24482. // Animations
  24483. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24484. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24485. this._animate();
  24486. this.onAfterAnimationsObservable.notifyObservers(this);
  24487. // Physics
  24488. if (this._physicsEngine) {
  24489. this.onBeforePhysicsObservable.notifyObservers(this);
  24490. this._physicsEngine._step(deltaTime / 1000.0);
  24491. this.onAfterPhysicsObservable.notifyObservers(this);
  24492. }
  24493. }
  24494. // update gamepad manager
  24495. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24496. this._gamepadManager._checkGamepadsStatus();
  24497. }
  24498. // Update Cameras
  24499. if (this.activeCameras.length > 0) {
  24500. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24501. var camera = this.activeCameras[cameraIndex];
  24502. camera.update();
  24503. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24504. // rig cameras
  24505. for (var index = 0; index < camera._rigCameras.length; index++) {
  24506. camera._rigCameras[index].update();
  24507. }
  24508. }
  24509. }
  24510. }
  24511. else if (this.activeCamera) {
  24512. this.activeCamera.update();
  24513. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24514. // rig cameras
  24515. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24516. this.activeCamera._rigCameras[index].update();
  24517. }
  24518. }
  24519. }
  24520. // Before render
  24521. this.onBeforeRenderObservable.notifyObservers(this);
  24522. // Customs render targets
  24523. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24524. var engine = this.getEngine();
  24525. var currentActiveCamera = this.activeCamera;
  24526. if (this.renderTargetsEnabled) {
  24527. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24528. this._intermediateRendering = true;
  24529. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24530. var renderTarget = this.customRenderTargets[customIndex];
  24531. if (renderTarget._shouldRender()) {
  24532. this._renderId++;
  24533. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24534. if (!this.activeCamera)
  24535. throw new Error("Active camera not set");
  24536. // Viewport
  24537. engine.setViewport(this.activeCamera.viewport);
  24538. // Camera
  24539. this.updateTransformMatrix();
  24540. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24541. }
  24542. }
  24543. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24544. this._intermediateRendering = false;
  24545. this._renderId++;
  24546. }
  24547. // Restore back buffer
  24548. if (this.customRenderTargets.length > 0) {
  24549. engine.restoreDefaultFramebuffer();
  24550. }
  24551. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24552. this.activeCamera = currentActiveCamera;
  24553. // Procedural textures
  24554. if (this.proceduralTexturesEnabled) {
  24555. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24556. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24557. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24558. if (proceduralTexture._shouldRender()) {
  24559. proceduralTexture.render();
  24560. }
  24561. }
  24562. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24563. }
  24564. // Clear
  24565. if (this.autoClearDepthAndStencil || this.autoClear) {
  24566. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24567. }
  24568. // Shadows
  24569. if (this.shadowsEnabled) {
  24570. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24571. var light = this.lights[lightIndex];
  24572. var shadowGenerator = light.getShadowGenerator();
  24573. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24574. var shadowMap = (shadowGenerator.getShadowMap());
  24575. if (this.textures.indexOf(shadowMap) !== -1) {
  24576. this._renderTargets.push(shadowMap);
  24577. }
  24578. }
  24579. }
  24580. }
  24581. // Depth renderer
  24582. for (var key in this._depthRenderer) {
  24583. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24584. }
  24585. // Geometry renderer
  24586. if (this._geometryBufferRenderer) {
  24587. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24588. }
  24589. // RenderPipeline
  24590. if (this._postProcessRenderPipelineManager) {
  24591. this._postProcessRenderPipelineManager.update();
  24592. }
  24593. // Multi-cameras?
  24594. if (this.activeCameras.length > 0) {
  24595. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24596. if (cameraIndex > 0) {
  24597. this._engine.clear(null, false, true, true);
  24598. }
  24599. this._processSubCameras(this.activeCameras[cameraIndex]);
  24600. }
  24601. }
  24602. else {
  24603. if (!this.activeCamera) {
  24604. throw new Error("No camera defined");
  24605. }
  24606. this._processSubCameras(this.activeCamera);
  24607. }
  24608. // Intersection checks
  24609. this._checkIntersections();
  24610. // Update the audio listener attached to the camera
  24611. if (BABYLON.AudioEngine) {
  24612. this._updateAudioParameters();
  24613. }
  24614. // After render
  24615. if (this.afterRender) {
  24616. this.afterRender();
  24617. }
  24618. this.onAfterRenderObservable.notifyObservers(this);
  24619. // Cleaning
  24620. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24621. var data = this._toBeDisposed.data[index];
  24622. if (data) {
  24623. data.dispose();
  24624. }
  24625. this._toBeDisposed[index] = null;
  24626. }
  24627. this._toBeDisposed.reset();
  24628. if (this.dumpNextRenderTargets) {
  24629. this.dumpNextRenderTargets = false;
  24630. }
  24631. this._activeBones.addCount(0, true);
  24632. this._activeIndices.addCount(0, true);
  24633. this._activeParticles.addCount(0, true);
  24634. };
  24635. Scene.prototype._updateAudioParameters = function () {
  24636. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24637. return;
  24638. }
  24639. var listeningCamera;
  24640. var audioEngine = BABYLON.Engine.audioEngine;
  24641. if (this.activeCameras.length > 0) {
  24642. listeningCamera = this.activeCameras[0];
  24643. }
  24644. else {
  24645. listeningCamera = this.activeCamera;
  24646. }
  24647. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24648. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24649. // for VR cameras
  24650. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24651. listeningCamera = listeningCamera.rigCameras[0];
  24652. }
  24653. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24654. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24655. cameraDirection.normalize();
  24656. // To avoid some errors on GearVR
  24657. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24658. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24659. }
  24660. var i;
  24661. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24662. var sound = this.mainSoundTrack.soundCollection[i];
  24663. if (sound.useCustomAttenuation) {
  24664. sound.updateDistanceFromListener();
  24665. }
  24666. }
  24667. for (i = 0; i < this.soundTracks.length; i++) {
  24668. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24669. sound = this.soundTracks[i].soundCollection[j];
  24670. if (sound.useCustomAttenuation) {
  24671. sound.updateDistanceFromListener();
  24672. }
  24673. }
  24674. }
  24675. }
  24676. };
  24677. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24678. // Audio
  24679. get: function () {
  24680. return this._audioEnabled;
  24681. },
  24682. set: function (value) {
  24683. this._audioEnabled = value;
  24684. if (BABYLON.AudioEngine) {
  24685. if (this._audioEnabled) {
  24686. this._enableAudio();
  24687. }
  24688. else {
  24689. this._disableAudio();
  24690. }
  24691. }
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Scene.prototype._disableAudio = function () {
  24697. var i;
  24698. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24699. this.mainSoundTrack.soundCollection[i].pause();
  24700. }
  24701. for (i = 0; i < this.soundTracks.length; i++) {
  24702. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24703. this.soundTracks[i].soundCollection[j].pause();
  24704. }
  24705. }
  24706. };
  24707. Scene.prototype._enableAudio = function () {
  24708. var i;
  24709. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24710. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24711. this.mainSoundTrack.soundCollection[i].play();
  24712. }
  24713. }
  24714. for (i = 0; i < this.soundTracks.length; i++) {
  24715. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24716. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24717. this.soundTracks[i].soundCollection[j].play();
  24718. }
  24719. }
  24720. }
  24721. };
  24722. Object.defineProperty(Scene.prototype, "headphone", {
  24723. get: function () {
  24724. return this._headphone;
  24725. },
  24726. set: function (value) {
  24727. this._headphone = value;
  24728. if (BABYLON.AudioEngine) {
  24729. if (this._headphone) {
  24730. this._switchAudioModeForHeadphones();
  24731. }
  24732. else {
  24733. this._switchAudioModeForNormalSpeakers();
  24734. }
  24735. }
  24736. },
  24737. enumerable: true,
  24738. configurable: true
  24739. });
  24740. Scene.prototype._switchAudioModeForHeadphones = function () {
  24741. this.mainSoundTrack.switchPanningModelToHRTF();
  24742. for (var i = 0; i < this.soundTracks.length; i++) {
  24743. this.soundTracks[i].switchPanningModelToHRTF();
  24744. }
  24745. };
  24746. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24747. this.mainSoundTrack.switchPanningModelToEqualPower();
  24748. for (var i = 0; i < this.soundTracks.length; i++) {
  24749. this.soundTracks[i].switchPanningModelToEqualPower();
  24750. }
  24751. };
  24752. /**
  24753. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24754. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24755. * @returns the created depth renderer
  24756. */
  24757. Scene.prototype.enableDepthRenderer = function (camera) {
  24758. camera = camera || this.activeCamera;
  24759. if (!camera) {
  24760. throw "No camera available to enable depth renderer";
  24761. }
  24762. if (!this._depthRenderer[camera.id]) {
  24763. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24764. }
  24765. return this._depthRenderer[camera.id];
  24766. };
  24767. /**
  24768. * Disables a depth renderer for a given camera
  24769. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24770. */
  24771. Scene.prototype.disableDepthRenderer = function (camera) {
  24772. camera = camera || this.activeCamera;
  24773. if (!camera || !this._depthRenderer[camera.id]) {
  24774. return;
  24775. }
  24776. this._depthRenderer[camera.id].dispose();
  24777. delete this._depthRenderer[camera.id];
  24778. };
  24779. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24780. if (ratio === void 0) { ratio = 1; }
  24781. if (this._geometryBufferRenderer) {
  24782. return this._geometryBufferRenderer;
  24783. }
  24784. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24785. if (!this._geometryBufferRenderer.isSupported) {
  24786. this._geometryBufferRenderer = null;
  24787. }
  24788. return this._geometryBufferRenderer;
  24789. };
  24790. Scene.prototype.disableGeometryBufferRenderer = function () {
  24791. if (!this._geometryBufferRenderer) {
  24792. return;
  24793. }
  24794. this._geometryBufferRenderer.dispose();
  24795. this._geometryBufferRenderer = null;
  24796. };
  24797. Scene.prototype.freezeMaterials = function () {
  24798. for (var i = 0; i < this.materials.length; i++) {
  24799. this.materials[i].freeze();
  24800. }
  24801. };
  24802. Scene.prototype.unfreezeMaterials = function () {
  24803. for (var i = 0; i < this.materials.length; i++) {
  24804. this.materials[i].unfreeze();
  24805. }
  24806. };
  24807. Scene.prototype.dispose = function () {
  24808. this.beforeRender = null;
  24809. this.afterRender = null;
  24810. this.skeletons = [];
  24811. this.morphTargetManagers = [];
  24812. this.importedMeshesFiles = new Array();
  24813. this.stopAllAnimations();
  24814. this.resetCachedMaterial();
  24815. for (var key in this._depthRenderer) {
  24816. this._depthRenderer[key].dispose();
  24817. }
  24818. if (this._gamepadManager) {
  24819. this._gamepadManager.dispose();
  24820. this._gamepadManager = null;
  24821. }
  24822. // Smart arrays
  24823. if (this.activeCamera) {
  24824. this.activeCamera._activeMeshes.dispose();
  24825. this.activeCamera = null;
  24826. }
  24827. this._activeMeshes.dispose();
  24828. this._renderingManager.dispose();
  24829. this._processedMaterials.dispose();
  24830. this._activeParticleSystems.dispose();
  24831. this._activeSkeletons.dispose();
  24832. this._softwareSkinnedMeshes.dispose();
  24833. this._renderTargets.dispose();
  24834. if (this._boundingBoxRenderer) {
  24835. this._boundingBoxRenderer.dispose();
  24836. }
  24837. this._meshesForIntersections.dispose();
  24838. this._toBeDisposed.dispose();
  24839. // Abort active requests
  24840. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24841. var request = _a[_i];
  24842. request.abort();
  24843. }
  24844. // Debug layer
  24845. if (this._debugLayer) {
  24846. this._debugLayer.hide();
  24847. }
  24848. // Events
  24849. this.onDisposeObservable.notifyObservers(this);
  24850. this.onDisposeObservable.clear();
  24851. this.onBeforeRenderObservable.clear();
  24852. this.onAfterRenderObservable.clear();
  24853. this.OnBeforeRenderTargetsRenderObservable.clear();
  24854. this.OnAfterRenderTargetsRenderObservable.clear();
  24855. this.onAfterStepObservable.clear();
  24856. this.onBeforeStepObservable.clear();
  24857. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24858. this.onAfterActiveMeshesEvaluationObservable.clear();
  24859. this.onBeforeParticlesRenderingObservable.clear();
  24860. this.onAfterParticlesRenderingObservable.clear();
  24861. this.onBeforeSpritesRenderingObservable.clear();
  24862. this.onAfterSpritesRenderingObservable.clear();
  24863. this.onBeforeDrawPhaseObservable.clear();
  24864. this.onAfterDrawPhaseObservable.clear();
  24865. this.onBeforePhysicsObservable.clear();
  24866. this.onAfterPhysicsObservable.clear();
  24867. this.onBeforeAnimationsObservable.clear();
  24868. this.onAfterAnimationsObservable.clear();
  24869. this.onDataLoadedObservable.clear();
  24870. this.detachControl();
  24871. // Release sounds & sounds tracks
  24872. if (BABYLON.AudioEngine) {
  24873. this.disposeSounds();
  24874. }
  24875. // VR Helper
  24876. if (this.VRHelper) {
  24877. this.VRHelper.dispose();
  24878. }
  24879. // Detach cameras
  24880. var canvas = this._engine.getRenderingCanvas();
  24881. if (canvas) {
  24882. var index;
  24883. for (index = 0; index < this.cameras.length; index++) {
  24884. this.cameras[index].detachControl(canvas);
  24885. }
  24886. }
  24887. // Release animation groups
  24888. while (this.animationGroups.length) {
  24889. this.animationGroups[0].dispose();
  24890. }
  24891. // Release lights
  24892. while (this.lights.length) {
  24893. this.lights[0].dispose();
  24894. }
  24895. // Release meshes
  24896. while (this.meshes.length) {
  24897. this.meshes[0].dispose(true);
  24898. }
  24899. while (this.transformNodes.length) {
  24900. this.removeTransformNode(this.transformNodes[0]);
  24901. }
  24902. // Release cameras
  24903. while (this.cameras.length) {
  24904. this.cameras[0].dispose();
  24905. }
  24906. // Release materials
  24907. if (this.defaultMaterial) {
  24908. this.defaultMaterial.dispose();
  24909. }
  24910. while (this.multiMaterials.length) {
  24911. this.multiMaterials[0].dispose();
  24912. }
  24913. while (this.materials.length) {
  24914. this.materials[0].dispose();
  24915. }
  24916. // Release particles
  24917. while (this.particleSystems.length) {
  24918. this.particleSystems[0].dispose();
  24919. }
  24920. // Release sprites
  24921. while (this.spriteManagers.length) {
  24922. this.spriteManagers[0].dispose();
  24923. }
  24924. // Release postProcesses
  24925. while (this.postProcesses.length) {
  24926. this.postProcesses[0].dispose();
  24927. }
  24928. // Release layers
  24929. while (this.layers.length) {
  24930. this.layers[0].dispose();
  24931. }
  24932. while (this.effectLayers.length) {
  24933. this.effectLayers[0].dispose();
  24934. }
  24935. // Release textures
  24936. while (this.textures.length) {
  24937. this.textures[0].dispose();
  24938. }
  24939. // Release UBO
  24940. this._sceneUbo.dispose();
  24941. if (this._alternateSceneUbo) {
  24942. this._alternateSceneUbo.dispose();
  24943. }
  24944. // Post-processes
  24945. this.postProcessManager.dispose();
  24946. if (this._postProcessRenderPipelineManager) {
  24947. this._postProcessRenderPipelineManager.dispose();
  24948. }
  24949. // Physics
  24950. if (this._physicsEngine) {
  24951. this.disablePhysicsEngine();
  24952. }
  24953. // Remove from engine
  24954. index = this._engine.scenes.indexOf(this);
  24955. if (index > -1) {
  24956. this._engine.scenes.splice(index, 1);
  24957. }
  24958. this._engine.wipeCaches(true);
  24959. this._isDisposed = true;
  24960. };
  24961. Object.defineProperty(Scene.prototype, "isDisposed", {
  24962. get: function () {
  24963. return this._isDisposed;
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. // Release sounds & sounds tracks
  24969. Scene.prototype.disposeSounds = function () {
  24970. if (!this._mainSoundTrack) {
  24971. return;
  24972. }
  24973. this.mainSoundTrack.dispose();
  24974. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24975. this.soundTracks[scIndex].dispose();
  24976. }
  24977. };
  24978. // Octrees
  24979. /**
  24980. * Get the world extend vectors with an optional filter
  24981. *
  24982. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24983. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24984. */
  24985. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24986. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24987. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24988. filterPredicate = filterPredicate || (function () { return true; });
  24989. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24990. mesh.computeWorldMatrix(true);
  24991. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24992. return;
  24993. }
  24994. var boundingInfo = mesh.getBoundingInfo();
  24995. var minBox = boundingInfo.boundingBox.minimumWorld;
  24996. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24997. BABYLON.Tools.CheckExtends(minBox, min, max);
  24998. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24999. });
  25000. return {
  25001. min: min,
  25002. max: max
  25003. };
  25004. };
  25005. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25006. if (maxCapacity === void 0) { maxCapacity = 64; }
  25007. if (maxDepth === void 0) { maxDepth = 2; }
  25008. if (!this._selectionOctree) {
  25009. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25010. }
  25011. var worldExtends = this.getWorldExtends();
  25012. // Update octree
  25013. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25014. return this._selectionOctree;
  25015. };
  25016. // Picking
  25017. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25018. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25019. var result = BABYLON.Ray.Zero();
  25020. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25021. return result;
  25022. };
  25023. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25024. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25025. var engine = this._engine;
  25026. if (!camera) {
  25027. if (!this.activeCamera)
  25028. throw new Error("Active camera not set");
  25029. camera = this.activeCamera;
  25030. }
  25031. var cameraViewport = camera.viewport;
  25032. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25033. // Moving coordinates to local viewport world
  25034. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25035. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25036. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25037. return this;
  25038. };
  25039. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25040. var result = BABYLON.Ray.Zero();
  25041. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25042. return result;
  25043. };
  25044. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25045. if (!BABYLON.PickingInfo) {
  25046. return this;
  25047. }
  25048. var engine = this._engine;
  25049. if (!camera) {
  25050. if (!this.activeCamera)
  25051. throw new Error("Active camera not set");
  25052. camera = this.activeCamera;
  25053. }
  25054. var cameraViewport = camera.viewport;
  25055. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25056. var identity = BABYLON.Matrix.Identity();
  25057. // Moving coordinates to local viewport world
  25058. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25059. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25060. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25061. return this;
  25062. };
  25063. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25064. if (!BABYLON.PickingInfo) {
  25065. return null;
  25066. }
  25067. var pickingInfo = null;
  25068. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25069. var mesh = this.meshes[meshIndex];
  25070. if (predicate) {
  25071. if (!predicate(mesh)) {
  25072. continue;
  25073. }
  25074. }
  25075. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25076. continue;
  25077. }
  25078. var world = mesh.getWorldMatrix();
  25079. var ray = rayFunction(world);
  25080. var result = mesh.intersects(ray, fastCheck);
  25081. if (!result || !result.hit)
  25082. continue;
  25083. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25084. continue;
  25085. pickingInfo = result;
  25086. if (fastCheck) {
  25087. break;
  25088. }
  25089. }
  25090. return pickingInfo || new BABYLON.PickingInfo();
  25091. };
  25092. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25093. if (!BABYLON.PickingInfo) {
  25094. return null;
  25095. }
  25096. var pickingInfos = new Array();
  25097. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25098. var mesh = this.meshes[meshIndex];
  25099. if (predicate) {
  25100. if (!predicate(mesh)) {
  25101. continue;
  25102. }
  25103. }
  25104. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25105. continue;
  25106. }
  25107. var world = mesh.getWorldMatrix();
  25108. var ray = rayFunction(world);
  25109. var result = mesh.intersects(ray, false);
  25110. if (!result || !result.hit)
  25111. continue;
  25112. pickingInfos.push(result);
  25113. }
  25114. return pickingInfos;
  25115. };
  25116. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25117. if (!BABYLON.PickingInfo) {
  25118. return null;
  25119. }
  25120. var pickingInfo = null;
  25121. if (!camera) {
  25122. if (!this.activeCamera) {
  25123. return null;
  25124. }
  25125. camera = this.activeCamera;
  25126. }
  25127. if (this.spriteManagers.length > 0) {
  25128. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25129. var spriteManager = this.spriteManagers[spriteIndex];
  25130. if (!spriteManager.isPickable) {
  25131. continue;
  25132. }
  25133. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25134. if (!result || !result.hit)
  25135. continue;
  25136. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25137. continue;
  25138. pickingInfo = result;
  25139. if (fastCheck) {
  25140. break;
  25141. }
  25142. }
  25143. }
  25144. return pickingInfo || new BABYLON.PickingInfo();
  25145. };
  25146. /** Launch a ray to try to pick a mesh in the scene
  25147. * @param x position on screen
  25148. * @param y position on screen
  25149. * @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
  25150. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25151. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25152. */
  25153. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25154. var _this = this;
  25155. if (!BABYLON.PickingInfo) {
  25156. return null;
  25157. }
  25158. return this._internalPick(function (world) {
  25159. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25160. return _this._tempPickingRay;
  25161. }, predicate, fastCheck);
  25162. };
  25163. /** Launch a ray to try to pick a sprite in the scene
  25164. * @param x position on screen
  25165. * @param y position on screen
  25166. * @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
  25167. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25168. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25169. */
  25170. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25171. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25172. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25173. };
  25174. /** Use the given ray to pick a mesh in the scene
  25175. * @param ray The ray to use to pick meshes
  25176. * @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
  25177. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25178. */
  25179. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25180. var _this = this;
  25181. return this._internalPick(function (world) {
  25182. if (!_this._pickWithRayInverseMatrix) {
  25183. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25184. }
  25185. world.invertToRef(_this._pickWithRayInverseMatrix);
  25186. if (!_this._cachedRayForTransform) {
  25187. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25188. }
  25189. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25190. return _this._cachedRayForTransform;
  25191. }, predicate, fastCheck);
  25192. };
  25193. /**
  25194. * Launch a ray to try to pick a mesh in the scene
  25195. * @param x X position on screen
  25196. * @param y Y position on screen
  25197. * @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
  25198. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25199. */
  25200. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25201. var _this = this;
  25202. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25203. };
  25204. /**
  25205. * Launch a ray to try to pick a mesh in the scene
  25206. * @param ray Ray to use
  25207. * @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
  25208. */
  25209. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25210. var _this = this;
  25211. return this._internalMultiPick(function (world) {
  25212. if (!_this._pickWithRayInverseMatrix) {
  25213. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25214. }
  25215. world.invertToRef(_this._pickWithRayInverseMatrix);
  25216. if (!_this._cachedRayForTransform) {
  25217. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25218. }
  25219. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25220. return _this._cachedRayForTransform;
  25221. }, predicate);
  25222. };
  25223. Scene.prototype.setPointerOverMesh = function (mesh) {
  25224. if (this._pointerOverMesh === mesh) {
  25225. return;
  25226. }
  25227. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25228. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25229. }
  25230. this._pointerOverMesh = mesh;
  25231. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25232. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25233. }
  25234. };
  25235. Scene.prototype.getPointerOverMesh = function () {
  25236. return this._pointerOverMesh;
  25237. };
  25238. Scene.prototype.setPointerOverSprite = function (sprite) {
  25239. if (this._pointerOverSprite === sprite) {
  25240. return;
  25241. }
  25242. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25243. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25244. }
  25245. this._pointerOverSprite = sprite;
  25246. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25247. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25248. }
  25249. };
  25250. Scene.prototype.getPointerOverSprite = function () {
  25251. return this._pointerOverSprite;
  25252. };
  25253. // Physics
  25254. Scene.prototype.getPhysicsEngine = function () {
  25255. return this._physicsEngine;
  25256. };
  25257. /**
  25258. * Enables physics to the current scene
  25259. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25260. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25261. * @return {boolean} was the physics engine initialized
  25262. */
  25263. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25264. if (gravity === void 0) { gravity = null; }
  25265. if (this._physicsEngine) {
  25266. return true;
  25267. }
  25268. try {
  25269. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25270. return true;
  25271. }
  25272. catch (e) {
  25273. BABYLON.Tools.Error(e.message);
  25274. return false;
  25275. }
  25276. };
  25277. Scene.prototype.disablePhysicsEngine = function () {
  25278. if (!this._physicsEngine) {
  25279. return;
  25280. }
  25281. this._physicsEngine.dispose();
  25282. this._physicsEngine = null;
  25283. };
  25284. Scene.prototype.isPhysicsEnabled = function () {
  25285. return this._physicsEngine !== undefined;
  25286. };
  25287. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25288. var mesh = compound.parts[0].mesh;
  25289. if (mesh.physicsImpostor) {
  25290. mesh.physicsImpostor.dispose();
  25291. mesh.physicsImpostor = null;
  25292. }
  25293. };
  25294. // Misc.
  25295. Scene.prototype._rebuildGeometries = function () {
  25296. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25297. var geometry = _a[_i];
  25298. geometry._rebuild();
  25299. }
  25300. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25301. var mesh = _c[_b];
  25302. mesh._rebuild();
  25303. }
  25304. if (this.postProcessManager) {
  25305. this.postProcessManager._rebuild();
  25306. }
  25307. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25308. var layer = _e[_d];
  25309. layer._rebuild();
  25310. }
  25311. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25312. var effectLayer = _g[_f];
  25313. effectLayer._rebuild();
  25314. }
  25315. if (this._boundingBoxRenderer) {
  25316. this._boundingBoxRenderer._rebuild();
  25317. }
  25318. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25319. var system = _j[_h];
  25320. system.rebuild();
  25321. }
  25322. if (this._postProcessRenderPipelineManager) {
  25323. this._postProcessRenderPipelineManager._rebuild();
  25324. }
  25325. };
  25326. Scene.prototype._rebuildTextures = function () {
  25327. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25328. var texture = _a[_i];
  25329. texture._rebuild();
  25330. }
  25331. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25332. };
  25333. /**
  25334. * Creates a default light for the scene.
  25335. * @param replace Whether to replace the existing lights in the scene.
  25336. */
  25337. Scene.prototype.createDefaultLight = function (replace) {
  25338. if (replace === void 0) { replace = false; }
  25339. // Dispose existing light in replace mode.
  25340. if (replace) {
  25341. if (this.lights) {
  25342. for (var i = 0; i < this.lights.length; i++) {
  25343. this.lights[i].dispose();
  25344. }
  25345. }
  25346. }
  25347. // Light
  25348. if (this.lights.length === 0) {
  25349. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25350. }
  25351. };
  25352. /**
  25353. * Creates a default camera for the scene.
  25354. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25355. * @param replace Whether to replace the existing active camera in the scene.
  25356. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25357. */
  25358. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25359. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25360. if (replace === void 0) { replace = false; }
  25361. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25362. // Dispose existing camera in replace mode.
  25363. if (replace) {
  25364. if (this.activeCamera) {
  25365. this.activeCamera.dispose();
  25366. this.activeCamera = null;
  25367. }
  25368. }
  25369. // Camera
  25370. if (!this.activeCamera) {
  25371. var worldExtends = this.getWorldExtends();
  25372. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25373. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25374. var camera;
  25375. var radius = worldSize.length() * 1.5;
  25376. // empty scene scenario!
  25377. if (!isFinite(radius)) {
  25378. radius = 1;
  25379. worldCenter.copyFromFloats(0, 0, 0);
  25380. }
  25381. if (createArcRotateCamera) {
  25382. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25383. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25384. arcRotateCamera.wheelPrecision = 100 / radius;
  25385. camera = arcRotateCamera;
  25386. }
  25387. else {
  25388. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25389. freeCamera.setTarget(worldCenter);
  25390. camera = freeCamera;
  25391. }
  25392. camera.minZ = radius * 0.01;
  25393. camera.maxZ = radius * 1000;
  25394. camera.speed = radius * 0.2;
  25395. this.activeCamera = camera;
  25396. var canvas = this.getEngine().getRenderingCanvas();
  25397. if (attachCameraControls && canvas) {
  25398. camera.attachControl(canvas);
  25399. }
  25400. }
  25401. };
  25402. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25403. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25404. if (replace === void 0) { replace = false; }
  25405. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25406. this.createDefaultLight(replace);
  25407. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25408. };
  25409. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25410. if (pbr === void 0) { pbr = false; }
  25411. if (scale === void 0) { scale = 1000; }
  25412. if (blur === void 0) { blur = 0; }
  25413. if (environmentTexture) {
  25414. this.environmentTexture = environmentTexture;
  25415. }
  25416. if (!this.environmentTexture) {
  25417. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25418. return null;
  25419. }
  25420. // Skybox
  25421. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25422. if (pbr) {
  25423. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25424. hdrSkyboxMaterial.backFaceCulling = false;
  25425. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25426. if (hdrSkyboxMaterial.reflectionTexture) {
  25427. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25428. }
  25429. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25430. hdrSkyboxMaterial.disableLighting = true;
  25431. hdrSkyboxMaterial.twoSidedLighting = true;
  25432. hdrSkybox.infiniteDistance = true;
  25433. hdrSkybox.material = hdrSkyboxMaterial;
  25434. }
  25435. else {
  25436. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25437. skyboxMaterial.backFaceCulling = false;
  25438. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25439. if (skyboxMaterial.reflectionTexture) {
  25440. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25441. }
  25442. skyboxMaterial.disableLighting = true;
  25443. hdrSkybox.infiniteDistance = true;
  25444. hdrSkybox.material = skyboxMaterial;
  25445. }
  25446. return hdrSkybox;
  25447. };
  25448. Scene.prototype.createDefaultEnvironment = function (options) {
  25449. if (BABYLON.EnvironmentHelper) {
  25450. return new BABYLON.EnvironmentHelper(options, this);
  25451. }
  25452. return null;
  25453. };
  25454. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25455. if (webVROptions === void 0) { webVROptions = {}; }
  25456. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25457. };
  25458. // Tags
  25459. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25460. if (tagsQuery === undefined) {
  25461. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25462. return list;
  25463. }
  25464. var listByTags = [];
  25465. forEach = forEach || (function (item) { return; });
  25466. for (var i in list) {
  25467. var item = list[i];
  25468. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25469. listByTags.push(item);
  25470. forEach(item);
  25471. }
  25472. }
  25473. return listByTags;
  25474. };
  25475. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25476. return this._getByTags(this.meshes, tagsQuery, forEach);
  25477. };
  25478. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25479. return this._getByTags(this.cameras, tagsQuery, forEach);
  25480. };
  25481. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25482. return this._getByTags(this.lights, tagsQuery, forEach);
  25483. };
  25484. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25485. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25486. };
  25487. /**
  25488. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25489. * This allowed control for front to back rendering or reversly depending of the special needs.
  25490. *
  25491. * @param renderingGroupId The rendering group id corresponding to its index
  25492. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25493. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25494. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25495. */
  25496. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25497. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25498. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25499. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25500. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25501. };
  25502. /**
  25503. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25504. *
  25505. * @param renderingGroupId The rendering group id corresponding to its index
  25506. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25507. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25508. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25509. */
  25510. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25511. if (depth === void 0) { depth = true; }
  25512. if (stencil === void 0) { stencil = true; }
  25513. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25514. };
  25515. /**
  25516. * Will flag all materials as dirty to trigger new shader compilation
  25517. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25518. */
  25519. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25520. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25521. var material = _a[_i];
  25522. if (predicate && !predicate(material)) {
  25523. continue;
  25524. }
  25525. material.markAsDirty(flag);
  25526. }
  25527. };
  25528. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25529. var _this = this;
  25530. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25531. this._activeRequests.push(request);
  25532. request.onCompleteObservable.add(function (request) {
  25533. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25534. });
  25535. return request;
  25536. };
  25537. /** @ignore */
  25538. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25539. var _this = this;
  25540. return new Promise(function (resolve, reject) {
  25541. _this._loadFile(url, function (data) {
  25542. resolve(data);
  25543. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25544. reject(exception);
  25545. });
  25546. });
  25547. };
  25548. // Statics
  25549. Scene._FOGMODE_NONE = 0;
  25550. Scene._FOGMODE_EXP = 1;
  25551. Scene._FOGMODE_EXP2 = 2;
  25552. Scene._FOGMODE_LINEAR = 3;
  25553. Scene._uniqueIdCounter = 0;
  25554. Scene.MinDeltaTime = 1.0;
  25555. Scene.MaxDeltaTime = 1000.0;
  25556. /** The distance in pixel that you have to move to prevent some events */
  25557. Scene.DragMovementThreshold = 10; // in pixels
  25558. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25559. Scene.LongPressDelay = 500; // in milliseconds
  25560. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25561. Scene.DoubleClickDelay = 300; // in milliseconds
  25562. /** If you need to check double click without raising a single click at first click, enable this flag */
  25563. Scene.ExclusiveDoubleClickMode = false;
  25564. return Scene;
  25565. }());
  25566. BABYLON.Scene = Scene;
  25567. })(BABYLON || (BABYLON = {}));
  25568. //# sourceMappingURL=babylon.scene.js.map
  25569. var BABYLON;
  25570. (function (BABYLON) {
  25571. /**
  25572. * Set of assets to keep when moving a scene into an asset container.
  25573. */
  25574. var KeepAssets = /** @class */ (function () {
  25575. function KeepAssets() {
  25576. /**
  25577. * Cameras to keep.
  25578. */
  25579. this.cameras = new Array();
  25580. /**
  25581. * Lights to keep.
  25582. */
  25583. this.lights = new Array();
  25584. /**
  25585. * Meshes to keep.
  25586. */
  25587. this.meshes = new Array();
  25588. /**
  25589. * Skeletons to keep.
  25590. */
  25591. this.skeletons = new Array();
  25592. /**
  25593. * ParticleSystems to keep.
  25594. */
  25595. this.particleSystems = new Array();
  25596. /**
  25597. * Animations to keep.
  25598. */
  25599. this.animations = new Array();
  25600. /**
  25601. * MultiMaterials to keep.
  25602. */
  25603. this.multiMaterials = new Array();
  25604. /**
  25605. * Materials to keep.
  25606. */
  25607. this.materials = new Array();
  25608. /**
  25609. * MorphTargetManagers to keep.
  25610. */
  25611. this.morphTargetManagers = new Array();
  25612. /**
  25613. * Geometries to keep.
  25614. */
  25615. this.geometries = new Array();
  25616. /**
  25617. * TransformNodes to keep.
  25618. */
  25619. this.transformNodes = new Array();
  25620. /**
  25621. * LensFlareSystems to keep.
  25622. */
  25623. this.lensFlareSystems = new Array();
  25624. /**
  25625. * ShadowGenerators to keep.
  25626. */
  25627. this.shadowGenerators = new Array();
  25628. /**
  25629. * ActionManagers to keep.
  25630. */
  25631. this.actionManagers = new Array();
  25632. /**
  25633. * Sounds to keep.
  25634. */
  25635. this.sounds = new Array();
  25636. }
  25637. return KeepAssets;
  25638. }());
  25639. BABYLON.KeepAssets = KeepAssets;
  25640. /**
  25641. * Container with a set of assets that can be added or removed from a scene.
  25642. */
  25643. var AssetContainer = /** @class */ (function () {
  25644. /**
  25645. * Instantiates an AssetContainer.
  25646. * @param scene The scene the AssetContainer belongs to.
  25647. */
  25648. function AssetContainer(scene) {
  25649. // Objects
  25650. /**
  25651. * Cameras populated in the container.
  25652. */
  25653. this.cameras = new Array();
  25654. /**
  25655. * Lights populated in the container.
  25656. */
  25657. this.lights = new Array();
  25658. /**
  25659. * Meshes populated in the container.
  25660. */
  25661. this.meshes = new Array();
  25662. /**
  25663. * Skeletons populated in the container.
  25664. */
  25665. this.skeletons = new Array();
  25666. /**
  25667. * ParticleSystems populated in the container.
  25668. */
  25669. this.particleSystems = new Array();
  25670. /**
  25671. * Animations populated in the container.
  25672. */
  25673. this.animations = new Array();
  25674. /**
  25675. * MultiMaterials populated in the container.
  25676. */
  25677. this.multiMaterials = new Array();
  25678. /**
  25679. * Materials populated in the container.
  25680. */
  25681. this.materials = new Array();
  25682. /**
  25683. * MorphTargetManagers populated in the container.
  25684. */
  25685. this.morphTargetManagers = new Array();
  25686. /**
  25687. * Geometries populated in the container.
  25688. */
  25689. this.geometries = new Array();
  25690. /**
  25691. * TransformNodes populated in the container.
  25692. */
  25693. this.transformNodes = new Array();
  25694. /**
  25695. * LensFlareSystems populated in the container.
  25696. */
  25697. this.lensFlareSystems = new Array();
  25698. /**
  25699. * ShadowGenerators populated in the container.
  25700. */
  25701. this.shadowGenerators = new Array();
  25702. /**
  25703. * ActionManagers populated in the container.
  25704. */
  25705. this.actionManagers = new Array();
  25706. /**
  25707. * Sounds populated in the container.
  25708. */
  25709. this.sounds = new Array();
  25710. this.scene = scene;
  25711. }
  25712. /**
  25713. * Adds all the assets from the container to the scene.
  25714. */
  25715. AssetContainer.prototype.addAllToScene = function () {
  25716. var _this = this;
  25717. this.cameras.forEach(function (o) {
  25718. _this.scene.addCamera(o);
  25719. });
  25720. this.lights.forEach(function (o) {
  25721. _this.scene.addLight(o);
  25722. });
  25723. this.meshes.forEach(function (o) {
  25724. _this.scene.addMesh(o);
  25725. });
  25726. this.skeletons.forEach(function (o) {
  25727. _this.scene.addSkeleton(o);
  25728. });
  25729. this.particleSystems.forEach(function (o) {
  25730. _this.scene.addParticleSystem(o);
  25731. });
  25732. this.animations.forEach(function (o) {
  25733. _this.scene.addAnimation(o);
  25734. });
  25735. this.multiMaterials.forEach(function (o) {
  25736. _this.scene.addMultiMaterial(o);
  25737. });
  25738. this.materials.forEach(function (o) {
  25739. _this.scene.addMaterial(o);
  25740. });
  25741. this.morphTargetManagers.forEach(function (o) {
  25742. _this.scene.addMorphTargetManager(o);
  25743. });
  25744. this.geometries.forEach(function (o) {
  25745. _this.scene.addGeometry(o);
  25746. });
  25747. this.transformNodes.forEach(function (o) {
  25748. _this.scene.addTransformNode(o);
  25749. });
  25750. this.lensFlareSystems.forEach(function (o) {
  25751. _this.scene.addLensFlareSystem(o);
  25752. });
  25753. this.actionManagers.forEach(function (o) {
  25754. _this.scene.addActionManager(o);
  25755. });
  25756. this.sounds.forEach(function (o) {
  25757. o.play();
  25758. o.autoplay = true;
  25759. _this.scene.mainSoundTrack.AddSound(o);
  25760. });
  25761. };
  25762. /**
  25763. * Removes all the assets in the container from the scene
  25764. */
  25765. AssetContainer.prototype.removeAllFromScene = function () {
  25766. var _this = this;
  25767. this.cameras.forEach(function (o) {
  25768. _this.scene.removeCamera(o);
  25769. });
  25770. this.lights.forEach(function (o) {
  25771. _this.scene.removeLight(o);
  25772. });
  25773. this.meshes.forEach(function (o) {
  25774. _this.scene.removeMesh(o);
  25775. });
  25776. this.skeletons.forEach(function (o) {
  25777. _this.scene.removeSkeleton(o);
  25778. });
  25779. this.particleSystems.forEach(function (o) {
  25780. _this.scene.removeParticleSystem(o);
  25781. });
  25782. this.animations.forEach(function (o) {
  25783. _this.scene.removeAnimation(o);
  25784. });
  25785. this.multiMaterials.forEach(function (o) {
  25786. _this.scene.removeMultiMaterial(o);
  25787. });
  25788. this.materials.forEach(function (o) {
  25789. _this.scene.removeMaterial(o);
  25790. });
  25791. this.morphTargetManagers.forEach(function (o) {
  25792. _this.scene.removeMorphTargetManager(o);
  25793. });
  25794. this.geometries.forEach(function (o) {
  25795. _this.scene.removeGeometry(o);
  25796. });
  25797. this.transformNodes.forEach(function (o) {
  25798. _this.scene.removeTransformNode(o);
  25799. });
  25800. this.lensFlareSystems.forEach(function (o) {
  25801. _this.scene.removeLensFlareSystem(o);
  25802. });
  25803. this.actionManagers.forEach(function (o) {
  25804. _this.scene.removeActionManager(o);
  25805. });
  25806. this.sounds.forEach(function (o) {
  25807. o.stop();
  25808. o.autoplay = false;
  25809. _this.scene.mainSoundTrack.RemoveSound(o);
  25810. });
  25811. };
  25812. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25813. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25814. var asset = sourceAssets_1[_i];
  25815. var move = true;
  25816. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25817. var keepAsset = keepAssets_1[_a];
  25818. if (asset === keepAsset) {
  25819. move = false;
  25820. break;
  25821. }
  25822. }
  25823. if (move) {
  25824. targetAssets.push(asset);
  25825. }
  25826. }
  25827. };
  25828. /**
  25829. * Removes all the assets contained in the scene and adds them to the container.
  25830. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25831. */
  25832. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25833. if (keepAssets === undefined) {
  25834. keepAssets = new KeepAssets();
  25835. }
  25836. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25837. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25838. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25839. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25840. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25841. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25842. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25843. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25844. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25845. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25846. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25847. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25848. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25849. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25850. this.removeAllFromScene();
  25851. };
  25852. return AssetContainer;
  25853. }());
  25854. BABYLON.AssetContainer = AssetContainer;
  25855. })(BABYLON || (BABYLON = {}));
  25856. //# sourceMappingURL=babylon.assetContainer.js.map
  25857. var BABYLON;
  25858. (function (BABYLON) {
  25859. var Buffer = /** @class */ (function () {
  25860. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25861. if (instanced === void 0) { instanced = false; }
  25862. if (engine instanceof BABYLON.Mesh) {
  25863. this._engine = engine.getScene().getEngine();
  25864. }
  25865. else {
  25866. this._engine = engine;
  25867. }
  25868. this._updatable = updatable;
  25869. this._instanced = instanced;
  25870. this._data = data;
  25871. this._strideSize = stride;
  25872. if (!postponeInternalCreation) {
  25873. this.create();
  25874. }
  25875. }
  25876. /**
  25877. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25878. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25879. * @param offset defines offset in the buffer (0 by default)
  25880. * @param size defines the size in floats of attributes (position is 3 for instance)
  25881. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25882. * @param instanced defines if the vertex buffer contains indexed data
  25883. * @returns the new vertex buffer
  25884. */
  25885. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25886. // a lot of these parameters are ignored as they are overriden by the buffer
  25887. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25888. };
  25889. // Properties
  25890. Buffer.prototype.isUpdatable = function () {
  25891. return this._updatable;
  25892. };
  25893. Buffer.prototype.getData = function () {
  25894. return this._data;
  25895. };
  25896. Buffer.prototype.getBuffer = function () {
  25897. return this._buffer;
  25898. };
  25899. Buffer.prototype.getStrideSize = function () {
  25900. return this._strideSize;
  25901. };
  25902. // public getIsInstanced(): boolean {
  25903. // return this._instanced;
  25904. // }
  25905. // public get instanceDivisor(): number {
  25906. // return this._instanceDivisor;
  25907. // }
  25908. // public set instanceDivisor(value: number) {
  25909. // this._instanceDivisor = value;
  25910. // if (value == 0) {
  25911. // this._instanced = false;
  25912. // } else {
  25913. // this._instanced = true;
  25914. // }
  25915. // }
  25916. // Methods
  25917. Buffer.prototype.create = function (data) {
  25918. if (data === void 0) { data = null; }
  25919. if (!data && this._buffer) {
  25920. return; // nothing to do
  25921. }
  25922. data = data || this._data;
  25923. if (!data) {
  25924. return;
  25925. }
  25926. if (!this._buffer) {
  25927. if (this._updatable) {
  25928. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25929. this._data = data;
  25930. }
  25931. else {
  25932. this._buffer = this._engine.createVertexBuffer(data);
  25933. }
  25934. }
  25935. else if (this._updatable) {
  25936. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25937. this._data = data;
  25938. }
  25939. };
  25940. Buffer.prototype._rebuild = function () {
  25941. this._buffer = null;
  25942. this.create(this._data);
  25943. };
  25944. Buffer.prototype.update = function (data) {
  25945. this.create(data);
  25946. };
  25947. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25948. if (!this._buffer) {
  25949. return;
  25950. }
  25951. if (this._updatable) {
  25952. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25953. this._data = null;
  25954. }
  25955. };
  25956. Buffer.prototype.dispose = function () {
  25957. if (!this._buffer) {
  25958. return;
  25959. }
  25960. if (this._engine._releaseBuffer(this._buffer)) {
  25961. this._buffer = null;
  25962. }
  25963. };
  25964. return Buffer;
  25965. }());
  25966. BABYLON.Buffer = Buffer;
  25967. })(BABYLON || (BABYLON = {}));
  25968. //# sourceMappingURL=babylon.buffer.js.map
  25969. var BABYLON;
  25970. (function (BABYLON) {
  25971. var VertexBuffer = /** @class */ (function () {
  25972. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25973. if (data instanceof BABYLON.Buffer) {
  25974. if (!stride) {
  25975. stride = data.getStrideSize();
  25976. }
  25977. this._buffer = data;
  25978. this._ownsBuffer = false;
  25979. }
  25980. else {
  25981. if (!stride) {
  25982. stride = VertexBuffer.DeduceStride(kind);
  25983. }
  25984. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25985. this._ownsBuffer = true;
  25986. }
  25987. this._stride = stride;
  25988. this._instanced = instanced !== undefined ? instanced : false;
  25989. this._instanceDivisor = instanced ? 1 : 0;
  25990. this._offset = offset ? offset : 0;
  25991. this._size = size ? size : stride;
  25992. this._kind = kind;
  25993. }
  25994. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25995. /**
  25996. * Gets or sets the instance divisor when in instanced mode
  25997. */
  25998. get: function () {
  25999. return this._instanceDivisor;
  26000. },
  26001. set: function (value) {
  26002. this._instanceDivisor = value;
  26003. if (value == 0) {
  26004. this._instanced = false;
  26005. }
  26006. else {
  26007. this._instanced = true;
  26008. }
  26009. },
  26010. enumerable: true,
  26011. configurable: true
  26012. });
  26013. VertexBuffer.prototype._rebuild = function () {
  26014. if (!this._buffer) {
  26015. return;
  26016. }
  26017. this._buffer._rebuild();
  26018. };
  26019. /**
  26020. * Returns the kind of the VertexBuffer (string).
  26021. */
  26022. VertexBuffer.prototype.getKind = function () {
  26023. return this._kind;
  26024. };
  26025. // Properties
  26026. /**
  26027. * Boolean : is the VertexBuffer updatable ?
  26028. */
  26029. VertexBuffer.prototype.isUpdatable = function () {
  26030. return this._buffer.isUpdatable();
  26031. };
  26032. /**
  26033. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26034. */
  26035. VertexBuffer.prototype.getData = function () {
  26036. return this._buffer.getData();
  26037. };
  26038. /**
  26039. * Returns the WebGLBuffer associated to the VertexBuffer.
  26040. */
  26041. VertexBuffer.prototype.getBuffer = function () {
  26042. return this._buffer.getBuffer();
  26043. };
  26044. /**
  26045. * Returns the stride of the VertexBuffer (integer).
  26046. */
  26047. VertexBuffer.prototype.getStrideSize = function () {
  26048. return this._stride;
  26049. };
  26050. /**
  26051. * Returns the offset (integer).
  26052. */
  26053. VertexBuffer.prototype.getOffset = function () {
  26054. return this._offset;
  26055. };
  26056. /**
  26057. * Returns the VertexBuffer total size (integer).
  26058. */
  26059. VertexBuffer.prototype.getSize = function () {
  26060. return this._size;
  26061. };
  26062. /**
  26063. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26064. */
  26065. VertexBuffer.prototype.getIsInstanced = function () {
  26066. return this._instanced;
  26067. };
  26068. /**
  26069. * Returns the instancing divisor, zero for non-instanced (integer).
  26070. */
  26071. VertexBuffer.prototype.getInstanceDivisor = function () {
  26072. return this._instanceDivisor;
  26073. };
  26074. // Methods
  26075. /**
  26076. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26077. * Returns the created WebGLBuffer.
  26078. */
  26079. VertexBuffer.prototype.create = function (data) {
  26080. return this._buffer.create(data);
  26081. };
  26082. /**
  26083. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26084. * This function will create a new buffer if the current one is not updatable
  26085. * Returns the updated WebGLBuffer.
  26086. */
  26087. VertexBuffer.prototype.update = function (data) {
  26088. return this._buffer.update(data);
  26089. };
  26090. /**
  26091. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26092. * Returns the directly updated WebGLBuffer.
  26093. */
  26094. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26095. return this._buffer.updateDirectly(data, offset);
  26096. };
  26097. /**
  26098. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26099. */
  26100. VertexBuffer.prototype.dispose = function () {
  26101. if (this._ownsBuffer) {
  26102. this._buffer.dispose();
  26103. }
  26104. };
  26105. Object.defineProperty(VertexBuffer, "PositionKind", {
  26106. get: function () {
  26107. return VertexBuffer._PositionKind;
  26108. },
  26109. enumerable: true,
  26110. configurable: true
  26111. });
  26112. Object.defineProperty(VertexBuffer, "NormalKind", {
  26113. get: function () {
  26114. return VertexBuffer._NormalKind;
  26115. },
  26116. enumerable: true,
  26117. configurable: true
  26118. });
  26119. Object.defineProperty(VertexBuffer, "TangentKind", {
  26120. get: function () {
  26121. return VertexBuffer._TangentKind;
  26122. },
  26123. enumerable: true,
  26124. configurable: true
  26125. });
  26126. Object.defineProperty(VertexBuffer, "UVKind", {
  26127. get: function () {
  26128. return VertexBuffer._UVKind;
  26129. },
  26130. enumerable: true,
  26131. configurable: true
  26132. });
  26133. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26134. get: function () {
  26135. return VertexBuffer._UV2Kind;
  26136. },
  26137. enumerable: true,
  26138. configurable: true
  26139. });
  26140. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26141. get: function () {
  26142. return VertexBuffer._UV3Kind;
  26143. },
  26144. enumerable: true,
  26145. configurable: true
  26146. });
  26147. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26148. get: function () {
  26149. return VertexBuffer._UV4Kind;
  26150. },
  26151. enumerable: true,
  26152. configurable: true
  26153. });
  26154. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26155. get: function () {
  26156. return VertexBuffer._UV5Kind;
  26157. },
  26158. enumerable: true,
  26159. configurable: true
  26160. });
  26161. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26162. get: function () {
  26163. return VertexBuffer._UV6Kind;
  26164. },
  26165. enumerable: true,
  26166. configurable: true
  26167. });
  26168. Object.defineProperty(VertexBuffer, "ColorKind", {
  26169. get: function () {
  26170. return VertexBuffer._ColorKind;
  26171. },
  26172. enumerable: true,
  26173. configurable: true
  26174. });
  26175. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26176. get: function () {
  26177. return VertexBuffer._MatricesIndicesKind;
  26178. },
  26179. enumerable: true,
  26180. configurable: true
  26181. });
  26182. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26183. get: function () {
  26184. return VertexBuffer._MatricesWeightsKind;
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26190. get: function () {
  26191. return VertexBuffer._MatricesIndicesExtraKind;
  26192. },
  26193. enumerable: true,
  26194. configurable: true
  26195. });
  26196. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26197. get: function () {
  26198. return VertexBuffer._MatricesWeightsExtraKind;
  26199. },
  26200. enumerable: true,
  26201. configurable: true
  26202. });
  26203. /**
  26204. * Deduces the stride given a kind.
  26205. * @param kind The kind string to deduce
  26206. * @returns The deduced stride
  26207. */
  26208. VertexBuffer.DeduceStride = function (kind) {
  26209. switch (kind) {
  26210. case VertexBuffer.UVKind:
  26211. case VertexBuffer.UV2Kind:
  26212. case VertexBuffer.UV3Kind:
  26213. case VertexBuffer.UV4Kind:
  26214. case VertexBuffer.UV5Kind:
  26215. case VertexBuffer.UV6Kind:
  26216. return 2;
  26217. case VertexBuffer.NormalKind:
  26218. case VertexBuffer.PositionKind:
  26219. return 3;
  26220. case VertexBuffer.ColorKind:
  26221. case VertexBuffer.MatricesIndicesKind:
  26222. case VertexBuffer.MatricesIndicesExtraKind:
  26223. case VertexBuffer.MatricesWeightsKind:
  26224. case VertexBuffer.MatricesWeightsExtraKind:
  26225. case VertexBuffer.TangentKind:
  26226. return 4;
  26227. default:
  26228. throw new Error("Invalid kind '" + kind + "'");
  26229. }
  26230. };
  26231. // Enums
  26232. VertexBuffer._PositionKind = "position";
  26233. VertexBuffer._NormalKind = "normal";
  26234. VertexBuffer._TangentKind = "tangent";
  26235. VertexBuffer._UVKind = "uv";
  26236. VertexBuffer._UV2Kind = "uv2";
  26237. VertexBuffer._UV3Kind = "uv3";
  26238. VertexBuffer._UV4Kind = "uv4";
  26239. VertexBuffer._UV5Kind = "uv5";
  26240. VertexBuffer._UV6Kind = "uv6";
  26241. VertexBuffer._ColorKind = "color";
  26242. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26243. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26244. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26245. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26246. return VertexBuffer;
  26247. }());
  26248. BABYLON.VertexBuffer = VertexBuffer;
  26249. })(BABYLON || (BABYLON = {}));
  26250. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26251. var BABYLON;
  26252. (function (BABYLON) {
  26253. /**
  26254. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26255. */
  26256. var DummyInternalTextureTracker = /** @class */ (function () {
  26257. function DummyInternalTextureTracker() {
  26258. /**
  26259. * Gets or set the previous tracker in the list
  26260. */
  26261. this.previous = null;
  26262. /**
  26263. * Gets or set the next tracker in the list
  26264. */
  26265. this.next = null;
  26266. }
  26267. return DummyInternalTextureTracker;
  26268. }());
  26269. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26270. })(BABYLON || (BABYLON = {}));
  26271. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. /**
  26275. * Class used to store data associated with WebGL texture data for the engine
  26276. * This class should not be used directly
  26277. */
  26278. var InternalTexture = /** @class */ (function () {
  26279. /**
  26280. * Creates a new InternalTexture
  26281. * @param engine defines the engine to use
  26282. * @param dataSource defines the type of data that will be used
  26283. */
  26284. function InternalTexture(engine, dataSource) {
  26285. /**
  26286. * Observable called when the texture is loaded
  26287. */
  26288. this.onLoadedObservable = new BABYLON.Observable();
  26289. /**
  26290. * Gets or set the previous tracker in the list
  26291. */
  26292. this.previous = null;
  26293. /**
  26294. * Gets or set the next tracker in the list
  26295. */
  26296. this.next = null;
  26297. // Private
  26298. /** @ignore */
  26299. this._initialSlot = -1;
  26300. /** @ignore */
  26301. this._designatedSlot = -1;
  26302. /** @ignore */
  26303. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26304. /** @ignore */
  26305. this._comparisonFunction = 0;
  26306. /** @ignore */
  26307. this._references = 1;
  26308. this._engine = engine;
  26309. this._dataSource = dataSource;
  26310. this._webGLTexture = engine._createTexture();
  26311. }
  26312. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26313. /**
  26314. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26315. */
  26316. get: function () {
  26317. return this._dataSource;
  26318. },
  26319. enumerable: true,
  26320. configurable: true
  26321. });
  26322. /**
  26323. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26324. */
  26325. InternalTexture.prototype.incrementReferences = function () {
  26326. this._references++;
  26327. };
  26328. /**
  26329. * Change the size of the texture (not the size of the content)
  26330. * @param width defines the new width
  26331. * @param height defines the new height
  26332. * @param depth defines the new depth (1 by default)
  26333. */
  26334. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26335. if (depth === void 0) { depth = 1; }
  26336. this.width = width;
  26337. this.height = height;
  26338. this.depth = depth;
  26339. this.baseWidth = width;
  26340. this.baseHeight = height;
  26341. this.baseDepth = depth;
  26342. this._size = width * height * depth;
  26343. };
  26344. /** @ignore */
  26345. InternalTexture.prototype._rebuild = function () {
  26346. var _this = this;
  26347. var proxy;
  26348. this.isReady = false;
  26349. this._cachedCoordinatesMode = null;
  26350. this._cachedWrapU = null;
  26351. this._cachedWrapV = null;
  26352. this._cachedAnisotropicFilteringLevel = null;
  26353. switch (this._dataSource) {
  26354. case InternalTexture.DATASOURCE_TEMP:
  26355. return;
  26356. case InternalTexture.DATASOURCE_URL:
  26357. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26358. _this.isReady = true;
  26359. }, null, this._buffer, undefined, this.format);
  26360. proxy._swapAndDie(this);
  26361. return;
  26362. case InternalTexture.DATASOURCE_RAW:
  26363. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26364. proxy._swapAndDie(this);
  26365. this.isReady = true;
  26366. return;
  26367. case InternalTexture.DATASOURCE_RAW3D:
  26368. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26369. proxy._swapAndDie(this);
  26370. this.isReady = true;
  26371. return;
  26372. case InternalTexture.DATASOURCE_DYNAMIC:
  26373. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26374. proxy._swapAndDie(this);
  26375. // The engine will make sure to update content so no need to flag it as isReady = true
  26376. return;
  26377. case InternalTexture.DATASOURCE_RENDERTARGET:
  26378. var options = new BABYLON.RenderTargetCreationOptions();
  26379. options.generateDepthBuffer = this._generateDepthBuffer;
  26380. options.generateMipMaps = this.generateMipMaps;
  26381. options.generateStencilBuffer = this._generateStencilBuffer;
  26382. options.samplingMode = this.samplingMode;
  26383. options.type = this.type;
  26384. if (this.isCube) {
  26385. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26386. }
  26387. else {
  26388. var size = {
  26389. width: this.width,
  26390. height: this.height
  26391. };
  26392. proxy = this._engine.createRenderTargetTexture(size, options);
  26393. }
  26394. proxy._swapAndDie(this);
  26395. this.isReady = true;
  26396. return;
  26397. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26398. var depthTextureOptions = {
  26399. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26400. comparisonFunction: this._comparisonFunction,
  26401. generateStencil: this._generateStencilBuffer,
  26402. };
  26403. if (this.isCube) {
  26404. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26405. }
  26406. else {
  26407. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26408. }
  26409. proxy._swapAndDie(this);
  26410. this.isReady = true;
  26411. return;
  26412. case InternalTexture.DATASOURCE_CUBE:
  26413. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26414. _this.isReady = true;
  26415. }, null, this.format, this._extension);
  26416. proxy._swapAndDie(this);
  26417. return;
  26418. case InternalTexture.DATASOURCE_CUBERAW:
  26419. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26420. proxy._swapAndDie(this);
  26421. this.isReady = true;
  26422. return;
  26423. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26424. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26425. if (proxy) {
  26426. proxy._swapAndDie(_this);
  26427. }
  26428. _this.isReady = true;
  26429. }, null, this.format, this._extension);
  26430. return;
  26431. }
  26432. };
  26433. InternalTexture.prototype._swapAndDie = function (target) {
  26434. target._webGLTexture = this._webGLTexture;
  26435. if (this._framebuffer) {
  26436. target._framebuffer = this._framebuffer;
  26437. }
  26438. if (this._depthStencilBuffer) {
  26439. target._depthStencilBuffer = this._depthStencilBuffer;
  26440. }
  26441. if (this._lodTextureHigh) {
  26442. if (target._lodTextureHigh) {
  26443. target._lodTextureHigh.dispose();
  26444. }
  26445. target._lodTextureHigh = this._lodTextureHigh;
  26446. }
  26447. if (this._lodTextureMid) {
  26448. if (target._lodTextureMid) {
  26449. target._lodTextureMid.dispose();
  26450. }
  26451. target._lodTextureMid = this._lodTextureMid;
  26452. }
  26453. if (this._lodTextureLow) {
  26454. if (target._lodTextureLow) {
  26455. target._lodTextureLow.dispose();
  26456. }
  26457. target._lodTextureLow = this._lodTextureLow;
  26458. }
  26459. var cache = this._engine.getLoadedTexturesCache();
  26460. var index = cache.indexOf(this);
  26461. if (index !== -1) {
  26462. cache.splice(index, 1);
  26463. }
  26464. };
  26465. /**
  26466. * Dispose the current allocated resources
  26467. */
  26468. InternalTexture.prototype.dispose = function () {
  26469. if (!this._webGLTexture) {
  26470. return;
  26471. }
  26472. this._references--;
  26473. if (this._references === 0) {
  26474. this._engine._releaseTexture(this);
  26475. this._webGLTexture = null;
  26476. this.previous = null;
  26477. this.next = null;
  26478. }
  26479. };
  26480. /**
  26481. * The source of the texture data is unknown
  26482. */
  26483. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26484. /**
  26485. * Texture data comes from an URL
  26486. */
  26487. InternalTexture.DATASOURCE_URL = 1;
  26488. /**
  26489. * Texture data is only used for temporary storage
  26490. */
  26491. InternalTexture.DATASOURCE_TEMP = 2;
  26492. /**
  26493. * Texture data comes from raw data (ArrayBuffer)
  26494. */
  26495. InternalTexture.DATASOURCE_RAW = 3;
  26496. /**
  26497. * Texture content is dynamic (video or dynamic texture)
  26498. */
  26499. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26500. /**
  26501. * Texture content is generated by rendering to it
  26502. */
  26503. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26504. /**
  26505. * Texture content is part of a multi render target process
  26506. */
  26507. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26508. /**
  26509. * Texture data comes from a cube data file
  26510. */
  26511. InternalTexture.DATASOURCE_CUBE = 7;
  26512. /**
  26513. * Texture data comes from a raw cube data
  26514. */
  26515. InternalTexture.DATASOURCE_CUBERAW = 8;
  26516. /**
  26517. * Texture data come from a prefiltered cube data file
  26518. */
  26519. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26520. /**
  26521. * Texture content is raw 3D data
  26522. */
  26523. InternalTexture.DATASOURCE_RAW3D = 10;
  26524. /**
  26525. * Texture content is a depth texture
  26526. */
  26527. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26528. return InternalTexture;
  26529. }());
  26530. BABYLON.InternalTexture = InternalTexture;
  26531. })(BABYLON || (BABYLON = {}));
  26532. //# sourceMappingURL=babylon.internalTexture.js.map
  26533. var BABYLON;
  26534. (function (BABYLON) {
  26535. var BaseTexture = /** @class */ (function () {
  26536. function BaseTexture(scene) {
  26537. this._hasAlpha = false;
  26538. this.getAlphaFromRGB = false;
  26539. this.level = 1;
  26540. this.coordinatesIndex = 0;
  26541. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26542. /**
  26543. * | Value | Type | Description |
  26544. * | ----- | ------------------ | ----------- |
  26545. * | 0 | CLAMP_ADDRESSMODE | |
  26546. * | 1 | WRAP_ADDRESSMODE | |
  26547. * | 2 | MIRROR_ADDRESSMODE | |
  26548. */
  26549. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26550. /**
  26551. * | Value | Type | Description |
  26552. * | ----- | ------------------ | ----------- |
  26553. * | 0 | CLAMP_ADDRESSMODE | |
  26554. * | 1 | WRAP_ADDRESSMODE | |
  26555. * | 2 | MIRROR_ADDRESSMODE | |
  26556. */
  26557. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26558. /**
  26559. * | Value | Type | Description |
  26560. * | ----- | ------------------ | ----------- |
  26561. * | 0 | CLAMP_ADDRESSMODE | |
  26562. * | 1 | WRAP_ADDRESSMODE | |
  26563. * | 2 | MIRROR_ADDRESSMODE | |
  26564. */
  26565. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26566. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26567. this.isCube = false;
  26568. this.is3D = false;
  26569. this.gammaSpace = true;
  26570. this.invertZ = false;
  26571. this.lodLevelInAlpha = false;
  26572. this.lodGenerationOffset = 0.0;
  26573. this.lodGenerationScale = 0.8;
  26574. this.isRenderTarget = false;
  26575. this.animations = new Array();
  26576. /**
  26577. * An event triggered when the texture is disposed.
  26578. * @type {BABYLON.Observable}
  26579. */
  26580. this.onDisposeObservable = new BABYLON.Observable();
  26581. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26583. if (this._scene) {
  26584. this._scene.textures.push(this);
  26585. }
  26586. this._uid = null;
  26587. }
  26588. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26589. get: function () {
  26590. return this._hasAlpha;
  26591. },
  26592. set: function (value) {
  26593. if (this._hasAlpha === value) {
  26594. return;
  26595. }
  26596. this._hasAlpha = value;
  26597. if (this._scene) {
  26598. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26599. }
  26600. },
  26601. enumerable: true,
  26602. configurable: true
  26603. });
  26604. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26605. get: function () {
  26606. return this._coordinatesMode;
  26607. },
  26608. /**
  26609. * How a texture is mapped.
  26610. *
  26611. * | Value | Type | Description |
  26612. * | ----- | ----------------------------------- | ----------- |
  26613. * | 0 | EXPLICIT_MODE | |
  26614. * | 1 | SPHERICAL_MODE | |
  26615. * | 2 | PLANAR_MODE | |
  26616. * | 3 | CUBIC_MODE | |
  26617. * | 4 | PROJECTION_MODE | |
  26618. * | 5 | SKYBOX_MODE | |
  26619. * | 6 | INVCUBIC_MODE | |
  26620. * | 7 | EQUIRECTANGULAR_MODE | |
  26621. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26622. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26623. */
  26624. set: function (value) {
  26625. if (this._coordinatesMode === value) {
  26626. return;
  26627. }
  26628. this._coordinatesMode = value;
  26629. if (this._scene) {
  26630. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26631. }
  26632. },
  26633. enumerable: true,
  26634. configurable: true
  26635. });
  26636. Object.defineProperty(BaseTexture.prototype, "uid", {
  26637. get: function () {
  26638. if (!this._uid) {
  26639. this._uid = BABYLON.Tools.RandomId();
  26640. }
  26641. return this._uid;
  26642. },
  26643. enumerable: true,
  26644. configurable: true
  26645. });
  26646. BaseTexture.prototype.toString = function () {
  26647. return this.name;
  26648. };
  26649. BaseTexture.prototype.getClassName = function () {
  26650. return "BaseTexture";
  26651. };
  26652. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26653. set: function (callback) {
  26654. if (this._onDisposeObserver) {
  26655. this.onDisposeObservable.remove(this._onDisposeObserver);
  26656. }
  26657. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26658. },
  26659. enumerable: true,
  26660. configurable: true
  26661. });
  26662. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26663. get: function () {
  26664. return true;
  26665. },
  26666. enumerable: true,
  26667. configurable: true
  26668. });
  26669. BaseTexture.prototype.getScene = function () {
  26670. return this._scene;
  26671. };
  26672. BaseTexture.prototype.getTextureMatrix = function () {
  26673. return BABYLON.Matrix.IdentityReadOnly;
  26674. };
  26675. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26676. return BABYLON.Matrix.IdentityReadOnly;
  26677. };
  26678. BaseTexture.prototype.getInternalTexture = function () {
  26679. return this._texture;
  26680. };
  26681. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26682. return !this.isBlocking || this.isReady();
  26683. };
  26684. BaseTexture.prototype.isReady = function () {
  26685. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26686. this.delayLoad();
  26687. return false;
  26688. }
  26689. if (this._texture) {
  26690. return this._texture.isReady;
  26691. }
  26692. return false;
  26693. };
  26694. BaseTexture.prototype.getSize = function () {
  26695. if (this._texture && this._texture.width) {
  26696. return new BABYLON.Size(this._texture.width, this._texture.height);
  26697. }
  26698. if (this._texture && this._texture._size) {
  26699. return new BABYLON.Size(this._texture._size, this._texture._size);
  26700. }
  26701. return BABYLON.Size.Zero();
  26702. };
  26703. BaseTexture.prototype.getBaseSize = function () {
  26704. if (!this.isReady() || !this._texture)
  26705. return BABYLON.Size.Zero();
  26706. if (this._texture._size) {
  26707. return new BABYLON.Size(this._texture._size, this._texture._size);
  26708. }
  26709. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26710. };
  26711. BaseTexture.prototype.scale = function (ratio) {
  26712. };
  26713. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26714. get: function () {
  26715. return false;
  26716. },
  26717. enumerable: true,
  26718. configurable: true
  26719. });
  26720. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26721. if (!this._scene) {
  26722. return null;
  26723. }
  26724. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26725. for (var index = 0; index < texturesCache.length; index++) {
  26726. var texturesCacheEntry = texturesCache[index];
  26727. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26728. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26729. texturesCacheEntry.incrementReferences();
  26730. return texturesCacheEntry;
  26731. }
  26732. }
  26733. }
  26734. return null;
  26735. };
  26736. BaseTexture.prototype._rebuild = function () {
  26737. };
  26738. BaseTexture.prototype.delayLoad = function () {
  26739. };
  26740. BaseTexture.prototype.clone = function () {
  26741. return null;
  26742. };
  26743. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26744. get: function () {
  26745. if (!this._texture) {
  26746. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26747. }
  26748. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26749. },
  26750. enumerable: true,
  26751. configurable: true
  26752. });
  26753. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26754. get: function () {
  26755. if (!this._texture) {
  26756. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26757. }
  26758. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26759. },
  26760. enumerable: true,
  26761. configurable: true
  26762. });
  26763. BaseTexture.prototype.readPixels = function (faceIndex) {
  26764. if (faceIndex === void 0) { faceIndex = 0; }
  26765. if (!this._texture) {
  26766. return null;
  26767. }
  26768. var size = this.getSize();
  26769. var scene = this.getScene();
  26770. if (!scene) {
  26771. return null;
  26772. }
  26773. var engine = scene.getEngine();
  26774. if (this._texture.isCube) {
  26775. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26776. }
  26777. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26778. };
  26779. BaseTexture.prototype.releaseInternalTexture = function () {
  26780. if (this._texture) {
  26781. this._texture.dispose();
  26782. this._texture = null;
  26783. }
  26784. };
  26785. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26786. get: function () {
  26787. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26788. return null;
  26789. }
  26790. if (!this._texture._sphericalPolynomial) {
  26791. this._texture._sphericalPolynomial =
  26792. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26793. }
  26794. return this._texture._sphericalPolynomial;
  26795. },
  26796. set: function (value) {
  26797. if (this._texture) {
  26798. this._texture._sphericalPolynomial = value;
  26799. }
  26800. },
  26801. enumerable: true,
  26802. configurable: true
  26803. });
  26804. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26805. get: function () {
  26806. if (this._texture) {
  26807. return this._texture._lodTextureHigh;
  26808. }
  26809. return null;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26815. get: function () {
  26816. if (this._texture) {
  26817. return this._texture._lodTextureMid;
  26818. }
  26819. return null;
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26825. get: function () {
  26826. if (this._texture) {
  26827. return this._texture._lodTextureLow;
  26828. }
  26829. return null;
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. BaseTexture.prototype.dispose = function () {
  26835. if (!this._scene) {
  26836. return;
  26837. }
  26838. // Animations
  26839. this._scene.stopAnimation(this);
  26840. // Remove from scene
  26841. this._scene._removePendingData(this);
  26842. var index = this._scene.textures.indexOf(this);
  26843. if (index >= 0) {
  26844. this._scene.textures.splice(index, 1);
  26845. }
  26846. if (this._texture === undefined) {
  26847. return;
  26848. }
  26849. // Release
  26850. this.releaseInternalTexture();
  26851. // Callback
  26852. this.onDisposeObservable.notifyObservers(this);
  26853. this.onDisposeObservable.clear();
  26854. };
  26855. BaseTexture.prototype.serialize = function () {
  26856. if (!this.name) {
  26857. return null;
  26858. }
  26859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26860. // Animations
  26861. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26862. return serializationObject;
  26863. };
  26864. BaseTexture.WhenAllReady = function (textures, callback) {
  26865. var numRemaining = textures.length;
  26866. if (numRemaining === 0) {
  26867. callback();
  26868. return;
  26869. }
  26870. var _loop_1 = function () {
  26871. texture = textures[i];
  26872. if (texture.isReady()) {
  26873. if (--numRemaining === 0) {
  26874. callback();
  26875. }
  26876. }
  26877. else {
  26878. onLoadObservable = texture.onLoadObservable;
  26879. var onLoadCallback_1 = function () {
  26880. onLoadObservable.removeCallback(onLoadCallback_1);
  26881. if (--numRemaining === 0) {
  26882. callback();
  26883. }
  26884. };
  26885. onLoadObservable.add(onLoadCallback_1);
  26886. }
  26887. };
  26888. var texture, onLoadObservable;
  26889. for (var i = 0; i < textures.length; i++) {
  26890. _loop_1();
  26891. }
  26892. };
  26893. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26894. __decorate([
  26895. BABYLON.serialize()
  26896. ], BaseTexture.prototype, "name", void 0);
  26897. __decorate([
  26898. BABYLON.serialize("hasAlpha")
  26899. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26900. __decorate([
  26901. BABYLON.serialize()
  26902. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26903. __decorate([
  26904. BABYLON.serialize()
  26905. ], BaseTexture.prototype, "level", void 0);
  26906. __decorate([
  26907. BABYLON.serialize()
  26908. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26909. __decorate([
  26910. BABYLON.serialize("coordinatesMode")
  26911. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26912. __decorate([
  26913. BABYLON.serialize()
  26914. ], BaseTexture.prototype, "wrapU", void 0);
  26915. __decorate([
  26916. BABYLON.serialize()
  26917. ], BaseTexture.prototype, "wrapV", void 0);
  26918. __decorate([
  26919. BABYLON.serialize()
  26920. ], BaseTexture.prototype, "wrapR", void 0);
  26921. __decorate([
  26922. BABYLON.serialize()
  26923. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26924. __decorate([
  26925. BABYLON.serialize()
  26926. ], BaseTexture.prototype, "isCube", void 0);
  26927. __decorate([
  26928. BABYLON.serialize()
  26929. ], BaseTexture.prototype, "is3D", void 0);
  26930. __decorate([
  26931. BABYLON.serialize()
  26932. ], BaseTexture.prototype, "gammaSpace", void 0);
  26933. __decorate([
  26934. BABYLON.serialize()
  26935. ], BaseTexture.prototype, "invertZ", void 0);
  26936. __decorate([
  26937. BABYLON.serialize()
  26938. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26939. __decorate([
  26940. BABYLON.serialize()
  26941. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26942. __decorate([
  26943. BABYLON.serialize()
  26944. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26945. __decorate([
  26946. BABYLON.serialize()
  26947. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26948. return BaseTexture;
  26949. }());
  26950. BABYLON.BaseTexture = BaseTexture;
  26951. })(BABYLON || (BABYLON = {}));
  26952. //# sourceMappingURL=babylon.baseTexture.js.map
  26953. var BABYLON;
  26954. (function (BABYLON) {
  26955. var Texture = /** @class */ (function (_super) {
  26956. __extends(Texture, _super);
  26957. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26958. if (noMipmap === void 0) { noMipmap = false; }
  26959. if (invertY === void 0) { invertY = true; }
  26960. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26961. if (onLoad === void 0) { onLoad = null; }
  26962. if (onError === void 0) { onError = null; }
  26963. if (buffer === void 0) { buffer = null; }
  26964. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26965. var _this = _super.call(this, scene) || this;
  26966. _this.uOffset = 0;
  26967. _this.vOffset = 0;
  26968. _this.uScale = 1.0;
  26969. _this.vScale = 1.0;
  26970. _this.uAng = 0;
  26971. _this.vAng = 0;
  26972. _this.wAng = 0;
  26973. _this._isBlocking = true;
  26974. _this.name = url || "";
  26975. _this.url = url;
  26976. _this._noMipmap = noMipmap;
  26977. _this._invertY = invertY;
  26978. _this._samplingMode = samplingMode;
  26979. _this._buffer = buffer;
  26980. _this._deleteBuffer = deleteBuffer;
  26981. if (format) {
  26982. _this._format = format;
  26983. }
  26984. scene = _this.getScene();
  26985. if (!scene) {
  26986. return _this;
  26987. }
  26988. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26989. var load = function () {
  26990. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26991. _this.onLoadObservable.notifyObservers(_this);
  26992. }
  26993. if (onLoad) {
  26994. onLoad();
  26995. }
  26996. if (!_this.isBlocking && scene) {
  26997. scene.resetCachedMaterial();
  26998. }
  26999. };
  27000. if (!_this.url) {
  27001. _this._delayedOnLoad = load;
  27002. _this._delayedOnError = onError;
  27003. return _this;
  27004. }
  27005. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27006. if (!_this._texture) {
  27007. if (!scene.useDelayedTextureLoading) {
  27008. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27009. if (deleteBuffer) {
  27010. delete _this._buffer;
  27011. }
  27012. }
  27013. else {
  27014. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27015. _this._delayedOnLoad = load;
  27016. _this._delayedOnError = onError;
  27017. }
  27018. }
  27019. else {
  27020. if (_this._texture.isReady) {
  27021. BABYLON.Tools.SetImmediate(function () { return load(); });
  27022. }
  27023. else {
  27024. _this._texture.onLoadedObservable.add(load);
  27025. }
  27026. }
  27027. return _this;
  27028. }
  27029. Object.defineProperty(Texture.prototype, "noMipmap", {
  27030. get: function () {
  27031. return this._noMipmap;
  27032. },
  27033. enumerable: true,
  27034. configurable: true
  27035. });
  27036. Object.defineProperty(Texture.prototype, "isBlocking", {
  27037. get: function () {
  27038. return this._isBlocking;
  27039. },
  27040. set: function (value) {
  27041. this._isBlocking = value;
  27042. },
  27043. enumerable: true,
  27044. configurable: true
  27045. });
  27046. Object.defineProperty(Texture.prototype, "samplingMode", {
  27047. get: function () {
  27048. return this._samplingMode;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. Texture.prototype.updateURL = function (url) {
  27054. this.url = url;
  27055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27056. this.delayLoad();
  27057. };
  27058. Texture.prototype.delayLoad = function () {
  27059. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27060. return;
  27061. }
  27062. var scene = this.getScene();
  27063. if (!scene) {
  27064. return;
  27065. }
  27066. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27067. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27068. if (!this._texture) {
  27069. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27070. if (this._deleteBuffer) {
  27071. delete this._buffer;
  27072. }
  27073. }
  27074. else {
  27075. if (this._delayedOnLoad) {
  27076. if (this._texture.isReady) {
  27077. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27078. }
  27079. else {
  27080. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27081. }
  27082. }
  27083. }
  27084. this._delayedOnLoad = null;
  27085. this._delayedOnError = null;
  27086. };
  27087. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27088. if (!this._texture) {
  27089. return;
  27090. }
  27091. var scene = this.getScene();
  27092. if (!scene) {
  27093. return;
  27094. }
  27095. this._samplingMode = samplingMode;
  27096. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27097. };
  27098. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27099. x *= this.uScale;
  27100. y *= this.vScale;
  27101. x -= 0.5 * this.uScale;
  27102. y -= 0.5 * this.vScale;
  27103. z -= 0.5;
  27104. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27105. t.x += 0.5 * this.uScale + this.uOffset;
  27106. t.y += 0.5 * this.vScale + this.vOffset;
  27107. t.z += 0.5;
  27108. };
  27109. Texture.prototype.getTextureMatrix = function () {
  27110. var _this = this;
  27111. if (this.uOffset === this._cachedUOffset &&
  27112. this.vOffset === this._cachedVOffset &&
  27113. this.uScale === this._cachedUScale &&
  27114. this.vScale === this._cachedVScale &&
  27115. this.uAng === this._cachedUAng &&
  27116. this.vAng === this._cachedVAng &&
  27117. this.wAng === this._cachedWAng) {
  27118. return this._cachedTextureMatrix;
  27119. }
  27120. this._cachedUOffset = this.uOffset;
  27121. this._cachedVOffset = this.vOffset;
  27122. this._cachedUScale = this.uScale;
  27123. this._cachedVScale = this.vScale;
  27124. this._cachedUAng = this.uAng;
  27125. this._cachedVAng = this.vAng;
  27126. this._cachedWAng = this.wAng;
  27127. if (!this._cachedTextureMatrix) {
  27128. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27129. this._rowGenerationMatrix = new BABYLON.Matrix();
  27130. this._t0 = BABYLON.Vector3.Zero();
  27131. this._t1 = BABYLON.Vector3.Zero();
  27132. this._t2 = BABYLON.Vector3.Zero();
  27133. }
  27134. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27135. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27136. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27137. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27138. this._t1.subtractInPlace(this._t0);
  27139. this._t2.subtractInPlace(this._t0);
  27140. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27141. this._cachedTextureMatrix.m[0] = this._t1.x;
  27142. this._cachedTextureMatrix.m[1] = this._t1.y;
  27143. this._cachedTextureMatrix.m[2] = this._t1.z;
  27144. this._cachedTextureMatrix.m[4] = this._t2.x;
  27145. this._cachedTextureMatrix.m[5] = this._t2.y;
  27146. this._cachedTextureMatrix.m[6] = this._t2.z;
  27147. this._cachedTextureMatrix.m[8] = this._t0.x;
  27148. this._cachedTextureMatrix.m[9] = this._t0.y;
  27149. this._cachedTextureMatrix.m[10] = this._t0.z;
  27150. var scene = this.getScene();
  27151. if (!scene) {
  27152. return this._cachedTextureMatrix;
  27153. }
  27154. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27155. return mat.hasTexture(_this);
  27156. });
  27157. return this._cachedTextureMatrix;
  27158. };
  27159. Texture.prototype.getReflectionTextureMatrix = function () {
  27160. var _this = this;
  27161. var scene = this.getScene();
  27162. if (!scene) {
  27163. return this._cachedTextureMatrix;
  27164. }
  27165. if (this.uOffset === this._cachedUOffset &&
  27166. this.vOffset === this._cachedVOffset &&
  27167. this.uScale === this._cachedUScale &&
  27168. this.vScale === this._cachedVScale &&
  27169. this.coordinatesMode === this._cachedCoordinatesMode) {
  27170. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27171. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27172. return this._cachedTextureMatrix;
  27173. }
  27174. }
  27175. else {
  27176. return this._cachedTextureMatrix;
  27177. }
  27178. }
  27179. if (!this._cachedTextureMatrix) {
  27180. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27181. }
  27182. if (!this._projectionModeMatrix) {
  27183. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27184. }
  27185. this._cachedUOffset = this.uOffset;
  27186. this._cachedVOffset = this.vOffset;
  27187. this._cachedUScale = this.uScale;
  27188. this._cachedVScale = this.vScale;
  27189. this._cachedCoordinatesMode = this.coordinatesMode;
  27190. switch (this.coordinatesMode) {
  27191. case Texture.PLANAR_MODE:
  27192. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27193. this._cachedTextureMatrix[0] = this.uScale;
  27194. this._cachedTextureMatrix[5] = this.vScale;
  27195. this._cachedTextureMatrix[12] = this.uOffset;
  27196. this._cachedTextureMatrix[13] = this.vOffset;
  27197. break;
  27198. case Texture.PROJECTION_MODE:
  27199. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27200. this._projectionModeMatrix.m[0] = 0.5;
  27201. this._projectionModeMatrix.m[5] = -0.5;
  27202. this._projectionModeMatrix.m[10] = 0.0;
  27203. this._projectionModeMatrix.m[12] = 0.5;
  27204. this._projectionModeMatrix.m[13] = 0.5;
  27205. this._projectionModeMatrix.m[14] = 1.0;
  27206. this._projectionModeMatrix.m[15] = 1.0;
  27207. var projectionMatrix = scene.getProjectionMatrix();
  27208. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27209. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27210. break;
  27211. default:
  27212. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27213. break;
  27214. }
  27215. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27216. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27217. });
  27218. return this._cachedTextureMatrix;
  27219. };
  27220. Texture.prototype.clone = function () {
  27221. var _this = this;
  27222. return BABYLON.SerializationHelper.Clone(function () {
  27223. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27224. }, this);
  27225. };
  27226. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27227. get: function () {
  27228. if (!this._onLoadObservable) {
  27229. this._onLoadObservable = new BABYLON.Observable();
  27230. }
  27231. return this._onLoadObservable;
  27232. },
  27233. enumerable: true,
  27234. configurable: true
  27235. });
  27236. Texture.prototype.serialize = function () {
  27237. var serializationObject = _super.prototype.serialize.call(this);
  27238. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27239. serializationObject.base64String = this._buffer;
  27240. serializationObject.name = serializationObject.name.replace("data:", "");
  27241. }
  27242. return serializationObject;
  27243. };
  27244. Texture.prototype.getClassName = function () {
  27245. return "Texture";
  27246. };
  27247. Texture.prototype.dispose = function () {
  27248. _super.prototype.dispose.call(this);
  27249. if (this.onLoadObservable) {
  27250. this.onLoadObservable.clear();
  27251. this._onLoadObservable = null;
  27252. }
  27253. this._delayedOnLoad = null;
  27254. this._delayedOnError = null;
  27255. };
  27256. // Statics
  27257. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27258. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27259. if (onLoad === void 0) { onLoad = null; }
  27260. if (onError === void 0) { onError = null; }
  27261. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27262. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27263. };
  27264. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27265. if (parsedTexture.customType) {
  27266. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27267. // Update Sampling Mode
  27268. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27269. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27270. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27271. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27272. }
  27273. }
  27274. return parsedCustomTexture;
  27275. }
  27276. if (parsedTexture.isCube) {
  27277. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27278. }
  27279. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27280. return null;
  27281. }
  27282. var texture = BABYLON.SerializationHelper.Parse(function () {
  27283. var generateMipMaps = true;
  27284. if (parsedTexture.noMipmap) {
  27285. generateMipMaps = false;
  27286. }
  27287. if (parsedTexture.mirrorPlane) {
  27288. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27289. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27290. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27291. return mirrorTexture;
  27292. }
  27293. else if (parsedTexture.isRenderTarget) {
  27294. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27295. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27296. return renderTargetTexture;
  27297. }
  27298. else {
  27299. var texture;
  27300. if (parsedTexture.base64String) {
  27301. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27302. }
  27303. else {
  27304. var url = rootUrl + parsedTexture.name;
  27305. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27306. url = parsedTexture.url;
  27307. }
  27308. texture = new Texture(url, scene, !generateMipMaps);
  27309. }
  27310. return texture;
  27311. }
  27312. }, parsedTexture, scene);
  27313. // Update Sampling Mode
  27314. if (parsedTexture.samplingMode) {
  27315. var sampling = parsedTexture.samplingMode;
  27316. if (texture._samplingMode !== sampling) {
  27317. texture.updateSamplingMode(sampling);
  27318. }
  27319. }
  27320. // Animations
  27321. if (parsedTexture.animations) {
  27322. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27323. var parsedAnimation = parsedTexture.animations[animationIndex];
  27324. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27325. }
  27326. }
  27327. return texture;
  27328. };
  27329. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27330. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27331. if (noMipmap === void 0) { noMipmap = false; }
  27332. if (invertY === void 0) { invertY = true; }
  27333. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27334. if (onLoad === void 0) { onLoad = null; }
  27335. if (onError === void 0) { onError = null; }
  27336. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27337. if (name.substr(0, 5) !== "data:") {
  27338. name = "data:" + name;
  27339. }
  27340. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27341. };
  27342. // Constants
  27343. Texture.NEAREST_SAMPLINGMODE = 1;
  27344. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27345. Texture.BILINEAR_SAMPLINGMODE = 2;
  27346. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27347. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27348. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27349. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27350. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27351. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27352. Texture.NEAREST_LINEAR = 7;
  27353. Texture.NEAREST_NEAREST = 8;
  27354. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27355. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27356. Texture.LINEAR_LINEAR = 11;
  27357. Texture.LINEAR_NEAREST = 12;
  27358. Texture.EXPLICIT_MODE = 0;
  27359. Texture.SPHERICAL_MODE = 1;
  27360. Texture.PLANAR_MODE = 2;
  27361. Texture.CUBIC_MODE = 3;
  27362. Texture.PROJECTION_MODE = 4;
  27363. Texture.SKYBOX_MODE = 5;
  27364. Texture.INVCUBIC_MODE = 6;
  27365. Texture.EQUIRECTANGULAR_MODE = 7;
  27366. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27367. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27368. Texture.CLAMP_ADDRESSMODE = 0;
  27369. Texture.WRAP_ADDRESSMODE = 1;
  27370. Texture.MIRROR_ADDRESSMODE = 2;
  27371. /**
  27372. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27373. */
  27374. Texture.UseSerializedUrlIfAny = false;
  27375. __decorate([
  27376. BABYLON.serialize()
  27377. ], Texture.prototype, "url", void 0);
  27378. __decorate([
  27379. BABYLON.serialize()
  27380. ], Texture.prototype, "uOffset", void 0);
  27381. __decorate([
  27382. BABYLON.serialize()
  27383. ], Texture.prototype, "vOffset", void 0);
  27384. __decorate([
  27385. BABYLON.serialize()
  27386. ], Texture.prototype, "uScale", void 0);
  27387. __decorate([
  27388. BABYLON.serialize()
  27389. ], Texture.prototype, "vScale", void 0);
  27390. __decorate([
  27391. BABYLON.serialize()
  27392. ], Texture.prototype, "uAng", void 0);
  27393. __decorate([
  27394. BABYLON.serialize()
  27395. ], Texture.prototype, "vAng", void 0);
  27396. __decorate([
  27397. BABYLON.serialize()
  27398. ], Texture.prototype, "wAng", void 0);
  27399. __decorate([
  27400. BABYLON.serialize()
  27401. ], Texture.prototype, "isBlocking", null);
  27402. return Texture;
  27403. }(BABYLON.BaseTexture));
  27404. BABYLON.Texture = Texture;
  27405. })(BABYLON || (BABYLON = {}));
  27406. //# sourceMappingURL=babylon.texture.js.map
  27407. var BABYLON;
  27408. (function (BABYLON) {
  27409. var _InstancesBatch = /** @class */ (function () {
  27410. function _InstancesBatch() {
  27411. this.mustReturn = false;
  27412. this.visibleInstances = new Array();
  27413. this.renderSelf = new Array();
  27414. }
  27415. return _InstancesBatch;
  27416. }());
  27417. BABYLON._InstancesBatch = _InstancesBatch;
  27418. var Mesh = /** @class */ (function (_super) {
  27419. __extends(Mesh, _super);
  27420. /**
  27421. * @constructor
  27422. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27423. * @param {Scene} scene The scene to add this mesh to.
  27424. * @param {Node} parent The parent of this mesh, if it has one
  27425. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27426. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27427. * When false, achieved by calling a clone(), also passing False.
  27428. * This will make creation of children, recursive.
  27429. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27430. */
  27431. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27432. if (scene === void 0) { scene = null; }
  27433. if (parent === void 0) { parent = null; }
  27434. if (source === void 0) { source = null; }
  27435. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27436. var _this = _super.call(this, name, scene) || this;
  27437. // Events
  27438. /**
  27439. * An event triggered before rendering the mesh
  27440. * @type {BABYLON.Observable}
  27441. */
  27442. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27443. /**
  27444. * An event triggered after rendering the mesh
  27445. * @type {BABYLON.Observable}
  27446. */
  27447. _this.onAfterRenderObservable = new BABYLON.Observable();
  27448. /**
  27449. * An event triggered before drawing the mesh
  27450. * @type {BABYLON.Observable}
  27451. */
  27452. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27453. // Members
  27454. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27455. _this.instances = new Array();
  27456. _this._LODLevels = new Array();
  27457. _this._visibleInstances = {};
  27458. _this._renderIdForInstances = new Array();
  27459. _this._batchCache = new _InstancesBatch();
  27460. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27461. // Use by builder only to know what orientation were the mesh build in.
  27462. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27463. _this.overrideMaterialSideOrientation = null;
  27464. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27465. // Will be used to save a source mesh reference, If any
  27466. _this._source = null;
  27467. scene = _this.getScene();
  27468. if (source) {
  27469. // Source mesh
  27470. _this._source = source;
  27471. // Geometry
  27472. if (source._geometry) {
  27473. source._geometry.applyToMesh(_this);
  27474. }
  27475. // Deep copy
  27476. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27477. // Metadata
  27478. if (source.metadata && source.metadata.clone) {
  27479. _this.metadata = source.metadata.clone();
  27480. }
  27481. else {
  27482. _this.metadata = source.metadata;
  27483. }
  27484. // Tags
  27485. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27486. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27487. }
  27488. // Parent
  27489. _this.parent = source.parent;
  27490. // Pivot
  27491. _this.setPivotMatrix(source.getPivotMatrix());
  27492. _this.id = name + "." + source.id;
  27493. // Material
  27494. _this.material = source.material;
  27495. var index;
  27496. if (!doNotCloneChildren) {
  27497. // Children
  27498. var directDescendants = source.getDescendants(true);
  27499. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27500. var child = directDescendants[index_1];
  27501. if (child.clone) {
  27502. child.clone(name + "." + child.name, _this);
  27503. }
  27504. }
  27505. }
  27506. // Physics clone
  27507. var physicsEngine = _this.getScene().getPhysicsEngine();
  27508. if (clonePhysicsImpostor && physicsEngine) {
  27509. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27510. if (impostor) {
  27511. _this.physicsImpostor = impostor.clone(_this);
  27512. }
  27513. }
  27514. // Particles
  27515. for (index = 0; index < scene.particleSystems.length; index++) {
  27516. var system = scene.particleSystems[index];
  27517. if (system.emitter === source) {
  27518. system.clone(system.name, _this);
  27519. }
  27520. }
  27521. _this.computeWorldMatrix(true);
  27522. }
  27523. // Parent
  27524. if (parent !== null) {
  27525. _this.parent = parent;
  27526. }
  27527. return _this;
  27528. }
  27529. Object.defineProperty(Mesh, "FRONTSIDE", {
  27530. /**
  27531. * Mesh side orientation : usually the external or front surface
  27532. */
  27533. get: function () {
  27534. return Mesh._FRONTSIDE;
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. Object.defineProperty(Mesh, "BACKSIDE", {
  27540. /**
  27541. * Mesh side orientation : usually the internal or back surface
  27542. */
  27543. get: function () {
  27544. return Mesh._BACKSIDE;
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27550. /**
  27551. * Mesh side orientation : both internal and external or front and back surfaces
  27552. */
  27553. get: function () {
  27554. return Mesh._DOUBLESIDE;
  27555. },
  27556. enumerable: true,
  27557. configurable: true
  27558. });
  27559. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27560. /**
  27561. * Mesh side orientation : by default, `FRONTSIDE`
  27562. */
  27563. get: function () {
  27564. return Mesh._DEFAULTSIDE;
  27565. },
  27566. enumerable: true,
  27567. configurable: true
  27568. });
  27569. Object.defineProperty(Mesh, "NO_CAP", {
  27570. /**
  27571. * Mesh cap setting : no cap
  27572. */
  27573. get: function () {
  27574. return Mesh._NO_CAP;
  27575. },
  27576. enumerable: true,
  27577. configurable: true
  27578. });
  27579. Object.defineProperty(Mesh, "CAP_START", {
  27580. /**
  27581. * Mesh cap setting : one cap at the beginning of the mesh
  27582. */
  27583. get: function () {
  27584. return Mesh._CAP_START;
  27585. },
  27586. enumerable: true,
  27587. configurable: true
  27588. });
  27589. Object.defineProperty(Mesh, "CAP_END", {
  27590. /**
  27591. * Mesh cap setting : one cap at the end of the mesh
  27592. */
  27593. get: function () {
  27594. return Mesh._CAP_END;
  27595. },
  27596. enumerable: true,
  27597. configurable: true
  27598. });
  27599. Object.defineProperty(Mesh, "CAP_ALL", {
  27600. /**
  27601. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27602. */
  27603. get: function () {
  27604. return Mesh._CAP_ALL;
  27605. },
  27606. enumerable: true,
  27607. configurable: true
  27608. });
  27609. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27610. set: function (callback) {
  27611. if (this._onBeforeDrawObserver) {
  27612. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27613. }
  27614. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27620. get: function () {
  27621. return this._morphTargetManager;
  27622. },
  27623. set: function (value) {
  27624. if (this._morphTargetManager === value) {
  27625. return;
  27626. }
  27627. this._morphTargetManager = value;
  27628. this._syncGeometryWithMorphTargetManager();
  27629. },
  27630. enumerable: true,
  27631. configurable: true
  27632. });
  27633. Object.defineProperty(Mesh.prototype, "source", {
  27634. get: function () {
  27635. return this._source;
  27636. },
  27637. enumerable: true,
  27638. configurable: true
  27639. });
  27640. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27641. get: function () {
  27642. return this._unIndexed;
  27643. },
  27644. set: function (value) {
  27645. if (this._unIndexed !== value) {
  27646. this._unIndexed = value;
  27647. this._markSubMeshesAsAttributesDirty();
  27648. }
  27649. },
  27650. enumerable: true,
  27651. configurable: true
  27652. });
  27653. // Methods
  27654. /**
  27655. * Returns the string "Mesh".
  27656. */
  27657. Mesh.prototype.getClassName = function () {
  27658. return "Mesh";
  27659. };
  27660. /**
  27661. * Returns a string.
  27662. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27663. */
  27664. Mesh.prototype.toString = function (fullDetails) {
  27665. var ret = _super.prototype.toString.call(this, fullDetails);
  27666. ret += ", n vertices: " + this.getTotalVertices();
  27667. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27668. if (this.animations) {
  27669. for (var i = 0; i < this.animations.length; i++) {
  27670. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27671. }
  27672. }
  27673. if (fullDetails) {
  27674. if (this._geometry) {
  27675. var ib = this.getIndices();
  27676. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27677. if (vb && ib) {
  27678. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27679. }
  27680. }
  27681. else {
  27682. ret += ", flat shading: UNKNOWN";
  27683. }
  27684. }
  27685. return ret;
  27686. };
  27687. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27688. /**
  27689. * True if the mesh has some Levels Of Details (LOD).
  27690. * Returns a boolean.
  27691. */
  27692. get: function () {
  27693. return this._LODLevels.length > 0;
  27694. },
  27695. enumerable: true,
  27696. configurable: true
  27697. });
  27698. /**
  27699. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27700. * @returns an array of {BABYLON.MeshLODLevel}
  27701. */
  27702. Mesh.prototype.getLODLevels = function () {
  27703. return this._LODLevels;
  27704. };
  27705. Mesh.prototype._sortLODLevels = function () {
  27706. this._LODLevels.sort(function (a, b) {
  27707. if (a.distance < b.distance) {
  27708. return 1;
  27709. }
  27710. if (a.distance > b.distance) {
  27711. return -1;
  27712. }
  27713. return 0;
  27714. });
  27715. };
  27716. /**
  27717. * Add a mesh as LOD level triggered at the given distance.
  27718. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27719. * @param {number} distance The distance from the center of the object to show this level
  27720. * @param {Mesh} mesh The mesh to be added as LOD level
  27721. * @return {Mesh} This mesh (for chaining)
  27722. */
  27723. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27724. if (mesh && mesh._masterMesh) {
  27725. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27726. return this;
  27727. }
  27728. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27729. this._LODLevels.push(level);
  27730. if (mesh) {
  27731. mesh._masterMesh = this;
  27732. }
  27733. this._sortLODLevels();
  27734. return this;
  27735. };
  27736. /**
  27737. * Returns the LOD level mesh at the passed distance or null if not found.
  27738. * It is related to the method `addLODLevel(distance, mesh)`.
  27739. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27740. * Returns an object Mesh or `null`.
  27741. */
  27742. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27743. for (var index = 0; index < this._LODLevels.length; index++) {
  27744. var level = this._LODLevels[index];
  27745. if (level.distance === distance) {
  27746. return level.mesh;
  27747. }
  27748. }
  27749. return null;
  27750. };
  27751. /**
  27752. * Remove a mesh from the LOD array
  27753. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27754. * @param {Mesh} mesh The mesh to be removed.
  27755. * @return {Mesh} This mesh (for chaining)
  27756. */
  27757. Mesh.prototype.removeLODLevel = function (mesh) {
  27758. for (var index = 0; index < this._LODLevels.length; index++) {
  27759. if (this._LODLevels[index].mesh === mesh) {
  27760. this._LODLevels.splice(index, 1);
  27761. if (mesh) {
  27762. mesh._masterMesh = null;
  27763. }
  27764. }
  27765. }
  27766. this._sortLODLevels();
  27767. return this;
  27768. };
  27769. /**
  27770. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27771. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27772. */
  27773. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27774. if (!this._LODLevels || this._LODLevels.length === 0) {
  27775. return this;
  27776. }
  27777. var bSphere;
  27778. if (boundingSphere) {
  27779. bSphere = boundingSphere;
  27780. }
  27781. else {
  27782. var boundingInfo = this.getBoundingInfo();
  27783. bSphere = boundingInfo.boundingSphere;
  27784. }
  27785. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27786. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27787. if (this.onLODLevelSelection) {
  27788. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27789. }
  27790. return this;
  27791. }
  27792. for (var index = 0; index < this._LODLevels.length; index++) {
  27793. var level = this._LODLevels[index];
  27794. if (level.distance < distanceToCamera) {
  27795. if (level.mesh) {
  27796. level.mesh._preActivate();
  27797. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27798. }
  27799. if (this.onLODLevelSelection) {
  27800. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27801. }
  27802. return level.mesh;
  27803. }
  27804. }
  27805. if (this.onLODLevelSelection) {
  27806. this.onLODLevelSelection(distanceToCamera, this, this);
  27807. }
  27808. return this;
  27809. };
  27810. Object.defineProperty(Mesh.prototype, "geometry", {
  27811. /**
  27812. * Returns the mesh internal Geometry object.
  27813. */
  27814. get: function () {
  27815. return this._geometry;
  27816. },
  27817. enumerable: true,
  27818. configurable: true
  27819. });
  27820. /**
  27821. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27822. */
  27823. Mesh.prototype.getTotalVertices = function () {
  27824. if (this._geometry === null || this._geometry === undefined) {
  27825. return 0;
  27826. }
  27827. return this._geometry.getTotalVertices();
  27828. };
  27829. /**
  27830. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27831. * 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.
  27832. * You can force the copy with forceCopy === true
  27833. * Returns null if the mesh has no geometry or no vertex buffer.
  27834. * Possible `kind` values :
  27835. * - BABYLON.VertexBuffer.PositionKind
  27836. * - BABYLON.VertexBuffer.UVKind
  27837. * - BABYLON.VertexBuffer.UV2Kind
  27838. * - BABYLON.VertexBuffer.UV3Kind
  27839. * - BABYLON.VertexBuffer.UV4Kind
  27840. * - BABYLON.VertexBuffer.UV5Kind
  27841. * - BABYLON.VertexBuffer.UV6Kind
  27842. * - BABYLON.VertexBuffer.ColorKind
  27843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27847. */
  27848. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27849. if (!this._geometry) {
  27850. return null;
  27851. }
  27852. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27853. };
  27854. /**
  27855. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27856. * Returns `null` if the mesh has no geometry.
  27857. * Possible `kind` values :
  27858. * - BABYLON.VertexBuffer.PositionKind
  27859. * - BABYLON.VertexBuffer.UVKind
  27860. * - BABYLON.VertexBuffer.UV2Kind
  27861. * - BABYLON.VertexBuffer.UV3Kind
  27862. * - BABYLON.VertexBuffer.UV4Kind
  27863. * - BABYLON.VertexBuffer.UV5Kind
  27864. * - BABYLON.VertexBuffer.UV6Kind
  27865. * - BABYLON.VertexBuffer.ColorKind
  27866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27870. */
  27871. Mesh.prototype.getVertexBuffer = function (kind) {
  27872. if (!this._geometry) {
  27873. return null;
  27874. }
  27875. return this._geometry.getVertexBuffer(kind);
  27876. };
  27877. /**
  27878. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27879. * Possible `kind` values :
  27880. * - BABYLON.VertexBuffer.PositionKind
  27881. * - BABYLON.VertexBuffer.UVKind
  27882. * - BABYLON.VertexBuffer.UV2Kind
  27883. * - BABYLON.VertexBuffer.UV3Kind
  27884. * - BABYLON.VertexBuffer.UV4Kind
  27885. * - BABYLON.VertexBuffer.UV5Kind
  27886. * - BABYLON.VertexBuffer.UV6Kind
  27887. * - BABYLON.VertexBuffer.ColorKind
  27888. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27889. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27890. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27891. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27892. */
  27893. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27894. if (!this._geometry) {
  27895. if (this._delayInfo) {
  27896. return this._delayInfo.indexOf(kind) !== -1;
  27897. }
  27898. return false;
  27899. }
  27900. return this._geometry.isVerticesDataPresent(kind);
  27901. };
  27902. /**
  27903. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27904. * Possible `kind` values :
  27905. * - BABYLON.VertexBuffer.PositionKind
  27906. * - BABYLON.VertexBuffer.UVKind
  27907. * - BABYLON.VertexBuffer.UV2Kind
  27908. * - BABYLON.VertexBuffer.UV3Kind
  27909. * - BABYLON.VertexBuffer.UV4Kind
  27910. * - BABYLON.VertexBuffer.UV5Kind
  27911. * - BABYLON.VertexBuffer.UV6Kind
  27912. * - BABYLON.VertexBuffer.ColorKind
  27913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27917. */
  27918. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27919. if (!this._geometry) {
  27920. if (this._delayInfo) {
  27921. return this._delayInfo.indexOf(kind) !== -1;
  27922. }
  27923. return false;
  27924. }
  27925. return this._geometry.isVertexBufferUpdatable(kind);
  27926. };
  27927. /**
  27928. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27929. * Possible `kind` values :
  27930. * - BABYLON.VertexBuffer.PositionKind
  27931. * - BABYLON.VertexBuffer.UVKind
  27932. * - BABYLON.VertexBuffer.UV2Kind
  27933. * - BABYLON.VertexBuffer.UV3Kind
  27934. * - BABYLON.VertexBuffer.UV4Kind
  27935. * - BABYLON.VertexBuffer.UV5Kind
  27936. * - BABYLON.VertexBuffer.UV6Kind
  27937. * - BABYLON.VertexBuffer.ColorKind
  27938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27942. */
  27943. Mesh.prototype.getVerticesDataKinds = function () {
  27944. if (!this._geometry) {
  27945. var result = new Array();
  27946. if (this._delayInfo) {
  27947. this._delayInfo.forEach(function (kind, index, array) {
  27948. result.push(kind);
  27949. });
  27950. }
  27951. return result;
  27952. }
  27953. return this._geometry.getVerticesDataKinds();
  27954. };
  27955. /**
  27956. * Returns a positive integer : the total number of indices in this mesh geometry.
  27957. * Returns zero if the mesh has no geometry.
  27958. */
  27959. Mesh.prototype.getTotalIndices = function () {
  27960. if (!this._geometry) {
  27961. return 0;
  27962. }
  27963. return this._geometry.getTotalIndices();
  27964. };
  27965. /**
  27966. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27967. * 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.
  27968. * Returns an empty array if the mesh has no geometry.
  27969. */
  27970. Mesh.prototype.getIndices = function (copyWhenShared) {
  27971. if (!this._geometry) {
  27972. return [];
  27973. }
  27974. return this._geometry.getIndices(copyWhenShared);
  27975. };
  27976. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27977. get: function () {
  27978. return this._masterMesh !== null && this._masterMesh !== undefined;
  27979. },
  27980. enumerable: true,
  27981. configurable: true
  27982. });
  27983. /**
  27984. * Determine if the current mesh is ready to be rendered
  27985. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27986. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27987. * @returns true if all associated assets are ready (material, textures, shaders)
  27988. */
  27989. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27990. if (completeCheck === void 0) { completeCheck = false; }
  27991. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27992. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27993. return false;
  27994. }
  27995. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27996. return false;
  27997. }
  27998. if (!this.subMeshes || this.subMeshes.length === 0) {
  27999. return true;
  28000. }
  28001. if (!completeCheck) {
  28002. return true;
  28003. }
  28004. var engine = this.getEngine();
  28005. var scene = this.getScene();
  28006. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28007. this.computeWorldMatrix();
  28008. var mat = this.material || scene.defaultMaterial;
  28009. if (mat) {
  28010. if (mat.storeEffectOnSubMeshes) {
  28011. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28012. var subMesh = _a[_i];
  28013. var effectiveMaterial = subMesh.getMaterial();
  28014. if (effectiveMaterial) {
  28015. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28016. return false;
  28017. }
  28018. }
  28019. }
  28020. }
  28021. else {
  28022. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28023. return false;
  28024. }
  28025. }
  28026. }
  28027. // Shadows
  28028. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28029. var light = _c[_b];
  28030. var generator = light.getShadowGenerator();
  28031. if (generator) {
  28032. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28033. var subMesh = _e[_d];
  28034. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28035. return false;
  28036. }
  28037. }
  28038. }
  28039. }
  28040. // LOD
  28041. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28042. var lod = _g[_f];
  28043. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28044. return false;
  28045. }
  28046. }
  28047. return true;
  28048. };
  28049. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28050. /**
  28051. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28052. * This property is pertinent only for updatable parametric shapes.
  28053. */
  28054. get: function () {
  28055. return this._areNormalsFrozen;
  28056. },
  28057. enumerable: true,
  28058. configurable: true
  28059. });
  28060. /**
  28061. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28062. * It has no effect at all on other shapes.
  28063. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28064. * Returns the Mesh.
  28065. */
  28066. Mesh.prototype.freezeNormals = function () {
  28067. this._areNormalsFrozen = true;
  28068. return this;
  28069. };
  28070. /**
  28071. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28072. * It has no effect at all on other shapes.
  28073. * It reactivates the mesh normals computation if it was previously frozen.
  28074. * Returns the Mesh.
  28075. */
  28076. Mesh.prototype.unfreezeNormals = function () {
  28077. this._areNormalsFrozen = false;
  28078. return this;
  28079. };
  28080. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28081. /**
  28082. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28083. */
  28084. set: function (count) {
  28085. this._overridenInstanceCount = count;
  28086. },
  28087. enumerable: true,
  28088. configurable: true
  28089. });
  28090. // Methods
  28091. Mesh.prototype._preActivate = function () {
  28092. var sceneRenderId = this.getScene().getRenderId();
  28093. if (this._preActivateId === sceneRenderId) {
  28094. return this;
  28095. }
  28096. this._preActivateId = sceneRenderId;
  28097. this._visibleInstances = null;
  28098. return this;
  28099. };
  28100. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28101. if (this._visibleInstances) {
  28102. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28103. }
  28104. return this;
  28105. };
  28106. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28107. if (!this._visibleInstances) {
  28108. this._visibleInstances = {};
  28109. this._visibleInstances.defaultRenderId = renderId;
  28110. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28111. }
  28112. if (!this._visibleInstances[renderId]) {
  28113. this._visibleInstances[renderId] = new Array();
  28114. }
  28115. this._visibleInstances[renderId].push(instance);
  28116. return this;
  28117. };
  28118. /**
  28119. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28120. * This means the mesh underlying bounding box and sphere are recomputed.
  28121. * Returns the Mesh.
  28122. */
  28123. Mesh.prototype.refreshBoundingInfo = function () {
  28124. return this._refreshBoundingInfo(false);
  28125. };
  28126. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28127. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28128. return this;
  28129. }
  28130. var data = this._getPositionData(applySkeleton);
  28131. if (data) {
  28132. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28133. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28134. }
  28135. if (this.subMeshes) {
  28136. for (var index = 0; index < this.subMeshes.length; index++) {
  28137. this.subMeshes[index].refreshBoundingInfo();
  28138. }
  28139. }
  28140. this._updateBoundingInfo();
  28141. return this;
  28142. };
  28143. Mesh.prototype._getPositionData = function (applySkeleton) {
  28144. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28145. if (data && applySkeleton && this.skeleton) {
  28146. data = BABYLON.Tools.Slice(data);
  28147. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28148. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28149. if (matricesWeightsData && matricesIndicesData) {
  28150. var needExtras = this.numBoneInfluencers > 4;
  28151. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28152. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28153. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28154. var tempVector = BABYLON.Tmp.Vector3[0];
  28155. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28156. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28157. var matWeightIdx = 0;
  28158. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28159. finalMatrix.reset();
  28160. var inf;
  28161. var weight;
  28162. for (inf = 0; inf < 4; inf++) {
  28163. weight = matricesWeightsData[matWeightIdx + inf];
  28164. if (weight <= 0)
  28165. break;
  28166. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28167. finalMatrix.addToSelf(tempMatrix);
  28168. }
  28169. if (needExtras) {
  28170. for (inf = 0; inf < 4; inf++) {
  28171. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28172. if (weight <= 0)
  28173. break;
  28174. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28175. finalMatrix.addToSelf(tempMatrix);
  28176. }
  28177. }
  28178. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28179. tempVector.toArray(data, index);
  28180. }
  28181. }
  28182. }
  28183. return data;
  28184. };
  28185. Mesh.prototype._createGlobalSubMesh = function (force) {
  28186. var totalVertices = this.getTotalVertices();
  28187. if (!totalVertices || !this.getIndices()) {
  28188. return null;
  28189. }
  28190. // Check if we need to recreate the submeshes
  28191. if (this.subMeshes && this.subMeshes.length > 0) {
  28192. var ib = this.getIndices();
  28193. if (!ib) {
  28194. return null;
  28195. }
  28196. var totalIndices = ib.length;
  28197. var needToRecreate = false;
  28198. if (force) {
  28199. needToRecreate = true;
  28200. }
  28201. else {
  28202. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28203. var submesh = _a[_i];
  28204. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28205. needToRecreate = true;
  28206. break;
  28207. }
  28208. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28209. needToRecreate = true;
  28210. break;
  28211. }
  28212. }
  28213. }
  28214. if (!needToRecreate) {
  28215. return this.subMeshes[0];
  28216. }
  28217. }
  28218. this.releaseSubMeshes();
  28219. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28220. };
  28221. Mesh.prototype.subdivide = function (count) {
  28222. if (count < 1) {
  28223. return;
  28224. }
  28225. var totalIndices = this.getTotalIndices();
  28226. var subdivisionSize = (totalIndices / count) | 0;
  28227. var offset = 0;
  28228. // Ensure that subdivisionSize is a multiple of 3
  28229. while (subdivisionSize % 3 !== 0) {
  28230. subdivisionSize++;
  28231. }
  28232. this.releaseSubMeshes();
  28233. for (var index = 0; index < count; index++) {
  28234. if (offset >= totalIndices) {
  28235. break;
  28236. }
  28237. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28238. offset += subdivisionSize;
  28239. }
  28240. this.synchronizeInstances();
  28241. };
  28242. /**
  28243. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28244. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28245. * The `data` are either a numeric array either a Float32Array.
  28246. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28247. * 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).
  28248. * Note that a new underlying VertexBuffer object is created each call.
  28249. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28250. *
  28251. * Possible `kind` values :
  28252. * - BABYLON.VertexBuffer.PositionKind
  28253. * - BABYLON.VertexBuffer.UVKind
  28254. * - BABYLON.VertexBuffer.UV2Kind
  28255. * - BABYLON.VertexBuffer.UV3Kind
  28256. * - BABYLON.VertexBuffer.UV4Kind
  28257. * - BABYLON.VertexBuffer.UV5Kind
  28258. * - BABYLON.VertexBuffer.UV6Kind
  28259. * - BABYLON.VertexBuffer.ColorKind
  28260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28264. *
  28265. * Returns the Mesh.
  28266. */
  28267. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28268. if (updatable === void 0) { updatable = false; }
  28269. if (!this._geometry) {
  28270. var vertexData = new BABYLON.VertexData();
  28271. vertexData.set(data, kind);
  28272. var scene = this.getScene();
  28273. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28274. }
  28275. else {
  28276. this._geometry.setVerticesData(kind, data, updatable, stride);
  28277. }
  28278. return this;
  28279. };
  28280. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28281. if (updatable === void 0) { updatable = true; }
  28282. var vb = this.getVertexBuffer(kind);
  28283. if (!vb || vb.isUpdatable() === updatable) {
  28284. return;
  28285. }
  28286. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28287. };
  28288. /**
  28289. * Sets the mesh VertexBuffer.
  28290. * Returns the Mesh.
  28291. */
  28292. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28293. if (!this._geometry) {
  28294. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28295. }
  28296. this._geometry.setVerticesBuffer(buffer);
  28297. return this;
  28298. };
  28299. /**
  28300. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28301. * If the mesh has no geometry, it is simply returned as it is.
  28302. * The `data` are either a numeric array either a Float32Array.
  28303. * No new underlying VertexBuffer object is created.
  28304. * 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.
  28305. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28306. *
  28307. * Possible `kind` values :
  28308. * - BABYLON.VertexBuffer.PositionKind
  28309. * - BABYLON.VertexBuffer.UVKind
  28310. * - BABYLON.VertexBuffer.UV2Kind
  28311. * - BABYLON.VertexBuffer.UV3Kind
  28312. * - BABYLON.VertexBuffer.UV4Kind
  28313. * - BABYLON.VertexBuffer.UV5Kind
  28314. * - BABYLON.VertexBuffer.UV6Kind
  28315. * - BABYLON.VertexBuffer.ColorKind
  28316. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28317. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28318. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28319. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28320. *
  28321. * Returns the Mesh.
  28322. */
  28323. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28324. if (!this._geometry) {
  28325. return this;
  28326. }
  28327. if (!makeItUnique) {
  28328. this._geometry.updateVerticesData(kind, data, updateExtends);
  28329. }
  28330. else {
  28331. this.makeGeometryUnique();
  28332. this.updateVerticesData(kind, data, updateExtends, false);
  28333. }
  28334. return this;
  28335. };
  28336. /**
  28337. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28338. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28339. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28340. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28341. * Returns the Mesh.
  28342. */
  28343. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28344. if (computeNormals === void 0) { computeNormals = true; }
  28345. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28346. if (!positions) {
  28347. return this;
  28348. }
  28349. positionFunction(positions);
  28350. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28351. if (computeNormals) {
  28352. var indices = this.getIndices();
  28353. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28354. if (!normals) {
  28355. return this;
  28356. }
  28357. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28358. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28359. }
  28360. return this;
  28361. };
  28362. /**
  28363. * Creates a un-shared specific occurence of the geometry for the mesh.
  28364. * Returns the Mesh.
  28365. */
  28366. Mesh.prototype.makeGeometryUnique = function () {
  28367. if (!this._geometry) {
  28368. return this;
  28369. }
  28370. var oldGeometry = this._geometry;
  28371. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28372. oldGeometry.releaseForMesh(this, true);
  28373. geometry.applyToMesh(this);
  28374. return this;
  28375. };
  28376. /**
  28377. * Sets the mesh indices.
  28378. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28379. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28380. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28381. * This method creates a new index buffer each call.
  28382. * Returns the Mesh.
  28383. */
  28384. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28385. if (totalVertices === void 0) { totalVertices = null; }
  28386. if (updatable === void 0) { updatable = false; }
  28387. if (!this._geometry) {
  28388. var vertexData = new BABYLON.VertexData();
  28389. vertexData.indices = indices;
  28390. var scene = this.getScene();
  28391. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28392. }
  28393. else {
  28394. this._geometry.setIndices(indices, totalVertices, updatable);
  28395. }
  28396. return this;
  28397. };
  28398. /**
  28399. * Update the current index buffer
  28400. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28401. * Returns the Mesh.
  28402. */
  28403. Mesh.prototype.updateIndices = function (indices, offset) {
  28404. if (!this._geometry) {
  28405. return this;
  28406. }
  28407. this._geometry.updateIndices(indices, offset);
  28408. return this;
  28409. };
  28410. /**
  28411. * Invert the geometry to move from a right handed system to a left handed one.
  28412. * Returns the Mesh.
  28413. */
  28414. Mesh.prototype.toLeftHanded = function () {
  28415. if (!this._geometry) {
  28416. return this;
  28417. }
  28418. this._geometry.toLeftHanded();
  28419. return this;
  28420. };
  28421. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28422. if (!this._geometry) {
  28423. return this;
  28424. }
  28425. var engine = this.getScene().getEngine();
  28426. // Wireframe
  28427. var indexToBind;
  28428. if (this._unIndexed) {
  28429. indexToBind = null;
  28430. }
  28431. else {
  28432. switch (fillMode) {
  28433. case BABYLON.Material.PointFillMode:
  28434. indexToBind = null;
  28435. break;
  28436. case BABYLON.Material.WireFrameFillMode:
  28437. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28438. break;
  28439. default:
  28440. case BABYLON.Material.TriangleFillMode:
  28441. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28442. break;
  28443. }
  28444. }
  28445. // VBOs
  28446. this._geometry._bind(effect, indexToBind);
  28447. return this;
  28448. };
  28449. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28450. if (alternate === void 0) { alternate = false; }
  28451. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28452. return this;
  28453. }
  28454. this.onBeforeDrawObservable.notifyObservers(this);
  28455. var scene = this.getScene();
  28456. var engine = scene.getEngine();
  28457. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28458. // or triangles as points
  28459. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28460. }
  28461. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28462. // Triangles as wireframe
  28463. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28464. }
  28465. else {
  28466. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28467. }
  28468. if (scene._isAlternateRenderingEnabled && !alternate) {
  28469. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28470. if (!effect || !scene.activeCamera) {
  28471. return this;
  28472. }
  28473. scene._switchToAlternateCameraConfiguration(true);
  28474. this._effectiveMaterial.bindView(effect);
  28475. this._effectiveMaterial.bindViewProjection(effect);
  28476. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28477. this._draw(subMesh, fillMode, instancesCount, true);
  28478. engine.setViewport(scene.activeCamera.viewport);
  28479. scene._switchToAlternateCameraConfiguration(false);
  28480. this._effectiveMaterial.bindView(effect);
  28481. this._effectiveMaterial.bindViewProjection(effect);
  28482. }
  28483. return this;
  28484. };
  28485. /**
  28486. * Registers for this mesh a javascript function called just before the rendering process.
  28487. * This function is passed the current mesh.
  28488. * Return the Mesh.
  28489. */
  28490. Mesh.prototype.registerBeforeRender = function (func) {
  28491. this.onBeforeRenderObservable.add(func);
  28492. return this;
  28493. };
  28494. /**
  28495. * Disposes a previously registered javascript function called before the rendering.
  28496. * This function is passed the current mesh.
  28497. * Returns the Mesh.
  28498. */
  28499. Mesh.prototype.unregisterBeforeRender = function (func) {
  28500. this.onBeforeRenderObservable.removeCallback(func);
  28501. return this;
  28502. };
  28503. /**
  28504. * Registers for this mesh a javascript function called just after the rendering is complete.
  28505. * This function is passed the current mesh.
  28506. * Returns the Mesh.
  28507. */
  28508. Mesh.prototype.registerAfterRender = function (func) {
  28509. this.onAfterRenderObservable.add(func);
  28510. return this;
  28511. };
  28512. /**
  28513. * Disposes a previously registered javascript function called after the rendering.
  28514. * This function is passed the current mesh.
  28515. * Return the Mesh.
  28516. */
  28517. Mesh.prototype.unregisterAfterRender = function (func) {
  28518. this.onAfterRenderObservable.removeCallback(func);
  28519. return this;
  28520. };
  28521. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28522. var scene = this.getScene();
  28523. this._batchCache.mustReturn = false;
  28524. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28525. this._batchCache.visibleInstances[subMeshId] = null;
  28526. if (this._visibleInstances) {
  28527. var currentRenderId = scene.getRenderId();
  28528. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28529. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28530. var selfRenderId = this._renderId;
  28531. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28532. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28533. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28534. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28535. }
  28536. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28537. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28538. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28539. this._batchCache.mustReturn = true;
  28540. return this._batchCache;
  28541. }
  28542. if (currentRenderId !== selfRenderId) {
  28543. this._batchCache.renderSelf[subMeshId] = false;
  28544. }
  28545. }
  28546. this._renderIdForInstances[subMeshId] = currentRenderId;
  28547. }
  28548. return this._batchCache;
  28549. };
  28550. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28551. var visibleInstances = batch.visibleInstances[subMesh._id];
  28552. if (!visibleInstances) {
  28553. return this;
  28554. }
  28555. var matricesCount = visibleInstances.length + 1;
  28556. var bufferSize = matricesCount * 16 * 4;
  28557. var currentInstancesBufferSize = this._instancesBufferSize;
  28558. var instancesBuffer = this._instancesBuffer;
  28559. while (this._instancesBufferSize < bufferSize) {
  28560. this._instancesBufferSize *= 2;
  28561. }
  28562. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28563. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28564. }
  28565. var offset = 0;
  28566. var instancesCount = 0;
  28567. var world = this.getWorldMatrix();
  28568. if (batch.renderSelf[subMesh._id]) {
  28569. world.copyToArray(this._instancesData, offset);
  28570. offset += 16;
  28571. instancesCount++;
  28572. }
  28573. if (visibleInstances) {
  28574. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28575. var instance = visibleInstances[instanceIndex];
  28576. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28577. offset += 16;
  28578. instancesCount++;
  28579. }
  28580. }
  28581. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28582. if (instancesBuffer) {
  28583. instancesBuffer.dispose();
  28584. }
  28585. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28586. this._instancesBuffer = instancesBuffer;
  28587. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28588. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28589. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28590. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28591. }
  28592. else {
  28593. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28594. }
  28595. this._bind(subMesh, effect, fillMode);
  28596. this._draw(subMesh, fillMode, instancesCount);
  28597. engine.unbindInstanceAttributes();
  28598. return this;
  28599. };
  28600. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28601. var scene = this.getScene();
  28602. var engine = scene.getEngine();
  28603. if (hardwareInstancedRendering) {
  28604. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28605. }
  28606. else {
  28607. if (batch.renderSelf[subMesh._id]) {
  28608. // Draw
  28609. if (onBeforeDraw) {
  28610. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28611. }
  28612. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28613. }
  28614. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28615. if (visibleInstancesForSubMesh) {
  28616. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28617. var instance = visibleInstancesForSubMesh[instanceIndex];
  28618. // World
  28619. var world = instance.getWorldMatrix();
  28620. if (onBeforeDraw) {
  28621. onBeforeDraw(true, world, effectiveMaterial);
  28622. }
  28623. // Draw
  28624. this._draw(subMesh, fillMode);
  28625. }
  28626. }
  28627. }
  28628. return this;
  28629. };
  28630. /**
  28631. * Triggers the draw call for the mesh.
  28632. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28633. * Returns the Mesh.
  28634. */
  28635. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28636. this.checkOcclusionQuery();
  28637. if (this._isOccluded) {
  28638. return this;
  28639. }
  28640. var scene = this.getScene();
  28641. // Managing instances
  28642. var batch = this._getInstancesRenderList(subMesh._id);
  28643. if (batch.mustReturn) {
  28644. return this;
  28645. }
  28646. // Checking geometry state
  28647. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28648. return this;
  28649. }
  28650. this.onBeforeRenderObservable.notifyObservers(this);
  28651. var engine = scene.getEngine();
  28652. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28653. // Material
  28654. var material = subMesh.getMaterial();
  28655. if (!material) {
  28656. return this;
  28657. }
  28658. this._effectiveMaterial = material;
  28659. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28660. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28661. return this;
  28662. }
  28663. }
  28664. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28665. return this;
  28666. }
  28667. // Alpha mode
  28668. if (enableAlphaMode) {
  28669. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28670. }
  28671. // Outline - step 1
  28672. var savedDepthWrite = engine.getDepthWrite();
  28673. if (this.renderOutline) {
  28674. engine.setDepthWrite(false);
  28675. scene.getOutlineRenderer().render(subMesh, batch);
  28676. engine.setDepthWrite(savedDepthWrite);
  28677. }
  28678. var effect;
  28679. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28680. effect = subMesh.effect;
  28681. }
  28682. else {
  28683. effect = this._effectiveMaterial.getEffect();
  28684. }
  28685. if (!effect) {
  28686. return this;
  28687. }
  28688. var sideOrientation = this.overrideMaterialSideOrientation;
  28689. if (sideOrientation == null) {
  28690. sideOrientation = this._effectiveMaterial.sideOrientation;
  28691. if (this._getWorldMatrixDeterminant() < 0) {
  28692. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28693. }
  28694. }
  28695. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28696. if (this._effectiveMaterial.forceDepthWrite) {
  28697. engine.setDepthWrite(true);
  28698. }
  28699. // Bind
  28700. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28701. if (!hardwareInstancedRendering) {
  28702. this._bind(subMesh, effect, fillMode);
  28703. }
  28704. var world = this.getWorldMatrix();
  28705. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28706. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28707. }
  28708. else {
  28709. this._effectiveMaterial.bind(world, this);
  28710. }
  28711. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28712. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28713. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28714. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28715. }
  28716. // Draw
  28717. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28718. // Unbind
  28719. this._effectiveMaterial.unbind();
  28720. // Outline - step 2
  28721. if (this.renderOutline && savedDepthWrite) {
  28722. engine.setDepthWrite(true);
  28723. engine.setColorWrite(false);
  28724. scene.getOutlineRenderer().render(subMesh, batch);
  28725. engine.setColorWrite(true);
  28726. }
  28727. // Overlay
  28728. if (this.renderOverlay) {
  28729. var currentMode = engine.getAlphaMode();
  28730. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28731. scene.getOutlineRenderer().render(subMesh, batch, true);
  28732. engine.setAlphaMode(currentMode);
  28733. }
  28734. this.onAfterRenderObservable.notifyObservers(this);
  28735. return this;
  28736. };
  28737. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28738. if (isInstance && effectiveMaterial) {
  28739. effectiveMaterial.bindOnlyWorldMatrix(world);
  28740. }
  28741. };
  28742. /**
  28743. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28744. */
  28745. Mesh.prototype.getEmittedParticleSystems = function () {
  28746. var results = new Array();
  28747. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28748. var particleSystem = this.getScene().particleSystems[index];
  28749. if (particleSystem.emitter === this) {
  28750. results.push(particleSystem);
  28751. }
  28752. }
  28753. return results;
  28754. };
  28755. /**
  28756. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28757. */
  28758. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28759. var results = new Array();
  28760. var descendants = this.getDescendants();
  28761. descendants.push(this);
  28762. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28763. var particleSystem = this.getScene().particleSystems[index];
  28764. var emitter = particleSystem.emitter;
  28765. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28766. results.push(particleSystem);
  28767. }
  28768. }
  28769. return results;
  28770. };
  28771. Mesh.prototype._checkDelayState = function () {
  28772. var scene = this.getScene();
  28773. if (this._geometry) {
  28774. this._geometry.load(scene);
  28775. }
  28776. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28777. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28778. this._queueLoad(scene);
  28779. }
  28780. return this;
  28781. };
  28782. Mesh.prototype._queueLoad = function (scene) {
  28783. var _this = this;
  28784. scene._addPendingData(this);
  28785. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28786. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28787. if (data instanceof ArrayBuffer) {
  28788. _this._delayLoadingFunction(data, _this);
  28789. }
  28790. else {
  28791. _this._delayLoadingFunction(JSON.parse(data), _this);
  28792. }
  28793. _this.instances.forEach(function (instance) {
  28794. instance._syncSubMeshes();
  28795. });
  28796. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28797. scene._removePendingData(_this);
  28798. }, function () { }, scene.database, getBinaryData);
  28799. return this;
  28800. };
  28801. /**
  28802. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28803. */
  28804. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28805. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28806. return false;
  28807. }
  28808. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28809. return false;
  28810. }
  28811. this._checkDelayState();
  28812. return true;
  28813. };
  28814. /**
  28815. * Sets the mesh material by the material or multiMaterial `id` property.
  28816. * The material `id` is a string identifying the material or the multiMaterial.
  28817. * This method returns the Mesh.
  28818. */
  28819. Mesh.prototype.setMaterialByID = function (id) {
  28820. var materials = this.getScene().materials;
  28821. var index;
  28822. for (index = materials.length - 1; index > -1; index--) {
  28823. if (materials[index].id === id) {
  28824. this.material = materials[index];
  28825. return this;
  28826. }
  28827. }
  28828. // Multi
  28829. var multiMaterials = this.getScene().multiMaterials;
  28830. for (index = multiMaterials.length - 1; index > -1; index--) {
  28831. if (multiMaterials[index].id === id) {
  28832. this.material = multiMaterials[index];
  28833. return this;
  28834. }
  28835. }
  28836. return this;
  28837. };
  28838. /**
  28839. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28840. */
  28841. Mesh.prototype.getAnimatables = function () {
  28842. var results = new Array();
  28843. if (this.material) {
  28844. results.push(this.material);
  28845. }
  28846. if (this.skeleton) {
  28847. results.push(this.skeleton);
  28848. }
  28849. return results;
  28850. };
  28851. /**
  28852. * Modifies the mesh geometry according to the passed transformation matrix.
  28853. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28854. * The mesh normals are modified accordingly the same transformation.
  28855. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28856. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28857. * Returns the Mesh.
  28858. */
  28859. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28860. // Position
  28861. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28862. return this;
  28863. }
  28864. var submeshes = this.subMeshes.splice(0);
  28865. this._resetPointsArrayCache();
  28866. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28867. var temp = new Array();
  28868. var index;
  28869. for (index = 0; index < data.length; index += 3) {
  28870. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28871. }
  28872. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28873. // Normals
  28874. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28875. return this;
  28876. }
  28877. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28878. temp = [];
  28879. for (index = 0; index < data.length; index += 3) {
  28880. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28881. }
  28882. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28883. // flip faces?
  28884. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28885. this.flipFaces();
  28886. }
  28887. // Restore submeshes
  28888. this.releaseSubMeshes();
  28889. this.subMeshes = submeshes;
  28890. return this;
  28891. };
  28892. /**
  28893. * Modifies the mesh geometry according to its own current World Matrix.
  28894. * The mesh World Matrix is then reset.
  28895. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28896. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28897. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28898. * Returns the Mesh.
  28899. */
  28900. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28901. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28902. this.scaling.copyFromFloats(1, 1, 1);
  28903. this.position.copyFromFloats(0, 0, 0);
  28904. this.rotation.copyFromFloats(0, 0, 0);
  28905. //only if quaternion is already set
  28906. if (this.rotationQuaternion) {
  28907. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28908. }
  28909. this._worldMatrix = BABYLON.Matrix.Identity();
  28910. return this;
  28911. };
  28912. Object.defineProperty(Mesh.prototype, "_positions", {
  28913. // Cache
  28914. get: function () {
  28915. if (this._geometry) {
  28916. return this._geometry._positions;
  28917. }
  28918. return null;
  28919. },
  28920. enumerable: true,
  28921. configurable: true
  28922. });
  28923. Mesh.prototype._resetPointsArrayCache = function () {
  28924. if (this._geometry) {
  28925. this._geometry._resetPointsArrayCache();
  28926. }
  28927. return this;
  28928. };
  28929. Mesh.prototype._generatePointsArray = function () {
  28930. if (this._geometry) {
  28931. return this._geometry._generatePointsArray();
  28932. }
  28933. return false;
  28934. };
  28935. /**
  28936. * Returns a new Mesh object generated from the current mesh properties.
  28937. * This method must not get confused with createInstance().
  28938. * The parameter `name` is a string, the name given to the new mesh.
  28939. * The optional parameter `newParent` can be any Node object (default `null`).
  28940. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28941. * 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.
  28942. */
  28943. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28944. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28945. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28946. };
  28947. /**
  28948. * Releases resources associated with this mesh.
  28949. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28950. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28951. */
  28952. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28953. var _this = this;
  28954. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28955. this.morphTargetManager = null;
  28956. if (this._geometry) {
  28957. this._geometry.releaseForMesh(this, true);
  28958. }
  28959. // Sources
  28960. var meshes = this.getScene().meshes;
  28961. meshes.forEach(function (abstractMesh) {
  28962. var mesh = abstractMesh;
  28963. if (mesh._source && mesh._source === _this) {
  28964. mesh._source = null;
  28965. }
  28966. });
  28967. this._source = null;
  28968. // Instances
  28969. if (this._instancesBuffer) {
  28970. this._instancesBuffer.dispose();
  28971. this._instancesBuffer = null;
  28972. }
  28973. while (this.instances.length) {
  28974. this.instances[0].dispose();
  28975. }
  28976. // Effect layers.
  28977. var effectLayers = this.getScene().effectLayers;
  28978. for (var i = 0; i < effectLayers.length; i++) {
  28979. var effectLayer = effectLayers[i];
  28980. if (effectLayer) {
  28981. effectLayer._disposeMesh(this);
  28982. }
  28983. }
  28984. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28985. };
  28986. /**
  28987. * Modifies the mesh geometry according to a displacement map.
  28988. * 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.
  28989. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28990. * This method returns nothing.
  28991. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28992. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28993. * 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.
  28994. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28995. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28996. *
  28997. * Returns the Mesh.
  28998. */
  28999. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29000. var _this = this;
  29001. var scene = this.getScene();
  29002. var onload = function (img) {
  29003. // Getting height map data
  29004. var canvas = document.createElement("canvas");
  29005. var context = canvas.getContext("2d");
  29006. var heightMapWidth = img.width;
  29007. var heightMapHeight = img.height;
  29008. canvas.width = heightMapWidth;
  29009. canvas.height = heightMapHeight;
  29010. context.drawImage(img, 0, 0);
  29011. // Create VertexData from map data
  29012. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29013. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29014. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29015. //execute success callback, if set
  29016. if (onSuccess) {
  29017. onSuccess(_this);
  29018. }
  29019. };
  29020. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29021. return this;
  29022. };
  29023. /**
  29024. * Modifies the mesh geometry according to a displacementMap buffer.
  29025. * 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.
  29026. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29027. * This method returns nothing.
  29028. * 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.
  29029. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29030. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29031. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29032. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29033. *
  29034. * Returns the Mesh.
  29035. */
  29036. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29038. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29039. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29040. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29041. return this;
  29042. }
  29043. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29044. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29045. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29046. var position = BABYLON.Vector3.Zero();
  29047. var normal = BABYLON.Vector3.Zero();
  29048. var uv = BABYLON.Vector2.Zero();
  29049. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29050. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29051. for (var index = 0; index < positions.length; index += 3) {
  29052. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29053. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29054. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29055. // Compute height
  29056. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29057. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29058. var pos = (u + v * heightMapWidth) * 4;
  29059. var r = buffer[pos] / 255.0;
  29060. var g = buffer[pos + 1] / 255.0;
  29061. var b = buffer[pos + 2] / 255.0;
  29062. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29063. normal.normalize();
  29064. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29065. position = position.add(normal);
  29066. position.toArray(positions, index);
  29067. }
  29068. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29069. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29070. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29071. return this;
  29072. };
  29073. /**
  29074. * Modify the mesh to get a flat shading rendering.
  29075. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29076. * This method returns the Mesh.
  29077. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29078. */
  29079. Mesh.prototype.convertToFlatShadedMesh = function () {
  29080. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29081. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29082. var kinds = this.getVerticesDataKinds();
  29083. var vbs = {};
  29084. var data = {};
  29085. var newdata = {};
  29086. var updatableNormals = false;
  29087. var kindIndex;
  29088. var kind;
  29089. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29090. kind = kinds[kindIndex];
  29091. var vertexBuffer = this.getVertexBuffer(kind);
  29092. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29093. updatableNormals = vertexBuffer.isUpdatable();
  29094. kinds.splice(kindIndex, 1);
  29095. kindIndex--;
  29096. continue;
  29097. }
  29098. vbs[kind] = vertexBuffer;
  29099. data[kind] = vbs[kind].getData();
  29100. newdata[kind] = [];
  29101. }
  29102. // Save previous submeshes
  29103. var previousSubmeshes = this.subMeshes.slice(0);
  29104. var indices = this.getIndices();
  29105. var totalIndices = this.getTotalIndices();
  29106. // Generating unique vertices per face
  29107. var index;
  29108. for (index = 0; index < totalIndices; index++) {
  29109. var vertexIndex = indices[index];
  29110. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29111. kind = kinds[kindIndex];
  29112. var stride = vbs[kind].getStrideSize();
  29113. for (var offset = 0; offset < stride; offset++) {
  29114. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29115. }
  29116. }
  29117. }
  29118. // Updating faces & normal
  29119. var normals = [];
  29120. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29121. for (index = 0; index < totalIndices; index += 3) {
  29122. indices[index] = index;
  29123. indices[index + 1] = index + 1;
  29124. indices[index + 2] = index + 2;
  29125. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29126. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29127. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29128. var p1p2 = p1.subtract(p2);
  29129. var p3p2 = p3.subtract(p2);
  29130. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29131. // Store same normals for every vertex
  29132. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29133. normals.push(normal.x);
  29134. normals.push(normal.y);
  29135. normals.push(normal.z);
  29136. }
  29137. }
  29138. this.setIndices(indices);
  29139. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29140. // Updating vertex buffers
  29141. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29142. kind = kinds[kindIndex];
  29143. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29144. }
  29145. // Updating submeshes
  29146. this.releaseSubMeshes();
  29147. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29148. var previousOne = previousSubmeshes[submeshIndex];
  29149. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29150. }
  29151. this.synchronizeInstances();
  29152. return this;
  29153. };
  29154. /**
  29155. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29156. * In other words, more vertices, no more indices and a single bigger VBO.
  29157. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29158. * Returns the Mesh.
  29159. */
  29160. Mesh.prototype.convertToUnIndexedMesh = function () {
  29161. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29162. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29163. var kinds = this.getVerticesDataKinds();
  29164. var vbs = {};
  29165. var data = {};
  29166. var newdata = {};
  29167. var kindIndex;
  29168. var kind;
  29169. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29170. kind = kinds[kindIndex];
  29171. var vertexBuffer = this.getVertexBuffer(kind);
  29172. vbs[kind] = vertexBuffer;
  29173. data[kind] = vbs[kind].getData();
  29174. newdata[kind] = [];
  29175. }
  29176. // Save previous submeshes
  29177. var previousSubmeshes = this.subMeshes.slice(0);
  29178. var indices = this.getIndices();
  29179. var totalIndices = this.getTotalIndices();
  29180. // Generating unique vertices per face
  29181. var index;
  29182. for (index = 0; index < totalIndices; index++) {
  29183. var vertexIndex = indices[index];
  29184. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29185. kind = kinds[kindIndex];
  29186. var stride = vbs[kind].getStrideSize();
  29187. for (var offset = 0; offset < stride; offset++) {
  29188. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29189. }
  29190. }
  29191. }
  29192. // Updating indices
  29193. for (index = 0; index < totalIndices; index += 3) {
  29194. indices[index] = index;
  29195. indices[index + 1] = index + 1;
  29196. indices[index + 2] = index + 2;
  29197. }
  29198. this.setIndices(indices);
  29199. // Updating vertex buffers
  29200. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29201. kind = kinds[kindIndex];
  29202. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29203. }
  29204. // Updating submeshes
  29205. this.releaseSubMeshes();
  29206. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29207. var previousOne = previousSubmeshes[submeshIndex];
  29208. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29209. }
  29210. this._unIndexed = true;
  29211. this.synchronizeInstances();
  29212. return this;
  29213. };
  29214. /**
  29215. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29216. * This method returns the Mesh.
  29217. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29218. */
  29219. Mesh.prototype.flipFaces = function (flipNormals) {
  29220. if (flipNormals === void 0) { flipNormals = false; }
  29221. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29222. var i;
  29223. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29224. for (i = 0; i < vertex_data.normals.length; i++) {
  29225. vertex_data.normals[i] *= -1;
  29226. }
  29227. }
  29228. if (vertex_data.indices) {
  29229. var temp;
  29230. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29231. // reassign indices
  29232. temp = vertex_data.indices[i + 1];
  29233. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29234. vertex_data.indices[i + 2] = temp;
  29235. }
  29236. }
  29237. vertex_data.applyToMesh(this);
  29238. return this;
  29239. };
  29240. // Instances
  29241. /**
  29242. * Creates a new InstancedMesh object from the mesh model.
  29243. * An instance shares the same properties and the same material than its model.
  29244. * Only these properties of each instance can then be set individually :
  29245. * - position
  29246. * - rotation
  29247. * - rotationQuaternion
  29248. * - setPivotMatrix
  29249. * - scaling
  29250. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29251. * Warning : this method is not supported for Line mesh and LineSystem
  29252. */
  29253. Mesh.prototype.createInstance = function (name) {
  29254. return new BABYLON.InstancedMesh(name, this);
  29255. };
  29256. /**
  29257. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29258. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29259. * This method returns the Mesh.
  29260. */
  29261. Mesh.prototype.synchronizeInstances = function () {
  29262. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29263. var instance = this.instances[instanceIndex];
  29264. instance._syncSubMeshes();
  29265. }
  29266. return this;
  29267. };
  29268. /**
  29269. * Simplify the mesh according to the given array of settings.
  29270. * Function will return immediately and will simplify async. It returns the Mesh.
  29271. * @param settings a collection of simplification settings.
  29272. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29273. * @param type the type of simplification to run.
  29274. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29275. */
  29276. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29277. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29278. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29279. this.getScene().simplificationQueue.addTask({
  29280. settings: settings,
  29281. parallelProcessing: parallelProcessing,
  29282. mesh: this,
  29283. simplificationType: simplificationType,
  29284. successCallback: successCallback
  29285. });
  29286. return this;
  29287. };
  29288. /**
  29289. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29290. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29291. * This should be used together with the simplification to avoid disappearing triangles.
  29292. * Returns the Mesh.
  29293. * @param successCallback an optional success callback to be called after the optimization finished.
  29294. */
  29295. Mesh.prototype.optimizeIndices = function (successCallback) {
  29296. var _this = this;
  29297. var indices = this.getIndices();
  29298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29299. if (!positions || !indices) {
  29300. return this;
  29301. }
  29302. var vectorPositions = new Array();
  29303. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29304. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29305. }
  29306. var dupes = new Array();
  29307. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29308. var realPos = vectorPositions.length - 1 - iteration;
  29309. var testedPosition = vectorPositions[realPos];
  29310. for (var j = 0; j < realPos; ++j) {
  29311. var againstPosition = vectorPositions[j];
  29312. if (testedPosition.equals(againstPosition)) {
  29313. dupes[realPos] = j;
  29314. break;
  29315. }
  29316. }
  29317. }, function () {
  29318. for (var i = 0; i < indices.length; ++i) {
  29319. indices[i] = dupes[indices[i]] || indices[i];
  29320. }
  29321. //indices are now reordered
  29322. var originalSubMeshes = _this.subMeshes.slice(0);
  29323. _this.setIndices(indices);
  29324. _this.subMeshes = originalSubMeshes;
  29325. if (successCallback) {
  29326. successCallback(_this);
  29327. }
  29328. });
  29329. return this;
  29330. };
  29331. Mesh.prototype.serialize = function (serializationObject) {
  29332. serializationObject.name = this.name;
  29333. serializationObject.id = this.id;
  29334. serializationObject.type = this.getClassName();
  29335. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29336. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29337. }
  29338. serializationObject.position = this.position.asArray();
  29339. if (this.rotationQuaternion) {
  29340. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29341. }
  29342. else if (this.rotation) {
  29343. serializationObject.rotation = this.rotation.asArray();
  29344. }
  29345. serializationObject.scaling = this.scaling.asArray();
  29346. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29347. serializationObject.isEnabled = this.isEnabled(false);
  29348. serializationObject.isVisible = this.isVisible;
  29349. serializationObject.infiniteDistance = this.infiniteDistance;
  29350. serializationObject.pickable = this.isPickable;
  29351. serializationObject.receiveShadows = this.receiveShadows;
  29352. serializationObject.billboardMode = this.billboardMode;
  29353. serializationObject.visibility = this.visibility;
  29354. serializationObject.checkCollisions = this.checkCollisions;
  29355. serializationObject.isBlocker = this.isBlocker;
  29356. // Parent
  29357. if (this.parent) {
  29358. serializationObject.parentId = this.parent.id;
  29359. }
  29360. // Geometry
  29361. serializationObject.isUnIndexed = this.isUnIndexed;
  29362. var geometry = this._geometry;
  29363. if (geometry) {
  29364. var geometryId = geometry.id;
  29365. serializationObject.geometryId = geometryId;
  29366. // SubMeshes
  29367. serializationObject.subMeshes = [];
  29368. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29369. var subMesh = this.subMeshes[subIndex];
  29370. serializationObject.subMeshes.push({
  29371. materialIndex: subMesh.materialIndex,
  29372. verticesStart: subMesh.verticesStart,
  29373. verticesCount: subMesh.verticesCount,
  29374. indexStart: subMesh.indexStart,
  29375. indexCount: subMesh.indexCount
  29376. });
  29377. }
  29378. }
  29379. // Material
  29380. if (this.material) {
  29381. serializationObject.materialId = this.material.id;
  29382. }
  29383. else {
  29384. this.material = null;
  29385. }
  29386. // Morph targets
  29387. if (this.morphTargetManager) {
  29388. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29389. }
  29390. // Skeleton
  29391. if (this.skeleton) {
  29392. serializationObject.skeletonId = this.skeleton.id;
  29393. }
  29394. // Physics
  29395. //TODO implement correct serialization for physics impostors.
  29396. var impostor = this.getPhysicsImpostor();
  29397. if (impostor) {
  29398. serializationObject.physicsMass = impostor.getParam("mass");
  29399. serializationObject.physicsFriction = impostor.getParam("friction");
  29400. serializationObject.physicsRestitution = impostor.getParam("mass");
  29401. serializationObject.physicsImpostor = impostor.type;
  29402. }
  29403. // Metadata
  29404. if (this.metadata) {
  29405. serializationObject.metadata = this.metadata;
  29406. }
  29407. // Instances
  29408. serializationObject.instances = [];
  29409. for (var index = 0; index < this.instances.length; index++) {
  29410. var instance = this.instances[index];
  29411. var serializationInstance = {
  29412. name: instance.name,
  29413. id: instance.id,
  29414. position: instance.position.asArray(),
  29415. scaling: instance.scaling.asArray()
  29416. };
  29417. if (instance.rotationQuaternion) {
  29418. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29419. }
  29420. else if (instance.rotation) {
  29421. serializationInstance.rotation = instance.rotation.asArray();
  29422. }
  29423. serializationObject.instances.push(serializationInstance);
  29424. // Animations
  29425. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29426. serializationInstance.ranges = instance.serializeAnimationRanges();
  29427. }
  29428. //
  29429. // Animations
  29430. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29431. serializationObject.ranges = this.serializeAnimationRanges();
  29432. // Layer mask
  29433. serializationObject.layerMask = this.layerMask;
  29434. // Alpha
  29435. serializationObject.alphaIndex = this.alphaIndex;
  29436. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29437. // Overlay
  29438. serializationObject.overlayAlpha = this.overlayAlpha;
  29439. serializationObject.overlayColor = this.overlayColor.asArray();
  29440. serializationObject.renderOverlay = this.renderOverlay;
  29441. // Fog
  29442. serializationObject.applyFog = this.applyFog;
  29443. // Action Manager
  29444. if (this.actionManager) {
  29445. serializationObject.actions = this.actionManager.serialize(this.name);
  29446. }
  29447. };
  29448. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29449. if (!this.geometry) {
  29450. return;
  29451. }
  29452. this._markSubMeshesAsAttributesDirty();
  29453. var morphTargetManager = this._morphTargetManager;
  29454. if (morphTargetManager && morphTargetManager.vertexCount) {
  29455. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29456. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29457. this.morphTargetManager = null;
  29458. return;
  29459. }
  29460. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29461. var morphTarget = morphTargetManager.getActiveTarget(index);
  29462. var positions = morphTarget.getPositions();
  29463. if (!positions) {
  29464. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29465. return;
  29466. }
  29467. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29468. var normals = morphTarget.getNormals();
  29469. if (normals) {
  29470. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29471. }
  29472. var tangents = morphTarget.getTangents();
  29473. if (tangents) {
  29474. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29475. }
  29476. }
  29477. }
  29478. else {
  29479. var index = 0;
  29480. // Positions
  29481. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29482. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29483. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29484. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29485. }
  29486. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29487. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29488. }
  29489. index++;
  29490. }
  29491. }
  29492. };
  29493. // Statics
  29494. /**
  29495. * Returns a new Mesh object parsed from the source provided.
  29496. * The parameter `parsedMesh` is the source.
  29497. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29498. */
  29499. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29500. var mesh;
  29501. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29502. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29503. }
  29504. else {
  29505. mesh = new Mesh(parsedMesh.name, scene);
  29506. }
  29507. mesh.id = parsedMesh.id;
  29508. if (BABYLON.Tags) {
  29509. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29510. }
  29511. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29512. if (parsedMesh.metadata !== undefined) {
  29513. mesh.metadata = parsedMesh.metadata;
  29514. }
  29515. if (parsedMesh.rotationQuaternion) {
  29516. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29517. }
  29518. else if (parsedMesh.rotation) {
  29519. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29520. }
  29521. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29522. if (parsedMesh.localMatrix) {
  29523. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29524. }
  29525. else if (parsedMesh.pivotMatrix) {
  29526. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29527. }
  29528. mesh.setEnabled(parsedMesh.isEnabled);
  29529. mesh.isVisible = parsedMesh.isVisible;
  29530. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29531. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29532. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29533. if (parsedMesh.applyFog !== undefined) {
  29534. mesh.applyFog = parsedMesh.applyFog;
  29535. }
  29536. if (parsedMesh.pickable !== undefined) {
  29537. mesh.isPickable = parsedMesh.pickable;
  29538. }
  29539. if (parsedMesh.alphaIndex !== undefined) {
  29540. mesh.alphaIndex = parsedMesh.alphaIndex;
  29541. }
  29542. mesh.receiveShadows = parsedMesh.receiveShadows;
  29543. mesh.billboardMode = parsedMesh.billboardMode;
  29544. if (parsedMesh.visibility !== undefined) {
  29545. mesh.visibility = parsedMesh.visibility;
  29546. }
  29547. mesh.checkCollisions = parsedMesh.checkCollisions;
  29548. if (parsedMesh.isBlocker !== undefined) {
  29549. mesh.isBlocker = parsedMesh.isBlocker;
  29550. }
  29551. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29552. // freezeWorldMatrix
  29553. if (parsedMesh.freezeWorldMatrix) {
  29554. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29555. }
  29556. // Parent
  29557. if (parsedMesh.parentId) {
  29558. mesh._waitingParentId = parsedMesh.parentId;
  29559. }
  29560. // Actions
  29561. if (parsedMesh.actions !== undefined) {
  29562. mesh._waitingActions = parsedMesh.actions;
  29563. }
  29564. // Overlay
  29565. if (parsedMesh.overlayAlpha !== undefined) {
  29566. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29567. }
  29568. if (parsedMesh.overlayColor !== undefined) {
  29569. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29570. }
  29571. if (parsedMesh.renderOverlay !== undefined) {
  29572. mesh.renderOverlay = parsedMesh.renderOverlay;
  29573. }
  29574. // Geometry
  29575. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29576. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29577. if (parsedMesh.delayLoadingFile) {
  29578. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29579. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29580. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29581. if (parsedMesh._binaryInfo) {
  29582. mesh._binaryInfo = parsedMesh._binaryInfo;
  29583. }
  29584. mesh._delayInfo = [];
  29585. if (parsedMesh.hasUVs) {
  29586. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29587. }
  29588. if (parsedMesh.hasUVs2) {
  29589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29590. }
  29591. if (parsedMesh.hasUVs3) {
  29592. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29593. }
  29594. if (parsedMesh.hasUVs4) {
  29595. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29596. }
  29597. if (parsedMesh.hasUVs5) {
  29598. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29599. }
  29600. if (parsedMesh.hasUVs6) {
  29601. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29602. }
  29603. if (parsedMesh.hasColors) {
  29604. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29605. }
  29606. if (parsedMesh.hasMatricesIndices) {
  29607. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29608. }
  29609. if (parsedMesh.hasMatricesWeights) {
  29610. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29611. }
  29612. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29613. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29614. mesh._checkDelayState();
  29615. }
  29616. }
  29617. else {
  29618. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29619. }
  29620. // Material
  29621. if (parsedMesh.materialId) {
  29622. mesh.setMaterialByID(parsedMesh.materialId);
  29623. }
  29624. else {
  29625. mesh.material = null;
  29626. }
  29627. // Morph targets
  29628. if (parsedMesh.morphTargetManagerId > -1) {
  29629. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29630. }
  29631. // Skeleton
  29632. if (parsedMesh.skeletonId > -1) {
  29633. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29634. if (parsedMesh.numBoneInfluencers) {
  29635. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29636. }
  29637. }
  29638. // Animations
  29639. if (parsedMesh.animations) {
  29640. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29641. var parsedAnimation = parsedMesh.animations[animationIndex];
  29642. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29643. }
  29644. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29645. }
  29646. if (parsedMesh.autoAnimate) {
  29647. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29648. }
  29649. // Layer Mask
  29650. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29651. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29652. }
  29653. else {
  29654. mesh.layerMask = 0x0FFFFFFF;
  29655. }
  29656. // Physics
  29657. if (parsedMesh.physicsImpostor) {
  29658. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29659. mass: parsedMesh.physicsMass,
  29660. friction: parsedMesh.physicsFriction,
  29661. restitution: parsedMesh.physicsRestitution
  29662. }, scene);
  29663. }
  29664. // Instances
  29665. if (parsedMesh.instances) {
  29666. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29667. var parsedInstance = parsedMesh.instances[index];
  29668. var instance = mesh.createInstance(parsedInstance.name);
  29669. if (parsedInstance.id) {
  29670. instance.id = parsedInstance.id;
  29671. }
  29672. if (BABYLON.Tags) {
  29673. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29674. }
  29675. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29676. if (parsedInstance.parentId) {
  29677. instance._waitingParentId = parsedInstance.parentId;
  29678. }
  29679. if (parsedInstance.rotationQuaternion) {
  29680. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29681. }
  29682. else if (parsedInstance.rotation) {
  29683. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29684. }
  29685. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29686. instance.checkCollisions = mesh.checkCollisions;
  29687. if (parsedMesh.animations) {
  29688. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29689. parsedAnimation = parsedMesh.animations[animationIndex];
  29690. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29691. }
  29692. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29693. }
  29694. }
  29695. }
  29696. return mesh;
  29697. };
  29698. /**
  29699. * Creates a ribbon mesh.
  29700. * Please consider using the same method from the MeshBuilder class instead.
  29701. * 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.
  29702. *
  29703. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29704. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29705. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29706. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29707. * 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.
  29708. * 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.
  29709. * 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
  29710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29713. */
  29714. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29715. if (closeArray === void 0) { closeArray = false; }
  29716. if (updatable === void 0) { updatable = false; }
  29717. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29718. pathArray: pathArray,
  29719. closeArray: closeArray,
  29720. closePath: closePath,
  29721. offset: offset,
  29722. updatable: updatable,
  29723. sideOrientation: sideOrientation,
  29724. instance: instance
  29725. }, scene);
  29726. };
  29727. /**
  29728. * Creates a plane polygonal mesh. By default, this is a disc.
  29729. * Please consider using the same method from the MeshBuilder class instead.
  29730. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29731. * 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.
  29732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29735. */
  29736. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29737. if (scene === void 0) { scene = null; }
  29738. var options = {
  29739. radius: radius,
  29740. tessellation: tessellation,
  29741. sideOrientation: sideOrientation,
  29742. updatable: updatable
  29743. };
  29744. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29745. };
  29746. /**
  29747. * Creates a box mesh.
  29748. * Please consider using the same method from the MeshBuilder class instead.
  29749. * The parameter `size` sets the size (float) of each box side (default 1).
  29750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29753. */
  29754. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29755. if (scene === void 0) { scene = null; }
  29756. var options = {
  29757. size: size,
  29758. sideOrientation: sideOrientation,
  29759. updatable: updatable
  29760. };
  29761. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29762. };
  29763. /**
  29764. * Creates a sphere mesh.
  29765. * Please consider using the same method from the MeshBuilder class instead.
  29766. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29767. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29771. */
  29772. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29773. var options = {
  29774. segments: segments,
  29775. diameterX: diameter,
  29776. diameterY: diameter,
  29777. diameterZ: diameter,
  29778. sideOrientation: sideOrientation,
  29779. updatable: updatable
  29780. };
  29781. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29782. };
  29783. /**
  29784. * Creates a cylinder or a cone mesh.
  29785. * Please consider using the same method from the MeshBuilder class instead.
  29786. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29787. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29788. * 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.
  29789. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29790. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29794. */
  29795. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29796. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29797. if (scene !== undefined) {
  29798. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29799. updatable = scene;
  29800. }
  29801. scene = subdivisions;
  29802. subdivisions = 1;
  29803. }
  29804. var options = {
  29805. height: height,
  29806. diameterTop: diameterTop,
  29807. diameterBottom: diameterBottom,
  29808. tessellation: tessellation,
  29809. subdivisions: subdivisions,
  29810. sideOrientation: sideOrientation,
  29811. updatable: updatable
  29812. };
  29813. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29814. };
  29815. // Torus (Code from SharpDX.org)
  29816. /**
  29817. * Creates a torus mesh.
  29818. * Please consider using the same method from the MeshBuilder class instead.
  29819. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29820. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29821. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29825. */
  29826. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29827. var options = {
  29828. diameter: diameter,
  29829. thickness: thickness,
  29830. tessellation: tessellation,
  29831. sideOrientation: sideOrientation,
  29832. updatable: updatable
  29833. };
  29834. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29835. };
  29836. /**
  29837. * Creates a torus knot mesh.
  29838. * Please consider using the same method from the MeshBuilder class instead.
  29839. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29840. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29841. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29842. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29846. */
  29847. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29848. var options = {
  29849. radius: radius,
  29850. tube: tube,
  29851. radialSegments: radialSegments,
  29852. tubularSegments: tubularSegments,
  29853. p: p,
  29854. q: q,
  29855. sideOrientation: sideOrientation,
  29856. updatable: updatable
  29857. };
  29858. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29859. };
  29860. /**
  29861. * Creates a line mesh.
  29862. * Please consider using the same method from the MeshBuilder class instead.
  29863. * 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.
  29864. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29865. * The parameter `points` is an array successive Vector3.
  29866. * 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
  29867. * When updating an instance, remember that only point positions can change, not the number of points.
  29868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29869. */
  29870. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29871. if (scene === void 0) { scene = null; }
  29872. if (updatable === void 0) { updatable = false; }
  29873. if (instance === void 0) { instance = null; }
  29874. var options = {
  29875. points: points,
  29876. updatable: updatable,
  29877. instance: instance
  29878. };
  29879. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29880. };
  29881. /**
  29882. * Creates a dashed line mesh.
  29883. * Please consider using the same method from the MeshBuilder class instead.
  29884. * 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.
  29885. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29886. * The parameter `points` is an array successive Vector3.
  29887. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29888. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29889. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29890. * 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
  29891. * When updating an instance, remember that only point positions can change, not the number of points.
  29892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29893. */
  29894. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29895. if (scene === void 0) { scene = null; }
  29896. var options = {
  29897. points: points,
  29898. dashSize: dashSize,
  29899. gapSize: gapSize,
  29900. dashNb: dashNb,
  29901. updatable: updatable,
  29902. instance: instance
  29903. };
  29904. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29905. };
  29906. /**
  29907. * Creates a polygon mesh.
  29908. * Please consider using the same method from the MeshBuilder class instead.
  29909. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29910. * 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.
  29911. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29913. * Remember you can only change the shape positions, not their number when updating a polygon.
  29914. */
  29915. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29916. var options = {
  29917. shape: shape,
  29918. holes: holes,
  29919. updatable: updatable,
  29920. sideOrientation: sideOrientation
  29921. };
  29922. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29923. };
  29924. /**
  29925. * Creates an extruded polygon mesh, with depth in the Y direction.
  29926. * Please consider using the same method from the MeshBuilder class instead.
  29927. */
  29928. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29929. var options = {
  29930. shape: shape,
  29931. holes: holes,
  29932. depth: depth,
  29933. updatable: updatable,
  29934. sideOrientation: sideOrientation
  29935. };
  29936. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29937. };
  29938. /**
  29939. * Creates an extruded shape mesh.
  29940. * 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.
  29941. * Please consider using the same method from the MeshBuilder class instead.
  29942. *
  29943. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29944. * 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
  29945. * extruded along the Z axis.
  29946. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29947. * 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.
  29948. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29949. * 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
  29950. * 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
  29951. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29955. */
  29956. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29957. if (scene === void 0) { scene = null; }
  29958. var options = {
  29959. shape: shape,
  29960. path: path,
  29961. scale: scale,
  29962. rotation: rotation,
  29963. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29964. sideOrientation: sideOrientation,
  29965. instance: instance,
  29966. updatable: updatable
  29967. };
  29968. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29969. };
  29970. /**
  29971. * Creates an custom extruded shape mesh.
  29972. * 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.
  29973. * Please consider using the same method from the MeshBuilder class instead.
  29974. *
  29975. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29976. * 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
  29977. * extruded along the Z axis.
  29978. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29979. * 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
  29980. * and the distance of this point from the begining of the path :
  29981. * ```javascript
  29982. * var rotationFunction = function(i, distance) {
  29983. * // do things
  29984. * return rotationValue; }
  29985. * ```
  29986. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29987. * 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
  29988. * and the distance of this point from the begining of the path :
  29989. * ```javascript
  29990. * var scaleFunction = function(i, distance) {
  29991. * // do things
  29992. * return scaleValue;}
  29993. * ```
  29994. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29995. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29996. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29997. * 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
  29998. * 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
  29999. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30000. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30001. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30003. */
  30004. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30005. var options = {
  30006. shape: shape,
  30007. path: path,
  30008. scaleFunction: scaleFunction,
  30009. rotationFunction: rotationFunction,
  30010. ribbonCloseArray: ribbonCloseArray,
  30011. ribbonClosePath: ribbonClosePath,
  30012. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30013. sideOrientation: sideOrientation,
  30014. instance: instance,
  30015. updatable: updatable
  30016. };
  30017. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30018. };
  30019. /**
  30020. * Creates lathe mesh.
  30021. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30022. * Please consider using the same method from the MeshBuilder class instead.
  30023. * 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
  30024. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30025. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30026. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30030. */
  30031. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30032. var options = {
  30033. shape: shape,
  30034. radius: radius,
  30035. tessellation: tessellation,
  30036. sideOrientation: sideOrientation,
  30037. updatable: updatable
  30038. };
  30039. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30040. };
  30041. /**
  30042. * Creates a plane mesh.
  30043. * Please consider using the same method from the MeshBuilder class instead.
  30044. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30046. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30048. */
  30049. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30050. var options = {
  30051. size: size,
  30052. width: size,
  30053. height: size,
  30054. sideOrientation: sideOrientation,
  30055. updatable: updatable
  30056. };
  30057. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30058. };
  30059. /**
  30060. * Creates a ground mesh.
  30061. * Please consider using the same method from the MeshBuilder class instead.
  30062. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30063. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30065. */
  30066. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30067. var options = {
  30068. width: width,
  30069. height: height,
  30070. subdivisions: subdivisions,
  30071. updatable: updatable
  30072. };
  30073. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30074. };
  30075. /**
  30076. * Creates a tiled ground mesh.
  30077. * Please consider using the same method from the MeshBuilder class instead.
  30078. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30079. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30080. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30081. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30082. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30083. * numbers of subdivisions on the ground width and height of each tile.
  30084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30085. */
  30086. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30087. var options = {
  30088. xmin: xmin,
  30089. zmin: zmin,
  30090. xmax: xmax,
  30091. zmax: zmax,
  30092. subdivisions: subdivisions,
  30093. precision: precision,
  30094. updatable: updatable
  30095. };
  30096. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30097. };
  30098. /**
  30099. * Creates a ground mesh from a height map.
  30100. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30101. * Please consider using the same method from the MeshBuilder class instead.
  30102. * The parameter `url` sets the URL of the height map image resource.
  30103. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30104. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30105. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30106. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30107. * 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).
  30108. * This function is passed the newly built mesh :
  30109. * ```javascript
  30110. * function(mesh) { // do things
  30111. * return; }
  30112. * ```
  30113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30114. */
  30115. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30116. var options = {
  30117. width: width,
  30118. height: height,
  30119. subdivisions: subdivisions,
  30120. minHeight: minHeight,
  30121. maxHeight: maxHeight,
  30122. updatable: updatable,
  30123. onReady: onReady
  30124. };
  30125. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30126. };
  30127. /**
  30128. * Creates a tube mesh.
  30129. * 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.
  30130. * Please consider using the same method from the MeshBuilder class instead.
  30131. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30132. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30133. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30134. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30135. * 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.
  30136. * It must return a radius value (positive float) :
  30137. * ```javascript
  30138. * var radiusFunction = function(i, distance) {
  30139. * // do things
  30140. * return radius; }
  30141. * ```
  30142. * 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
  30143. * 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
  30144. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30147. */
  30148. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30149. var options = {
  30150. path: path,
  30151. radius: radius,
  30152. tessellation: tessellation,
  30153. radiusFunction: radiusFunction,
  30154. arc: 1,
  30155. cap: cap,
  30156. updatable: updatable,
  30157. sideOrientation: sideOrientation,
  30158. instance: instance
  30159. };
  30160. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30161. };
  30162. /**
  30163. * Creates a polyhedron mesh.
  30164. * Please consider using the same method from the MeshBuilder class instead.
  30165. * 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
  30166. * to choose the wanted type.
  30167. * The parameter `size` (positive float, default 1) sets the polygon size.
  30168. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30169. * 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`.
  30170. * 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
  30171. * 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)`).
  30172. * 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
  30173. * 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.
  30174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30177. */
  30178. Mesh.CreatePolyhedron = function (name, options, scene) {
  30179. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30180. };
  30181. /**
  30182. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30183. * Please consider using the same method from the MeshBuilder class instead.
  30184. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30185. * 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`).
  30186. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30187. * 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.
  30188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30191. */
  30192. Mesh.CreateIcoSphere = function (name, options, scene) {
  30193. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30194. };
  30195. /**
  30196. * Creates a decal mesh.
  30197. * Please consider using the same method from the MeshBuilder class instead.
  30198. * 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.
  30199. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30200. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30201. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30202. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30203. */
  30204. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30205. var options = {
  30206. position: position,
  30207. normal: normal,
  30208. size: size,
  30209. angle: angle
  30210. };
  30211. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30212. };
  30213. // Skeletons
  30214. /**
  30215. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30216. */
  30217. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30218. if (!this._sourcePositions) {
  30219. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30220. if (!source) {
  30221. return this._sourcePositions;
  30222. }
  30223. this._sourcePositions = new Float32Array(source);
  30224. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30225. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30226. }
  30227. }
  30228. return this._sourcePositions;
  30229. };
  30230. /**
  30231. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30232. */
  30233. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30234. if (!this._sourceNormals) {
  30235. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30236. if (!source) {
  30237. return this._sourceNormals;
  30238. }
  30239. this._sourceNormals = new Float32Array(source);
  30240. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30241. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30242. }
  30243. }
  30244. return this._sourceNormals;
  30245. };
  30246. /**
  30247. * Updates the vertex buffer by applying transformation from the bones.
  30248. * Returns the Mesh.
  30249. *
  30250. * @param {skeleton} skeleton to apply
  30251. */
  30252. Mesh.prototype.applySkeleton = function (skeleton) {
  30253. if (!this.geometry) {
  30254. return this;
  30255. }
  30256. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30257. return this;
  30258. }
  30259. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30261. return this;
  30262. }
  30263. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30264. return this;
  30265. }
  30266. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30267. return this;
  30268. }
  30269. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30270. return this;
  30271. }
  30272. if (!this._sourcePositions) {
  30273. var submeshes = this.subMeshes.slice();
  30274. this.setPositionsForCPUSkinning();
  30275. this.subMeshes = submeshes;
  30276. }
  30277. if (!this._sourceNormals) {
  30278. this.setNormalsForCPUSkinning();
  30279. }
  30280. // positionsData checks for not being Float32Array will only pass at most once
  30281. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30282. if (!positionsData) {
  30283. return this;
  30284. }
  30285. if (!(positionsData instanceof Float32Array)) {
  30286. positionsData = new Float32Array(positionsData);
  30287. }
  30288. // normalsData checks for not being Float32Array will only pass at most once
  30289. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30290. if (!normalsData) {
  30291. return this;
  30292. }
  30293. if (!(normalsData instanceof Float32Array)) {
  30294. normalsData = new Float32Array(normalsData);
  30295. }
  30296. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30297. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30298. if (!matricesWeightsData || !matricesIndicesData) {
  30299. return this;
  30300. }
  30301. var needExtras = this.numBoneInfluencers > 4;
  30302. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30303. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30304. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30305. var tempVector3 = BABYLON.Vector3.Zero();
  30306. var finalMatrix = new BABYLON.Matrix();
  30307. var tempMatrix = new BABYLON.Matrix();
  30308. var matWeightIdx = 0;
  30309. var inf;
  30310. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30311. var weight;
  30312. for (inf = 0; inf < 4; inf++) {
  30313. weight = matricesWeightsData[matWeightIdx + inf];
  30314. if (weight > 0) {
  30315. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30316. finalMatrix.addToSelf(tempMatrix);
  30317. }
  30318. else
  30319. break;
  30320. }
  30321. if (needExtras) {
  30322. for (inf = 0; inf < 4; inf++) {
  30323. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30324. if (weight > 0) {
  30325. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30326. finalMatrix.addToSelf(tempMatrix);
  30327. }
  30328. else
  30329. break;
  30330. }
  30331. }
  30332. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30333. tempVector3.toArray(positionsData, index);
  30334. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30335. tempVector3.toArray(normalsData, index);
  30336. finalMatrix.reset();
  30337. }
  30338. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30339. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30340. return this;
  30341. };
  30342. // Tools
  30343. /**
  30344. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30345. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30346. */
  30347. Mesh.MinMax = function (meshes) {
  30348. var minVector = null;
  30349. var maxVector = null;
  30350. meshes.forEach(function (mesh, index, array) {
  30351. var boundingInfo = mesh.getBoundingInfo();
  30352. var boundingBox = boundingInfo.boundingBox;
  30353. if (!minVector || !maxVector) {
  30354. minVector = boundingBox.minimumWorld;
  30355. maxVector = boundingBox.maximumWorld;
  30356. }
  30357. else {
  30358. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30359. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30360. }
  30361. });
  30362. if (!minVector || !maxVector) {
  30363. return {
  30364. min: BABYLON.Vector3.Zero(),
  30365. max: BABYLON.Vector3.Zero()
  30366. };
  30367. }
  30368. return {
  30369. min: minVector,
  30370. max: maxVector
  30371. };
  30372. };
  30373. /**
  30374. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30375. */
  30376. Mesh.Center = function (meshesOrMinMaxVector) {
  30377. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30378. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30379. };
  30380. /**
  30381. * Merge the array of meshes into a single mesh for performance reasons.
  30382. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30383. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30384. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30385. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30386. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30387. */
  30388. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30389. if (disposeSource === void 0) { disposeSource = true; }
  30390. var index;
  30391. if (!allow32BitsIndices) {
  30392. var totalVertices = 0;
  30393. // Counting vertices
  30394. for (index = 0; index < meshes.length; index++) {
  30395. if (meshes[index]) {
  30396. totalVertices += meshes[index].getTotalVertices();
  30397. if (totalVertices > 65536) {
  30398. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30399. return null;
  30400. }
  30401. }
  30402. }
  30403. }
  30404. // Merge
  30405. var vertexData = null;
  30406. var otherVertexData;
  30407. var indiceArray = new Array();
  30408. var source = null;
  30409. for (index = 0; index < meshes.length; index++) {
  30410. if (meshes[index]) {
  30411. meshes[index].computeWorldMatrix(true);
  30412. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30413. otherVertexData.transform(meshes[index].getWorldMatrix());
  30414. if (vertexData) {
  30415. vertexData.merge(otherVertexData);
  30416. }
  30417. else {
  30418. vertexData = otherVertexData;
  30419. source = meshes[index];
  30420. }
  30421. if (subdivideWithSubMeshes) {
  30422. indiceArray.push(meshes[index].getTotalIndices());
  30423. }
  30424. }
  30425. }
  30426. source = source;
  30427. if (!meshSubclass) {
  30428. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30429. }
  30430. vertexData.applyToMesh(meshSubclass);
  30431. // Setting properties
  30432. meshSubclass.material = source.material;
  30433. meshSubclass.checkCollisions = source.checkCollisions;
  30434. // Cleaning
  30435. if (disposeSource) {
  30436. for (index = 0; index < meshes.length; index++) {
  30437. if (meshes[index]) {
  30438. meshes[index].dispose();
  30439. }
  30440. }
  30441. }
  30442. // Subdivide
  30443. if (subdivideWithSubMeshes) {
  30444. //-- Suppresions du submesh global
  30445. meshSubclass.releaseSubMeshes();
  30446. index = 0;
  30447. var offset = 0;
  30448. //-- aplique la subdivision en fonction du tableau d'indices
  30449. while (index < indiceArray.length) {
  30450. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30451. offset += indiceArray[index];
  30452. index++;
  30453. }
  30454. }
  30455. return meshSubclass;
  30456. };
  30457. // Consts
  30458. Mesh._FRONTSIDE = 0;
  30459. Mesh._BACKSIDE = 1;
  30460. Mesh._DOUBLESIDE = 2;
  30461. Mesh._DEFAULTSIDE = 0;
  30462. Mesh._NO_CAP = 0;
  30463. Mesh._CAP_START = 1;
  30464. Mesh._CAP_END = 2;
  30465. Mesh._CAP_ALL = 3;
  30466. return Mesh;
  30467. }(BABYLON.AbstractMesh));
  30468. BABYLON.Mesh = Mesh;
  30469. })(BABYLON || (BABYLON = {}));
  30470. //# sourceMappingURL=babylon.mesh.js.map
  30471. var BABYLON;
  30472. (function (BABYLON) {
  30473. var BaseSubMesh = /** @class */ (function () {
  30474. function BaseSubMesh() {
  30475. }
  30476. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30477. get: function () {
  30478. return this._materialEffect;
  30479. },
  30480. enumerable: true,
  30481. configurable: true
  30482. });
  30483. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30484. if (defines === void 0) { defines = null; }
  30485. if (this._materialEffect === effect) {
  30486. if (!effect) {
  30487. this._materialDefines = null;
  30488. }
  30489. return;
  30490. }
  30491. this._materialDefines = defines;
  30492. this._materialEffect = effect;
  30493. };
  30494. return BaseSubMesh;
  30495. }());
  30496. BABYLON.BaseSubMesh = BaseSubMesh;
  30497. var SubMesh = /** @class */ (function (_super) {
  30498. __extends(SubMesh, _super);
  30499. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30500. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30501. var _this = _super.call(this) || this;
  30502. _this.materialIndex = materialIndex;
  30503. _this.verticesStart = verticesStart;
  30504. _this.verticesCount = verticesCount;
  30505. _this.indexStart = indexStart;
  30506. _this.indexCount = indexCount;
  30507. _this._renderId = 0;
  30508. _this._mesh = mesh;
  30509. _this._renderingMesh = renderingMesh || mesh;
  30510. mesh.subMeshes.push(_this);
  30511. _this._trianglePlanes = [];
  30512. _this._id = mesh.subMeshes.length - 1;
  30513. if (createBoundingBox) {
  30514. _this.refreshBoundingInfo();
  30515. mesh.computeWorldMatrix(true);
  30516. }
  30517. return _this;
  30518. }
  30519. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30520. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30521. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30522. };
  30523. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30524. get: function () {
  30525. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. /**
  30531. * Returns the submesh BoudingInfo object.
  30532. */
  30533. SubMesh.prototype.getBoundingInfo = function () {
  30534. if (this.IsGlobal) {
  30535. return this._mesh.getBoundingInfo();
  30536. }
  30537. return this._boundingInfo;
  30538. };
  30539. /**
  30540. * Sets the submesh BoundingInfo.
  30541. * Return the SubMesh.
  30542. */
  30543. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30544. this._boundingInfo = boundingInfo;
  30545. return this;
  30546. };
  30547. /**
  30548. * Returns the mesh of the current submesh.
  30549. */
  30550. SubMesh.prototype.getMesh = function () {
  30551. return this._mesh;
  30552. };
  30553. /**
  30554. * Returns the rendering mesh of the submesh.
  30555. */
  30556. SubMesh.prototype.getRenderingMesh = function () {
  30557. return this._renderingMesh;
  30558. };
  30559. /**
  30560. * Returns the submesh material.
  30561. */
  30562. SubMesh.prototype.getMaterial = function () {
  30563. var rootMaterial = this._renderingMesh.material;
  30564. if (rootMaterial === null || rootMaterial === undefined) {
  30565. return this._mesh.getScene().defaultMaterial;
  30566. }
  30567. else if (rootMaterial.getSubMaterial) {
  30568. var multiMaterial = rootMaterial;
  30569. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30570. if (this._currentMaterial !== effectiveMaterial) {
  30571. this._currentMaterial = effectiveMaterial;
  30572. this._materialDefines = null;
  30573. }
  30574. return effectiveMaterial;
  30575. }
  30576. return rootMaterial;
  30577. };
  30578. // Methods
  30579. /**
  30580. * Sets a new updated BoundingInfo object to the submesh.
  30581. * Returns the SubMesh.
  30582. */
  30583. SubMesh.prototype.refreshBoundingInfo = function () {
  30584. this._lastColliderWorldVertices = null;
  30585. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30586. return this;
  30587. }
  30588. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30589. if (!data) {
  30590. this._boundingInfo = this._mesh.getBoundingInfo();
  30591. return this;
  30592. }
  30593. var indices = this._renderingMesh.getIndices();
  30594. var extend;
  30595. //is this the only submesh?
  30596. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30597. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30598. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30599. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30600. }
  30601. else {
  30602. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30603. }
  30604. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30605. return this;
  30606. };
  30607. SubMesh.prototype._checkCollision = function (collider) {
  30608. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30609. return boundingInfo._checkCollision(collider);
  30610. };
  30611. /**
  30612. * Updates the submesh BoundingInfo.
  30613. * Returns the Submesh.
  30614. */
  30615. SubMesh.prototype.updateBoundingInfo = function (world) {
  30616. var boundingInfo = this.getBoundingInfo();
  30617. if (!boundingInfo) {
  30618. this.refreshBoundingInfo();
  30619. boundingInfo = this.getBoundingInfo();
  30620. }
  30621. boundingInfo.update(world);
  30622. return this;
  30623. };
  30624. /**
  30625. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30626. * Boolean returned.
  30627. */
  30628. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30629. var boundingInfo = this.getBoundingInfo();
  30630. if (!boundingInfo) {
  30631. return false;
  30632. }
  30633. return boundingInfo.isInFrustum(frustumPlanes);
  30634. };
  30635. /**
  30636. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30637. * Boolean returned.
  30638. */
  30639. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30640. var boundingInfo = this.getBoundingInfo();
  30641. if (!boundingInfo) {
  30642. return false;
  30643. }
  30644. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30645. };
  30646. /**
  30647. * Renders the submesh.
  30648. * Returns it.
  30649. */
  30650. SubMesh.prototype.render = function (enableAlphaMode) {
  30651. this._renderingMesh.render(this, enableAlphaMode);
  30652. return this;
  30653. };
  30654. /**
  30655. * Returns a new Index Buffer.
  30656. * Type returned : WebGLBuffer.
  30657. */
  30658. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30659. if (!this._linesIndexBuffer) {
  30660. var linesIndices = [];
  30661. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30662. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30663. }
  30664. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30665. this.linesIndexCount = linesIndices.length;
  30666. }
  30667. return this._linesIndexBuffer;
  30668. };
  30669. /**
  30670. * True is the passed Ray intersects the submesh bounding box.
  30671. * Boolean returned.
  30672. */
  30673. SubMesh.prototype.canIntersects = function (ray) {
  30674. var boundingInfo = this.getBoundingInfo();
  30675. if (!boundingInfo) {
  30676. return false;
  30677. }
  30678. return ray.intersectsBox(boundingInfo.boundingBox);
  30679. };
  30680. /**
  30681. * Returns an object IntersectionInfo.
  30682. */
  30683. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30684. var intersectInfo = null;
  30685. // LineMesh first as it's also a Mesh...
  30686. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30687. var lineMesh = this._mesh;
  30688. // Line test
  30689. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30690. var p0 = positions[indices[index]];
  30691. var p1 = positions[indices[index + 1]];
  30692. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30693. if (length < 0) {
  30694. continue;
  30695. }
  30696. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30697. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30698. if (fastCheck) {
  30699. break;
  30700. }
  30701. }
  30702. }
  30703. }
  30704. else {
  30705. // Triangles test
  30706. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30707. var p0 = positions[indices[index]];
  30708. var p1 = positions[indices[index + 1]];
  30709. var p2 = positions[indices[index + 2]];
  30710. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30711. if (currentIntersectInfo) {
  30712. if (currentIntersectInfo.distance < 0) {
  30713. continue;
  30714. }
  30715. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30716. intersectInfo = currentIntersectInfo;
  30717. intersectInfo.faceId = index / 3;
  30718. if (fastCheck) {
  30719. break;
  30720. }
  30721. }
  30722. }
  30723. }
  30724. }
  30725. return intersectInfo;
  30726. };
  30727. SubMesh.prototype._rebuild = function () {
  30728. if (this._linesIndexBuffer) {
  30729. this._linesIndexBuffer = null;
  30730. }
  30731. };
  30732. // Clone
  30733. /**
  30734. * Creates a new Submesh from the passed Mesh.
  30735. */
  30736. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30737. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30738. if (!this.IsGlobal) {
  30739. var boundingInfo = this.getBoundingInfo();
  30740. if (!boundingInfo) {
  30741. return result;
  30742. }
  30743. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30744. }
  30745. return result;
  30746. };
  30747. // Dispose
  30748. /**
  30749. * Disposes the Submesh.
  30750. * Returns nothing.
  30751. */
  30752. SubMesh.prototype.dispose = function () {
  30753. if (this._linesIndexBuffer) {
  30754. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30755. this._linesIndexBuffer = null;
  30756. }
  30757. // Remove from mesh
  30758. var index = this._mesh.subMeshes.indexOf(this);
  30759. this._mesh.subMeshes.splice(index, 1);
  30760. };
  30761. // Statics
  30762. /**
  30763. * Creates a new Submesh from the passed parameters :
  30764. * - materialIndex (integer) : the index of the main mesh material.
  30765. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30766. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30767. * - mesh (Mesh) : the main mesh to create the submesh from.
  30768. * - renderingMesh (optional Mesh) : rendering mesh.
  30769. */
  30770. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30771. var minVertexIndex = Number.MAX_VALUE;
  30772. var maxVertexIndex = -Number.MAX_VALUE;
  30773. renderingMesh = (renderingMesh || mesh);
  30774. var indices = renderingMesh.getIndices();
  30775. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30776. var vertexIndex = indices[index];
  30777. if (vertexIndex < minVertexIndex)
  30778. minVertexIndex = vertexIndex;
  30779. if (vertexIndex > maxVertexIndex)
  30780. maxVertexIndex = vertexIndex;
  30781. }
  30782. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30783. };
  30784. return SubMesh;
  30785. }(BaseSubMesh));
  30786. BABYLON.SubMesh = SubMesh;
  30787. })(BABYLON || (BABYLON = {}));
  30788. //# sourceMappingURL=babylon.subMesh.js.map
  30789. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30790. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30791. s = arguments[i];
  30792. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30793. t[p] = s[p];
  30794. }
  30795. return t;
  30796. };
  30797. var BABYLON;
  30798. (function (BABYLON) {
  30799. /**
  30800. * Manages the defines for the Material.
  30801. */
  30802. var MaterialDefines = /** @class */ (function () {
  30803. function MaterialDefines() {
  30804. this._isDirty = true;
  30805. this._areLightsDirty = true;
  30806. this._areAttributesDirty = true;
  30807. this._areTexturesDirty = true;
  30808. this._areFresnelDirty = true;
  30809. this._areMiscDirty = true;
  30810. this._areImageProcessingDirty = true;
  30811. this._normals = false;
  30812. this._uvs = false;
  30813. this._needNormals = false;
  30814. this._needUVs = false;
  30815. }
  30816. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30817. /**
  30818. * Specifies if the material needs to be re-calculated.
  30819. */
  30820. get: function () {
  30821. return this._isDirty;
  30822. },
  30823. enumerable: true,
  30824. configurable: true
  30825. });
  30826. /**
  30827. * Marks the material to indicate that it has been re-calculated.
  30828. */
  30829. MaterialDefines.prototype.markAsProcessed = function () {
  30830. this._isDirty = false;
  30831. this._areAttributesDirty = false;
  30832. this._areTexturesDirty = false;
  30833. this._areFresnelDirty = false;
  30834. this._areLightsDirty = false;
  30835. this._areMiscDirty = false;
  30836. this._areImageProcessingDirty = false;
  30837. };
  30838. /**
  30839. * Marks the material to indicate that it needs to be re-calculated.
  30840. */
  30841. MaterialDefines.prototype.markAsUnprocessed = function () {
  30842. this._isDirty = true;
  30843. };
  30844. /**
  30845. * Marks the material to indicate all of its defines need to be re-calculated.
  30846. */
  30847. MaterialDefines.prototype.markAllAsDirty = function () {
  30848. this._areTexturesDirty = true;
  30849. this._areAttributesDirty = true;
  30850. this._areLightsDirty = true;
  30851. this._areFresnelDirty = true;
  30852. this._areMiscDirty = true;
  30853. this._areImageProcessingDirty = true;
  30854. this._isDirty = true;
  30855. };
  30856. /**
  30857. * Marks the material to indicate that image processing needs to be re-calculated.
  30858. */
  30859. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30860. this._areImageProcessingDirty = true;
  30861. this._isDirty = true;
  30862. };
  30863. /**
  30864. * Marks the material to indicate the lights need to be re-calculated.
  30865. */
  30866. MaterialDefines.prototype.markAsLightDirty = function () {
  30867. this._areLightsDirty = true;
  30868. this._isDirty = true;
  30869. };
  30870. /**
  30871. * Marks the attribute state as changed.
  30872. */
  30873. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30874. this._areAttributesDirty = true;
  30875. this._isDirty = true;
  30876. };
  30877. /**
  30878. * Marks the texture state as changed.
  30879. */
  30880. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30881. this._areTexturesDirty = true;
  30882. this._isDirty = true;
  30883. };
  30884. /**
  30885. * Marks the fresnel state as changed.
  30886. */
  30887. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30888. this._areFresnelDirty = true;
  30889. this._isDirty = true;
  30890. };
  30891. /**
  30892. * Marks the misc state as changed.
  30893. */
  30894. MaterialDefines.prototype.markAsMiscDirty = function () {
  30895. this._areMiscDirty = true;
  30896. this._isDirty = true;
  30897. };
  30898. /**
  30899. * Rebuilds the material defines.
  30900. */
  30901. MaterialDefines.prototype.rebuild = function () {
  30902. if (this._keys) {
  30903. delete this._keys;
  30904. }
  30905. this._keys = [];
  30906. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30907. var key = _a[_i];
  30908. if (key[0] === "_") {
  30909. continue;
  30910. }
  30911. this._keys.push(key);
  30912. }
  30913. };
  30914. /**
  30915. * Specifies if two material defines are equal.
  30916. * @param other - A material define instance to compare to.
  30917. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30918. */
  30919. MaterialDefines.prototype.isEqual = function (other) {
  30920. if (this._keys.length !== other._keys.length) {
  30921. return false;
  30922. }
  30923. for (var index = 0; index < this._keys.length; index++) {
  30924. var prop = this._keys[index];
  30925. if (this[prop] !== other[prop]) {
  30926. return false;
  30927. }
  30928. }
  30929. return true;
  30930. };
  30931. /**
  30932. * Clones this instance's defines to another instance.
  30933. * @param other - material defines to clone values to.
  30934. */
  30935. MaterialDefines.prototype.cloneTo = function (other) {
  30936. if (this._keys.length !== other._keys.length) {
  30937. other._keys = this._keys.slice(0);
  30938. }
  30939. for (var index = 0; index < this._keys.length; index++) {
  30940. var prop = this._keys[index];
  30941. other[prop] = this[prop];
  30942. }
  30943. };
  30944. /**
  30945. * Resets the material define values.
  30946. */
  30947. MaterialDefines.prototype.reset = function () {
  30948. for (var index = 0; index < this._keys.length; index++) {
  30949. var prop = this._keys[index];
  30950. if (typeof (this[prop]) === "number") {
  30951. this[prop] = 0;
  30952. }
  30953. else {
  30954. this[prop] = false;
  30955. }
  30956. }
  30957. };
  30958. /**
  30959. * Converts the material define values to a string.
  30960. * @returns - String of material define information.
  30961. */
  30962. MaterialDefines.prototype.toString = function () {
  30963. var result = "";
  30964. for (var index = 0; index < this._keys.length; index++) {
  30965. var prop = this._keys[index];
  30966. var value = this[prop];
  30967. if (typeof (value) === "number") {
  30968. result += "#define " + prop + " " + this[prop] + "\n";
  30969. }
  30970. else if (value) {
  30971. result += "#define " + prop + "\n";
  30972. }
  30973. }
  30974. return result;
  30975. };
  30976. return MaterialDefines;
  30977. }());
  30978. BABYLON.MaterialDefines = MaterialDefines;
  30979. /**
  30980. * This offers the main features of a material in BJS.
  30981. */
  30982. var Material = /** @class */ (function () {
  30983. /**
  30984. * Creates a material instance.
  30985. * @param name - The name of the material.
  30986. * @param scene - The BJS scene to reference.
  30987. * @param doNotAdd - Specifies if the material should be added to the scene.
  30988. */
  30989. function Material(name, scene, doNotAdd) {
  30990. /**
  30991. * Specifies if the ready state should be checked on each call.
  30992. */
  30993. this.checkReadyOnEveryCall = false;
  30994. /**
  30995. * Specifies if the ready state should be checked once.
  30996. */
  30997. this.checkReadyOnlyOnce = false;
  30998. /**
  30999. * The state of the material.
  31000. */
  31001. this.state = "";
  31002. /**
  31003. * The alpha value of the material.
  31004. */
  31005. this._alpha = 1.0;
  31006. /**
  31007. * Specifies if back face culling is enabled.
  31008. */
  31009. this._backFaceCulling = true;
  31010. /**
  31011. * Specifies if the material should be serialized.
  31012. */
  31013. this.doNotSerialize = false;
  31014. /**
  31015. * Specifies if the effect should be stored on sub meshes.
  31016. */
  31017. this.storeEffectOnSubMeshes = false;
  31018. /**
  31019. * An event triggered when the material is disposed.
  31020. * @type {BABYLON.Observable}
  31021. */
  31022. this.onDisposeObservable = new BABYLON.Observable();
  31023. /**
  31024. * An event triggered when the material is bound.
  31025. * @type {BABYLON.Observable}
  31026. */
  31027. this.onBindObservable = new BABYLON.Observable();
  31028. /**
  31029. * An event triggered when the material is unbound.
  31030. * @type {BABYLON.Observable}
  31031. */
  31032. this.onUnBindObservable = new BABYLON.Observable();
  31033. /**
  31034. * Stores the value of the alpha mode.
  31035. */
  31036. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31037. /**
  31038. * Stores the state of the need depth pre-pass value.
  31039. */
  31040. this._needDepthPrePass = false;
  31041. /**
  31042. * Specifies if depth writing should be disabled.
  31043. */
  31044. this.disableDepthWrite = false;
  31045. /**
  31046. * Specifies if depth writing should be forced.
  31047. */
  31048. this.forceDepthWrite = false;
  31049. /**
  31050. * Specifies if there should be a separate pass for culling.
  31051. */
  31052. this.separateCullingPass = false;
  31053. /**
  31054. * Stores the state specifing if fog should be enabled.
  31055. */
  31056. this._fogEnabled = true;
  31057. /**
  31058. * Stores the size of points.
  31059. */
  31060. this.pointSize = 1.0;
  31061. /**
  31062. * Stores the z offset value.
  31063. */
  31064. this.zOffset = 0;
  31065. /**
  31066. * Specifies if the material was previously ready.
  31067. */
  31068. this._wasPreviouslyReady = false;
  31069. /**
  31070. * Stores the fill mode state.
  31071. */
  31072. this._fillMode = Material.TriangleFillMode;
  31073. this.name = name;
  31074. this.id = name || BABYLON.Tools.RandomId();
  31075. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31076. if (this._scene.useRightHandedSystem) {
  31077. this.sideOrientation = Material.ClockWiseSideOrientation;
  31078. }
  31079. else {
  31080. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31081. }
  31082. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31083. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31084. if (!doNotAdd) {
  31085. this._scene.materials.push(this);
  31086. }
  31087. }
  31088. Object.defineProperty(Material, "TriangleFillMode", {
  31089. /**
  31090. * Returns the triangle fill mode.
  31091. */
  31092. get: function () {
  31093. return Material._TriangleFillMode;
  31094. },
  31095. enumerable: true,
  31096. configurable: true
  31097. });
  31098. Object.defineProperty(Material, "WireFrameFillMode", {
  31099. /**
  31100. * Returns the wireframe mode.
  31101. */
  31102. get: function () {
  31103. return Material._WireFrameFillMode;
  31104. },
  31105. enumerable: true,
  31106. configurable: true
  31107. });
  31108. Object.defineProperty(Material, "PointFillMode", {
  31109. /**
  31110. * Returns the point fill mode.
  31111. */
  31112. get: function () {
  31113. return Material._PointFillMode;
  31114. },
  31115. enumerable: true,
  31116. configurable: true
  31117. });
  31118. Object.defineProperty(Material, "PointListDrawMode", {
  31119. /**
  31120. * Returns the point list draw mode.
  31121. */
  31122. get: function () {
  31123. return Material._PointListDrawMode;
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(Material, "LineListDrawMode", {
  31129. /**
  31130. * Returns the line list draw mode.
  31131. */
  31132. get: function () {
  31133. return Material._LineListDrawMode;
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. Object.defineProperty(Material, "LineLoopDrawMode", {
  31139. /**
  31140. * Returns the line loop draw mode.
  31141. */
  31142. get: function () {
  31143. return Material._LineLoopDrawMode;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Material, "LineStripDrawMode", {
  31149. /**
  31150. * Returns the line strip draw mode.
  31151. */
  31152. get: function () {
  31153. return Material._LineStripDrawMode;
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31159. /**
  31160. * Returns the triangle strip draw mode.
  31161. */
  31162. get: function () {
  31163. return Material._TriangleStripDrawMode;
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31169. /**
  31170. * Returns the triangle fan draw mode.
  31171. */
  31172. get: function () {
  31173. return Material._TriangleFanDrawMode;
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31179. /**
  31180. * Returns the clock-wise side orientation.
  31181. */
  31182. get: function () {
  31183. return Material._ClockWiseSideOrientation;
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31189. /**
  31190. * Returns the counter clock-wise side orientation.
  31191. */
  31192. get: function () {
  31193. return Material._CounterClockWiseSideOrientation;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(Material, "TextureDirtyFlag", {
  31199. /**
  31200. * Returns the dirty texture flag value.
  31201. */
  31202. get: function () {
  31203. return Material._TextureDirtyFlag;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Material, "LightDirtyFlag", {
  31209. /**
  31210. * Returns the dirty light flag value.
  31211. */
  31212. get: function () {
  31213. return Material._LightDirtyFlag;
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31219. /**
  31220. * Returns the dirty fresnel flag value.
  31221. */
  31222. get: function () {
  31223. return Material._FresnelDirtyFlag;
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31229. /**
  31230. * Returns the dirty attributes flag value.
  31231. */
  31232. get: function () {
  31233. return Material._AttributesDirtyFlag;
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(Material, "MiscDirtyFlag", {
  31239. /**
  31240. * Returns the dirty misc flag value.
  31241. */
  31242. get: function () {
  31243. return Material._MiscDirtyFlag;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(Material.prototype, "alpha", {
  31249. /**
  31250. * Gets the alpha value of the material.
  31251. */
  31252. get: function () {
  31253. return this._alpha;
  31254. },
  31255. /**
  31256. * Sets the alpha value of the material.
  31257. */
  31258. set: function (value) {
  31259. if (this._alpha === value) {
  31260. return;
  31261. }
  31262. this._alpha = value;
  31263. this.markAsDirty(Material.MiscDirtyFlag);
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31269. /**
  31270. * Gets the back-face culling state.
  31271. */
  31272. get: function () {
  31273. return this._backFaceCulling;
  31274. },
  31275. /**
  31276. * Sets the back-face culling state.
  31277. */
  31278. set: function (value) {
  31279. if (this._backFaceCulling === value) {
  31280. return;
  31281. }
  31282. this._backFaceCulling = value;
  31283. this.markAsDirty(Material.TextureDirtyFlag);
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(Material.prototype, "onDispose", {
  31289. /**
  31290. * Called during a dispose event.
  31291. */
  31292. set: function (callback) {
  31293. if (this._onDisposeObserver) {
  31294. this.onDisposeObservable.remove(this._onDisposeObserver);
  31295. }
  31296. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31297. },
  31298. enumerable: true,
  31299. configurable: true
  31300. });
  31301. Object.defineProperty(Material.prototype, "onBind", {
  31302. /**
  31303. * Called during a bind event.
  31304. */
  31305. set: function (callback) {
  31306. if (this._onBindObserver) {
  31307. this.onBindObservable.remove(this._onBindObserver);
  31308. }
  31309. this._onBindObserver = this.onBindObservable.add(callback);
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Object.defineProperty(Material.prototype, "alphaMode", {
  31315. /**
  31316. * Gets the value of the alpha mode.
  31317. */
  31318. get: function () {
  31319. return this._alphaMode;
  31320. },
  31321. /**
  31322. * Sets the value of the alpha mode.
  31323. */
  31324. set: function (value) {
  31325. if (this._alphaMode === value) {
  31326. return;
  31327. }
  31328. this._alphaMode = value;
  31329. this.markAsDirty(Material.TextureDirtyFlag);
  31330. },
  31331. enumerable: true,
  31332. configurable: true
  31333. });
  31334. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31335. /**
  31336. * Gets the depth pre-pass value.
  31337. */
  31338. get: function () {
  31339. return this._needDepthPrePass;
  31340. },
  31341. /**
  31342. * Sets the need depth pre-pass value.
  31343. */
  31344. set: function (value) {
  31345. if (this._needDepthPrePass === value) {
  31346. return;
  31347. }
  31348. this._needDepthPrePass = value;
  31349. if (this._needDepthPrePass) {
  31350. this.checkReadyOnEveryCall = true;
  31351. }
  31352. },
  31353. enumerable: true,
  31354. configurable: true
  31355. });
  31356. Object.defineProperty(Material.prototype, "fogEnabled", {
  31357. /**
  31358. * Gets the value of the fog enabled state.
  31359. */
  31360. get: function () {
  31361. return this._fogEnabled;
  31362. },
  31363. /**
  31364. * Sets the state for enabling fog.
  31365. */
  31366. set: function (value) {
  31367. if (this._fogEnabled === value) {
  31368. return;
  31369. }
  31370. this._fogEnabled = value;
  31371. this.markAsDirty(Material.MiscDirtyFlag);
  31372. },
  31373. enumerable: true,
  31374. configurable: true
  31375. });
  31376. Object.defineProperty(Material.prototype, "wireframe", {
  31377. /**
  31378. * Gets a value specifying if wireframe mode is enabled.
  31379. */
  31380. get: function () {
  31381. return this._fillMode === Material.WireFrameFillMode;
  31382. },
  31383. /**
  31384. * Sets the state of wireframe mode.
  31385. */
  31386. set: function (value) {
  31387. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31388. },
  31389. enumerable: true,
  31390. configurable: true
  31391. });
  31392. Object.defineProperty(Material.prototype, "pointsCloud", {
  31393. /**
  31394. * Gets the value specifying if point clouds are enabled.
  31395. */
  31396. get: function () {
  31397. return this._fillMode === Material.PointFillMode;
  31398. },
  31399. /**
  31400. * Sets the state of point cloud mode.
  31401. */
  31402. set: function (value) {
  31403. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31404. },
  31405. enumerable: true,
  31406. configurable: true
  31407. });
  31408. Object.defineProperty(Material.prototype, "fillMode", {
  31409. /**
  31410. * Gets the material fill mode.
  31411. */
  31412. get: function () {
  31413. return this._fillMode;
  31414. },
  31415. /**
  31416. * Sets the material fill mode.
  31417. */
  31418. set: function (value) {
  31419. if (this._fillMode === value) {
  31420. return;
  31421. }
  31422. this._fillMode = value;
  31423. this.markAsDirty(Material.MiscDirtyFlag);
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. /**
  31429. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31430. * subclasses should override adding information pertainent to themselves.
  31431. * @returns - String with material information.
  31432. */
  31433. Material.prototype.toString = function (fullDetails) {
  31434. var ret = "Name: " + this.name;
  31435. if (fullDetails) {
  31436. }
  31437. return ret;
  31438. };
  31439. /**
  31440. * Gets the class name of the material.
  31441. * @returns - String with the class name of the material.
  31442. */
  31443. Material.prototype.getClassName = function () {
  31444. return "Material";
  31445. };
  31446. Object.defineProperty(Material.prototype, "isFrozen", {
  31447. /**
  31448. * Specifies if updates for the material been locked.
  31449. */
  31450. get: function () {
  31451. return this.checkReadyOnlyOnce;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. /**
  31457. * Locks updates for the material.
  31458. */
  31459. Material.prototype.freeze = function () {
  31460. this.checkReadyOnlyOnce = true;
  31461. };
  31462. /**
  31463. * Unlocks updates for the material.
  31464. */
  31465. Material.prototype.unfreeze = function () {
  31466. this.checkReadyOnlyOnce = false;
  31467. };
  31468. /**
  31469. * Specifies if the material is ready to be used.
  31470. * @param mesh - BJS mesh.
  31471. * @param useInstances - Specifies if instances should be used.
  31472. * @returns - Boolean indicating if the material is ready to be used.
  31473. */
  31474. Material.prototype.isReady = function (mesh, useInstances) {
  31475. return true;
  31476. };
  31477. /**
  31478. * Specifies that the submesh is ready to be used.
  31479. * @param mesh - BJS mesh.
  31480. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31481. * @param useInstances - Specifies that instances should be used.
  31482. * @returns - boolean indicating that the submesh is ready or not.
  31483. */
  31484. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31485. return false;
  31486. };
  31487. /**
  31488. * Returns the material effect.
  31489. * @returns - Nullable material effect.
  31490. */
  31491. Material.prototype.getEffect = function () {
  31492. return this._effect;
  31493. };
  31494. /**
  31495. * Returns the BJS scene.
  31496. * @returns - BJS Scene.
  31497. */
  31498. Material.prototype.getScene = function () {
  31499. return this._scene;
  31500. };
  31501. /**
  31502. * Specifies if the material will require alpha blending
  31503. * @returns - Boolean specifying if alpha blending is needed.
  31504. */
  31505. Material.prototype.needAlphaBlending = function () {
  31506. return (this.alpha < 1.0);
  31507. };
  31508. /**
  31509. * Specifies if the mesh will require alpha blending.
  31510. * @param mesh - BJS mesh.
  31511. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31512. */
  31513. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31514. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31515. };
  31516. /**
  31517. * Specifies if this material should be rendered in alpha test mode.
  31518. * @returns - Boolean specifying if an alpha test is needed.
  31519. */
  31520. Material.prototype.needAlphaTesting = function () {
  31521. return false;
  31522. };
  31523. /**
  31524. * Gets the texture used for the alpha test.
  31525. * @returns - Nullable alpha test texture.
  31526. */
  31527. Material.prototype.getAlphaTestTexture = function () {
  31528. return null;
  31529. };
  31530. /**
  31531. * Marks the material to indicate that it needs to be re-calculated.
  31532. */
  31533. Material.prototype.markDirty = function () {
  31534. this._wasPreviouslyReady = false;
  31535. };
  31536. Material.prototype._preBind = function (effect, overrideOrientation) {
  31537. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31538. var engine = this._scene.getEngine();
  31539. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31540. var reverse = orientation === Material.ClockWiseSideOrientation;
  31541. engine.enableEffect(effect ? effect : this._effect);
  31542. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31543. return reverse;
  31544. };
  31545. /**
  31546. * Binds the material to the mesh.
  31547. * @param world - World transformation matrix.
  31548. * @param mesh - Mesh to bind the material to.
  31549. */
  31550. Material.prototype.bind = function (world, mesh) {
  31551. };
  31552. /**
  31553. * Binds the submesh to the material.
  31554. * @param world - World transformation matrix.
  31555. * @param mesh - Mesh containing the submesh.
  31556. * @param subMesh - Submesh to bind the material to.
  31557. */
  31558. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31559. };
  31560. /**
  31561. * Binds the world matrix to the material.
  31562. * @param world - World transformation matrix.
  31563. */
  31564. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31565. };
  31566. /**
  31567. * Binds the scene's uniform buffer to the effect.
  31568. * @param effect - Effect to bind to the scene uniform buffer.
  31569. * @param sceneUbo - Scene uniform buffer.
  31570. */
  31571. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31572. sceneUbo.bindToEffect(effect, "Scene");
  31573. };
  31574. /**
  31575. * Binds the view matrix to the effect.
  31576. * @param effect - Effect to bind the view matrix to.
  31577. */
  31578. Material.prototype.bindView = function (effect) {
  31579. if (!this._useUBO) {
  31580. effect.setMatrix("view", this.getScene().getViewMatrix());
  31581. }
  31582. else {
  31583. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31584. }
  31585. };
  31586. /**
  31587. * Binds the view projection matrix to the effect.
  31588. * @param effect - Effect to bind the view projection matrix to.
  31589. */
  31590. Material.prototype.bindViewProjection = function (effect) {
  31591. if (!this._useUBO) {
  31592. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31593. }
  31594. else {
  31595. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31596. }
  31597. };
  31598. /**
  31599. * Specifies if material alpha testing should be turned on for the mesh.
  31600. * @param mesh - BJS mesh.
  31601. */
  31602. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31603. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31604. };
  31605. /**
  31606. * Processes to execute after binding the material to a mesh.
  31607. * @param mesh - BJS mesh.
  31608. */
  31609. Material.prototype._afterBind = function (mesh) {
  31610. this._scene._cachedMaterial = this;
  31611. if (mesh) {
  31612. this._scene._cachedVisibility = mesh.visibility;
  31613. }
  31614. else {
  31615. this._scene._cachedVisibility = 1;
  31616. }
  31617. if (mesh) {
  31618. this.onBindObservable.notifyObservers(mesh);
  31619. }
  31620. if (this.disableDepthWrite) {
  31621. var engine = this._scene.getEngine();
  31622. this._cachedDepthWriteState = engine.getDepthWrite();
  31623. engine.setDepthWrite(false);
  31624. }
  31625. };
  31626. /**
  31627. * Unbinds the material from the mesh.
  31628. */
  31629. Material.prototype.unbind = function () {
  31630. this.onUnBindObservable.notifyObservers(this);
  31631. if (this.disableDepthWrite) {
  31632. var engine = this._scene.getEngine();
  31633. engine.setDepthWrite(this._cachedDepthWriteState);
  31634. }
  31635. };
  31636. /**
  31637. * Gets the active textures from the material.
  31638. * @returns - Array of textures.
  31639. */
  31640. Material.prototype.getActiveTextures = function () {
  31641. return [];
  31642. };
  31643. /**
  31644. * Specifies if the material uses a texture.
  31645. * @param texture - Texture to check against the material.
  31646. * @returns - Boolean specifying if the material uses the texture.
  31647. */
  31648. Material.prototype.hasTexture = function (texture) {
  31649. return false;
  31650. };
  31651. /**
  31652. * Makes a duplicate of the material, and gives it a new name.
  31653. * @param name - Name to call the duplicated material.
  31654. * @returns - Nullable cloned material
  31655. */
  31656. Material.prototype.clone = function (name) {
  31657. return null;
  31658. };
  31659. /**
  31660. * Gets the meshes bound to the material.
  31661. * @returns - Array of meshes bound to the material.
  31662. */
  31663. Material.prototype.getBindedMeshes = function () {
  31664. var result = new Array();
  31665. for (var index = 0; index < this._scene.meshes.length; index++) {
  31666. var mesh = this._scene.meshes[index];
  31667. if (mesh.material === this) {
  31668. result.push(mesh);
  31669. }
  31670. }
  31671. return result;
  31672. };
  31673. /**
  31674. * Force shader compilation
  31675. * @param mesh - BJS mesh.
  31676. * @param onCompiled - function to execute once the material is compiled.
  31677. * @param options - options to pass to this function.
  31678. */
  31679. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31680. var _this = this;
  31681. var localOptions = __assign({ clipPlane: false }, options);
  31682. var subMesh = new BABYLON.BaseSubMesh();
  31683. var scene = this.getScene();
  31684. var checkReady = function () {
  31685. if (!_this._scene || !_this._scene.getEngine()) {
  31686. return;
  31687. }
  31688. if (subMesh._materialDefines) {
  31689. subMesh._materialDefines._renderId = -1;
  31690. }
  31691. var clipPlaneState = scene.clipPlane;
  31692. if (localOptions.clipPlane) {
  31693. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31694. }
  31695. if (_this.storeEffectOnSubMeshes) {
  31696. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31697. if (onCompiled) {
  31698. onCompiled(_this);
  31699. }
  31700. }
  31701. else {
  31702. setTimeout(checkReady, 16);
  31703. }
  31704. }
  31705. else {
  31706. if (_this.isReady(mesh)) {
  31707. if (onCompiled) {
  31708. onCompiled(_this);
  31709. }
  31710. }
  31711. else {
  31712. setTimeout(checkReady, 16);
  31713. }
  31714. }
  31715. if (localOptions.clipPlane) {
  31716. scene.clipPlane = clipPlaneState;
  31717. }
  31718. };
  31719. checkReady();
  31720. };
  31721. /**
  31722. * Force shader compilation.
  31723. * @param mesh The mesh that will use this material
  31724. * @param options Additional options for compiling the shaders
  31725. * @returns A promise that resolves when the compilation completes
  31726. */
  31727. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31728. var _this = this;
  31729. return new Promise(function (resolve) {
  31730. _this.forceCompilation(mesh, function () {
  31731. resolve();
  31732. }, options);
  31733. });
  31734. };
  31735. /**
  31736. * Marks a define in the material to indicate that it needs to be re-computed.
  31737. * @param flag - Material define flag.
  31738. */
  31739. Material.prototype.markAsDirty = function (flag) {
  31740. if (flag & Material.TextureDirtyFlag) {
  31741. this._markAllSubMeshesAsTexturesDirty();
  31742. }
  31743. if (flag & Material.LightDirtyFlag) {
  31744. this._markAllSubMeshesAsLightsDirty();
  31745. }
  31746. if (flag & Material.FresnelDirtyFlag) {
  31747. this._markAllSubMeshesAsFresnelDirty();
  31748. }
  31749. if (flag & Material.AttributesDirtyFlag) {
  31750. this._markAllSubMeshesAsAttributesDirty();
  31751. }
  31752. if (flag & Material.MiscDirtyFlag) {
  31753. this._markAllSubMeshesAsMiscDirty();
  31754. }
  31755. this.getScene().resetCachedMaterial();
  31756. };
  31757. /**
  31758. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31759. * @param func - function which checks material defines against the submeshes.
  31760. */
  31761. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31762. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31763. var mesh = _a[_i];
  31764. if (!mesh.subMeshes) {
  31765. continue;
  31766. }
  31767. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31768. var subMesh = _c[_b];
  31769. if (subMesh.getMaterial() !== this) {
  31770. continue;
  31771. }
  31772. if (!subMesh._materialDefines) {
  31773. continue;
  31774. }
  31775. func(subMesh._materialDefines);
  31776. }
  31777. }
  31778. };
  31779. /**
  31780. * Indicates that image processing needs to be re-calculated for all submeshes.
  31781. */
  31782. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31783. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31784. };
  31785. /**
  31786. * Indicates that textures need to be re-calculated for all submeshes.
  31787. */
  31788. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31789. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31790. };
  31791. /**
  31792. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31793. */
  31794. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31795. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31796. };
  31797. /**
  31798. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31799. */
  31800. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31801. this._markAllSubMeshesAsDirty(function (defines) {
  31802. defines.markAsFresnelDirty();
  31803. defines.markAsMiscDirty();
  31804. });
  31805. };
  31806. /**
  31807. * Indicates that lights need to be re-calculated for all submeshes.
  31808. */
  31809. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31810. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31811. };
  31812. /**
  31813. * Indicates that attributes need to be re-calculated for all submeshes.
  31814. */
  31815. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31816. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31817. };
  31818. /**
  31819. * Indicates that misc needs to be re-calculated for all submeshes.
  31820. */
  31821. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31822. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31823. };
  31824. /**
  31825. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31826. */
  31827. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31828. this._markAllSubMeshesAsDirty(function (defines) {
  31829. defines.markAsTexturesDirty();
  31830. defines.markAsMiscDirty();
  31831. });
  31832. };
  31833. /**
  31834. * Disposes the material.
  31835. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31836. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31837. */
  31838. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31839. // Animations
  31840. this.getScene().stopAnimation(this);
  31841. this.getScene().freeProcessedMaterials();
  31842. // Remove from scene
  31843. var index = this._scene.materials.indexOf(this);
  31844. if (index >= 0) {
  31845. this._scene.materials.splice(index, 1);
  31846. }
  31847. // Remove from meshes
  31848. for (index = 0; index < this._scene.meshes.length; index++) {
  31849. var mesh = this._scene.meshes[index];
  31850. if (mesh.material === this) {
  31851. mesh.material = null;
  31852. if (mesh.geometry) {
  31853. var geometry = (mesh.geometry);
  31854. if (this.storeEffectOnSubMeshes) {
  31855. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31856. var subMesh = _a[_i];
  31857. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31858. if (forceDisposeEffect && subMesh._materialEffect) {
  31859. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31860. }
  31861. }
  31862. }
  31863. else {
  31864. geometry._releaseVertexArrayObject(this._effect);
  31865. }
  31866. }
  31867. }
  31868. }
  31869. this._uniformBuffer.dispose();
  31870. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31871. if (forceDisposeEffect && this._effect) {
  31872. if (!this.storeEffectOnSubMeshes) {
  31873. this._scene.getEngine()._releaseEffect(this._effect);
  31874. }
  31875. this._effect = null;
  31876. }
  31877. // Callback
  31878. this.onDisposeObservable.notifyObservers(this);
  31879. this.onDisposeObservable.clear();
  31880. this.onBindObservable.clear();
  31881. this.onUnBindObservable.clear();
  31882. };
  31883. /**
  31884. * Serializes this material.
  31885. * @returns - serialized material object.
  31886. */
  31887. Material.prototype.serialize = function () {
  31888. return BABYLON.SerializationHelper.Serialize(this);
  31889. };
  31890. /**
  31891. * Creates a MultiMaterial from parse MultiMaterial data.
  31892. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31893. * @param scene - BJS scene.
  31894. * @returns - MultiMaterial.
  31895. */
  31896. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31897. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31898. multiMaterial.id = parsedMultiMaterial.id;
  31899. if (BABYLON.Tags) {
  31900. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31901. }
  31902. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31903. var subMatId = parsedMultiMaterial.materials[matIndex];
  31904. if (subMatId) {
  31905. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31906. }
  31907. else {
  31908. multiMaterial.subMaterials.push(null);
  31909. }
  31910. }
  31911. return multiMaterial;
  31912. };
  31913. /**
  31914. * Creates a material from parsed material data.
  31915. * @param parsedMaterial - Parsed material data.
  31916. * @param scene - BJS scene.
  31917. * @param rootUrl - Root URL containing the material information.
  31918. * @returns - Parsed material.
  31919. */
  31920. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31921. if (!parsedMaterial.customType) {
  31922. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31923. }
  31924. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31925. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31926. if (!BABYLON.LegacyPBRMaterial) {
  31927. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31928. return;
  31929. }
  31930. }
  31931. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31932. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31933. ;
  31934. };
  31935. // Triangle views
  31936. Material._TriangleFillMode = 0;
  31937. Material._WireFrameFillMode = 1;
  31938. Material._PointFillMode = 2;
  31939. // Draw modes
  31940. Material._PointListDrawMode = 3;
  31941. Material._LineListDrawMode = 4;
  31942. Material._LineLoopDrawMode = 5;
  31943. Material._LineStripDrawMode = 6;
  31944. Material._TriangleStripDrawMode = 7;
  31945. Material._TriangleFanDrawMode = 8;
  31946. /**
  31947. * Stores the clock-wise side orientation.
  31948. */
  31949. Material._ClockWiseSideOrientation = 0;
  31950. /**
  31951. * Stores the counter clock-wise side orientation.
  31952. */
  31953. Material._CounterClockWiseSideOrientation = 1;
  31954. /**
  31955. * The dirty texture flag value.
  31956. */
  31957. Material._TextureDirtyFlag = 1;
  31958. /**
  31959. * The dirty light flag value.
  31960. */
  31961. Material._LightDirtyFlag = 2;
  31962. /**
  31963. * The dirty fresnel flag value.
  31964. */
  31965. Material._FresnelDirtyFlag = 4;
  31966. /**
  31967. * The dirty attribute flag value.
  31968. */
  31969. Material._AttributesDirtyFlag = 8;
  31970. /**
  31971. * The dirty misc flag value.
  31972. */
  31973. Material._MiscDirtyFlag = 16;
  31974. __decorate([
  31975. BABYLON.serialize()
  31976. ], Material.prototype, "id", void 0);
  31977. __decorate([
  31978. BABYLON.serialize()
  31979. ], Material.prototype, "name", void 0);
  31980. __decorate([
  31981. BABYLON.serialize()
  31982. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31983. __decorate([
  31984. BABYLON.serialize()
  31985. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31986. __decorate([
  31987. BABYLON.serialize()
  31988. ], Material.prototype, "state", void 0);
  31989. __decorate([
  31990. BABYLON.serialize("alpha")
  31991. ], Material.prototype, "_alpha", void 0);
  31992. __decorate([
  31993. BABYLON.serialize("backFaceCulling")
  31994. ], Material.prototype, "_backFaceCulling", void 0);
  31995. __decorate([
  31996. BABYLON.serialize()
  31997. ], Material.prototype, "sideOrientation", void 0);
  31998. __decorate([
  31999. BABYLON.serialize("alphaMode")
  32000. ], Material.prototype, "_alphaMode", void 0);
  32001. __decorate([
  32002. BABYLON.serialize()
  32003. ], Material.prototype, "_needDepthPrePass", void 0);
  32004. __decorate([
  32005. BABYLON.serialize()
  32006. ], Material.prototype, "disableDepthWrite", void 0);
  32007. __decorate([
  32008. BABYLON.serialize()
  32009. ], Material.prototype, "forceDepthWrite", void 0);
  32010. __decorate([
  32011. BABYLON.serialize()
  32012. ], Material.prototype, "separateCullingPass", void 0);
  32013. __decorate([
  32014. BABYLON.serialize("fogEnabled")
  32015. ], Material.prototype, "_fogEnabled", void 0);
  32016. __decorate([
  32017. BABYLON.serialize()
  32018. ], Material.prototype, "pointSize", void 0);
  32019. __decorate([
  32020. BABYLON.serialize()
  32021. ], Material.prototype, "zOffset", void 0);
  32022. __decorate([
  32023. BABYLON.serialize()
  32024. ], Material.prototype, "wireframe", null);
  32025. __decorate([
  32026. BABYLON.serialize()
  32027. ], Material.prototype, "pointsCloud", null);
  32028. __decorate([
  32029. BABYLON.serialize()
  32030. ], Material.prototype, "fillMode", null);
  32031. return Material;
  32032. }());
  32033. BABYLON.Material = Material;
  32034. })(BABYLON || (BABYLON = {}));
  32035. //# sourceMappingURL=babylon.material.js.map
  32036. var BABYLON;
  32037. (function (BABYLON) {
  32038. var UniformBuffer = /** @class */ (function () {
  32039. /**
  32040. * Uniform buffer objects.
  32041. *
  32042. * Handles blocks of uniform on the GPU.
  32043. *
  32044. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32045. *
  32046. * For more information, please refer to :
  32047. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32048. */
  32049. function UniformBuffer(engine, data, dynamic) {
  32050. this._engine = engine;
  32051. this._noUBO = !engine.supportsUniformBuffers;
  32052. this._dynamic = dynamic;
  32053. this._data = data || [];
  32054. this._uniformLocations = {};
  32055. this._uniformSizes = {};
  32056. this._uniformLocationPointer = 0;
  32057. this._needSync = false;
  32058. if (this._noUBO) {
  32059. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32060. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32061. this.updateFloat = this._updateFloatForEffect;
  32062. this.updateFloat2 = this._updateFloat2ForEffect;
  32063. this.updateFloat3 = this._updateFloat3ForEffect;
  32064. this.updateFloat4 = this._updateFloat4ForEffect;
  32065. this.updateMatrix = this._updateMatrixForEffect;
  32066. this.updateVector3 = this._updateVector3ForEffect;
  32067. this.updateVector4 = this._updateVector4ForEffect;
  32068. this.updateColor3 = this._updateColor3ForEffect;
  32069. this.updateColor4 = this._updateColor4ForEffect;
  32070. }
  32071. else {
  32072. this._engine._uniformBuffers.push(this);
  32073. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32074. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32075. this.updateFloat = this._updateFloatForUniform;
  32076. this.updateFloat2 = this._updateFloat2ForUniform;
  32077. this.updateFloat3 = this._updateFloat3ForUniform;
  32078. this.updateFloat4 = this._updateFloat4ForUniform;
  32079. this.updateMatrix = this._updateMatrixForUniform;
  32080. this.updateVector3 = this._updateVector3ForUniform;
  32081. this.updateVector4 = this._updateVector4ForUniform;
  32082. this.updateColor3 = this._updateColor3ForUniform;
  32083. this.updateColor4 = this._updateColor4ForUniform;
  32084. }
  32085. }
  32086. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32087. // Properties
  32088. /**
  32089. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32090. * or just falling back on setUniformXXX calls.
  32091. */
  32092. get: function () {
  32093. return !this._noUBO;
  32094. },
  32095. enumerable: true,
  32096. configurable: true
  32097. });
  32098. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32099. /**
  32100. * Indicates if the WebGL underlying uniform buffer is in sync
  32101. * with the javascript cache data.
  32102. */
  32103. get: function () {
  32104. return !this._needSync;
  32105. },
  32106. enumerable: true,
  32107. configurable: true
  32108. });
  32109. /**
  32110. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32111. * Also, a dynamic UniformBuffer will disable cache verification and always
  32112. * update the underlying WebGL uniform buffer to the GPU.
  32113. */
  32114. UniformBuffer.prototype.isDynamic = function () {
  32115. return this._dynamic !== undefined;
  32116. };
  32117. /**
  32118. * The data cache on JS side.
  32119. */
  32120. UniformBuffer.prototype.getData = function () {
  32121. return this._bufferData;
  32122. };
  32123. /**
  32124. * The underlying WebGL Uniform buffer.
  32125. */
  32126. UniformBuffer.prototype.getBuffer = function () {
  32127. return this._buffer;
  32128. };
  32129. /**
  32130. * std140 layout specifies how to align data within an UBO structure.
  32131. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32132. * for specs.
  32133. */
  32134. UniformBuffer.prototype._fillAlignment = function (size) {
  32135. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32136. // and 4x4 matrices
  32137. // TODO : change if other types are used
  32138. var alignment;
  32139. if (size <= 2) {
  32140. alignment = size;
  32141. }
  32142. else {
  32143. alignment = 4;
  32144. }
  32145. if ((this._uniformLocationPointer % alignment) !== 0) {
  32146. var oldPointer = this._uniformLocationPointer;
  32147. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32148. var diff = this._uniformLocationPointer - oldPointer;
  32149. for (var i = 0; i < diff; i++) {
  32150. this._data.push(0);
  32151. }
  32152. }
  32153. };
  32154. /**
  32155. * Adds an uniform in the buffer.
  32156. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32157. * for the layout to be correct !
  32158. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32159. * @param {number|number[]} size Data size, or data directly.
  32160. */
  32161. UniformBuffer.prototype.addUniform = function (name, size) {
  32162. if (this._noUBO) {
  32163. return;
  32164. }
  32165. if (this._uniformLocations[name] !== undefined) {
  32166. // Already existing uniform
  32167. return;
  32168. }
  32169. // This function must be called in the order of the shader layout !
  32170. // size can be the size of the uniform, or data directly
  32171. var data;
  32172. if (size instanceof Array) {
  32173. data = size;
  32174. size = data.length;
  32175. }
  32176. else {
  32177. size = size;
  32178. data = [];
  32179. // Fill with zeros
  32180. for (var i = 0; i < size; i++) {
  32181. data.push(0);
  32182. }
  32183. }
  32184. this._fillAlignment(size);
  32185. this._uniformSizes[name] = size;
  32186. this._uniformLocations[name] = this._uniformLocationPointer;
  32187. this._uniformLocationPointer += size;
  32188. for (var i = 0; i < size; i++) {
  32189. this._data.push(data[i]);
  32190. }
  32191. this._needSync = true;
  32192. };
  32193. /**
  32194. * Wrapper for addUniform.
  32195. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32196. * @param {Matrix} mat A 4x4 matrix.
  32197. */
  32198. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32199. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32200. };
  32201. /**
  32202. * Wrapper for addUniform.
  32203. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32204. * @param {number} x
  32205. * @param {number} y
  32206. */
  32207. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32208. var temp = [x, y];
  32209. this.addUniform(name, temp);
  32210. };
  32211. /**
  32212. * Wrapper for addUniform.
  32213. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32214. * @param {number} x
  32215. * @param {number} y
  32216. * @param {number} z
  32217. */
  32218. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32219. var temp = [x, y, z];
  32220. this.addUniform(name, temp);
  32221. };
  32222. /**
  32223. * Wrapper for addUniform.
  32224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32225. * @param {Color3} color
  32226. */
  32227. UniformBuffer.prototype.addColor3 = function (name, color) {
  32228. var temp = new Array();
  32229. color.toArray(temp);
  32230. this.addUniform(name, temp);
  32231. };
  32232. /**
  32233. * Wrapper for addUniform.
  32234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32235. * @param {Color3} color
  32236. * @param {number} alpha
  32237. */
  32238. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32239. var temp = new Array();
  32240. color.toArray(temp);
  32241. temp.push(alpha);
  32242. this.addUniform(name, temp);
  32243. };
  32244. /**
  32245. * Wrapper for addUniform.
  32246. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32247. * @param {Vector3} vector
  32248. */
  32249. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32250. var temp = new Array();
  32251. vector.toArray(temp);
  32252. this.addUniform(name, temp);
  32253. };
  32254. /**
  32255. * Wrapper for addUniform.
  32256. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32257. */
  32258. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32259. this.addUniform(name, 12);
  32260. };
  32261. /**
  32262. * Wrapper for addUniform.
  32263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32264. */
  32265. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32266. this.addUniform(name, 8);
  32267. };
  32268. /**
  32269. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32270. */
  32271. UniformBuffer.prototype.create = function () {
  32272. if (this._noUBO) {
  32273. return;
  32274. }
  32275. if (this._buffer) {
  32276. return; // nothing to do
  32277. }
  32278. // See spec, alignment must be filled as a vec4
  32279. this._fillAlignment(4);
  32280. this._bufferData = new Float32Array(this._data);
  32281. this._rebuild();
  32282. this._needSync = true;
  32283. };
  32284. UniformBuffer.prototype._rebuild = function () {
  32285. if (this._noUBO) {
  32286. return;
  32287. }
  32288. if (this._dynamic) {
  32289. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32290. }
  32291. else {
  32292. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32293. }
  32294. };
  32295. /**
  32296. * Updates the WebGL Uniform Buffer on the GPU.
  32297. * If the `dynamic` flag is set to true, no cache comparison is done.
  32298. * Otherwise, the buffer will be updated only if the cache differs.
  32299. */
  32300. UniformBuffer.prototype.update = function () {
  32301. if (!this._buffer) {
  32302. this.create();
  32303. return;
  32304. }
  32305. if (!this._dynamic && !this._needSync) {
  32306. return;
  32307. }
  32308. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32309. this._needSync = false;
  32310. };
  32311. /**
  32312. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32313. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32314. * @param {number[]|Float32Array} data Flattened data
  32315. * @param {number} size Size of the data.
  32316. */
  32317. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32318. var location = this._uniformLocations[uniformName];
  32319. if (location === undefined) {
  32320. if (this._buffer) {
  32321. // Cannot add an uniform if the buffer is already created
  32322. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32323. return;
  32324. }
  32325. this.addUniform(uniformName, size);
  32326. location = this._uniformLocations[uniformName];
  32327. }
  32328. if (!this._buffer) {
  32329. this.create();
  32330. }
  32331. if (!this._dynamic) {
  32332. // Cache for static uniform buffers
  32333. var changed = false;
  32334. for (var i = 0; i < size; i++) {
  32335. if (this._bufferData[location + i] !== data[i]) {
  32336. changed = true;
  32337. this._bufferData[location + i] = data[i];
  32338. }
  32339. }
  32340. this._needSync = this._needSync || changed;
  32341. }
  32342. else {
  32343. // No cache for dynamic
  32344. for (var i = 0; i < size; i++) {
  32345. this._bufferData[location + i] = data[i];
  32346. }
  32347. }
  32348. };
  32349. // Update methods
  32350. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32351. // To match std140, matrix must be realigned
  32352. for (var i = 0; i < 3; i++) {
  32353. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32354. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32355. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32356. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32357. }
  32358. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32359. };
  32360. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32361. this._currentEffect.setMatrix3x3(name, matrix);
  32362. };
  32363. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32364. this._currentEffect.setMatrix2x2(name, matrix);
  32365. };
  32366. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32367. // To match std140, matrix must be realigned
  32368. for (var i = 0; i < 2; i++) {
  32369. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32370. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32371. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32372. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32373. }
  32374. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32375. };
  32376. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32377. this._currentEffect.setFloat(name, x);
  32378. };
  32379. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32380. UniformBuffer._tempBuffer[0] = x;
  32381. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32382. };
  32383. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32384. if (suffix === void 0) { suffix = ""; }
  32385. this._currentEffect.setFloat2(name + suffix, x, y);
  32386. };
  32387. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32388. if (suffix === void 0) { suffix = ""; }
  32389. UniformBuffer._tempBuffer[0] = x;
  32390. UniformBuffer._tempBuffer[1] = y;
  32391. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32392. };
  32393. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32394. if (suffix === void 0) { suffix = ""; }
  32395. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32396. };
  32397. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32398. if (suffix === void 0) { suffix = ""; }
  32399. UniformBuffer._tempBuffer[0] = x;
  32400. UniformBuffer._tempBuffer[1] = y;
  32401. UniformBuffer._tempBuffer[2] = z;
  32402. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32403. };
  32404. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32405. if (suffix === void 0) { suffix = ""; }
  32406. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32407. };
  32408. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32409. if (suffix === void 0) { suffix = ""; }
  32410. UniformBuffer._tempBuffer[0] = x;
  32411. UniformBuffer._tempBuffer[1] = y;
  32412. UniformBuffer._tempBuffer[2] = z;
  32413. UniformBuffer._tempBuffer[3] = w;
  32414. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32415. };
  32416. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32417. this._currentEffect.setMatrix(name, mat);
  32418. };
  32419. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32420. this.updateUniform(name, mat.toArray(), 16);
  32421. };
  32422. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32423. this._currentEffect.setVector3(name, vector);
  32424. };
  32425. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32426. vector.toArray(UniformBuffer._tempBuffer);
  32427. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32428. };
  32429. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32430. this._currentEffect.setVector4(name, vector);
  32431. };
  32432. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32433. vector.toArray(UniformBuffer._tempBuffer);
  32434. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32435. };
  32436. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32437. if (suffix === void 0) { suffix = ""; }
  32438. this._currentEffect.setColor3(name + suffix, color);
  32439. };
  32440. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32441. if (suffix === void 0) { suffix = ""; }
  32442. color.toArray(UniformBuffer._tempBuffer);
  32443. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32444. };
  32445. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32446. if (suffix === void 0) { suffix = ""; }
  32447. this._currentEffect.setColor4(name + suffix, color, alpha);
  32448. };
  32449. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32450. if (suffix === void 0) { suffix = ""; }
  32451. color.toArray(UniformBuffer._tempBuffer);
  32452. UniformBuffer._tempBuffer[3] = alpha;
  32453. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32454. };
  32455. /**
  32456. * Sets a sampler uniform on the effect.
  32457. * @param {string} name Name of the sampler.
  32458. * @param {Texture} texture
  32459. */
  32460. UniformBuffer.prototype.setTexture = function (name, texture) {
  32461. this._currentEffect.setTexture(name, texture);
  32462. };
  32463. /**
  32464. * Directly updates the value of the uniform in the cache AND on the GPU.
  32465. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32466. * @param {number[]|Float32Array} data Flattened data
  32467. */
  32468. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32469. this.updateUniform(uniformName, data, data.length);
  32470. this.update();
  32471. };
  32472. /**
  32473. * Binds this uniform buffer to an effect.
  32474. * @param {Effect} effect
  32475. * @param {string} name Name of the uniform block in the shader.
  32476. */
  32477. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32478. this._currentEffect = effect;
  32479. if (this._noUBO || !this._buffer) {
  32480. return;
  32481. }
  32482. effect.bindUniformBuffer(this._buffer, name);
  32483. };
  32484. /**
  32485. * Disposes the uniform buffer.
  32486. */
  32487. UniformBuffer.prototype.dispose = function () {
  32488. if (this._noUBO) {
  32489. return;
  32490. }
  32491. var index = this._engine._uniformBuffers.indexOf(this);
  32492. if (index !== -1) {
  32493. this._engine._uniformBuffers.splice(index, 1);
  32494. }
  32495. if (!this._buffer) {
  32496. return;
  32497. }
  32498. if (this._engine._releaseBuffer(this._buffer)) {
  32499. this._buffer = null;
  32500. }
  32501. };
  32502. // Pool for avoiding memory leaks
  32503. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32504. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32505. return UniformBuffer;
  32506. }());
  32507. BABYLON.UniformBuffer = UniformBuffer;
  32508. })(BABYLON || (BABYLON = {}));
  32509. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32510. var BABYLON;
  32511. (function (BABYLON) {
  32512. var VertexData = /** @class */ (function () {
  32513. function VertexData() {
  32514. }
  32515. VertexData.prototype.set = function (data, kind) {
  32516. switch (kind) {
  32517. case BABYLON.VertexBuffer.PositionKind:
  32518. this.positions = data;
  32519. break;
  32520. case BABYLON.VertexBuffer.NormalKind:
  32521. this.normals = data;
  32522. break;
  32523. case BABYLON.VertexBuffer.TangentKind:
  32524. this.tangents = data;
  32525. break;
  32526. case BABYLON.VertexBuffer.UVKind:
  32527. this.uvs = data;
  32528. break;
  32529. case BABYLON.VertexBuffer.UV2Kind:
  32530. this.uvs2 = data;
  32531. break;
  32532. case BABYLON.VertexBuffer.UV3Kind:
  32533. this.uvs3 = data;
  32534. break;
  32535. case BABYLON.VertexBuffer.UV4Kind:
  32536. this.uvs4 = data;
  32537. break;
  32538. case BABYLON.VertexBuffer.UV5Kind:
  32539. this.uvs5 = data;
  32540. break;
  32541. case BABYLON.VertexBuffer.UV6Kind:
  32542. this.uvs6 = data;
  32543. break;
  32544. case BABYLON.VertexBuffer.ColorKind:
  32545. this.colors = data;
  32546. break;
  32547. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32548. this.matricesIndices = data;
  32549. break;
  32550. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32551. this.matricesWeights = data;
  32552. break;
  32553. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32554. this.matricesIndicesExtra = data;
  32555. break;
  32556. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32557. this.matricesWeightsExtra = data;
  32558. break;
  32559. }
  32560. };
  32561. /**
  32562. * Associates the vertexData to the passed Mesh.
  32563. * Sets it as updatable or not (default `false`).
  32564. * Returns the VertexData.
  32565. */
  32566. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32567. this._applyTo(mesh, updatable);
  32568. return this;
  32569. };
  32570. /**
  32571. * Associates the vertexData to the passed Geometry.
  32572. * Sets it as updatable or not (default `false`).
  32573. * Returns the VertexData.
  32574. */
  32575. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32576. this._applyTo(geometry, updatable);
  32577. return this;
  32578. };
  32579. /**
  32580. * Updates the associated mesh.
  32581. * Returns the VertexData.
  32582. */
  32583. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32584. this._update(mesh);
  32585. return this;
  32586. };
  32587. /**
  32588. * Updates the associated geometry.
  32589. * Returns the VertexData.
  32590. */
  32591. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32592. this._update(geometry);
  32593. return this;
  32594. };
  32595. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32596. if (updatable === void 0) { updatable = false; }
  32597. if (this.positions) {
  32598. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32599. }
  32600. if (this.normals) {
  32601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32602. }
  32603. if (this.tangents) {
  32604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32605. }
  32606. if (this.uvs) {
  32607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32608. }
  32609. if (this.uvs2) {
  32610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32611. }
  32612. if (this.uvs3) {
  32613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32614. }
  32615. if (this.uvs4) {
  32616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32617. }
  32618. if (this.uvs5) {
  32619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32620. }
  32621. if (this.uvs6) {
  32622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32623. }
  32624. if (this.colors) {
  32625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32626. }
  32627. if (this.matricesIndices) {
  32628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32629. }
  32630. if (this.matricesWeights) {
  32631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32632. }
  32633. if (this.matricesIndicesExtra) {
  32634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32635. }
  32636. if (this.matricesWeightsExtra) {
  32637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32638. }
  32639. if (this.indices) {
  32640. meshOrGeometry.setIndices(this.indices, null, updatable);
  32641. }
  32642. return this;
  32643. };
  32644. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32645. if (this.positions) {
  32646. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32647. }
  32648. if (this.normals) {
  32649. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32650. }
  32651. if (this.tangents) {
  32652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32653. }
  32654. if (this.uvs) {
  32655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32656. }
  32657. if (this.uvs2) {
  32658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32659. }
  32660. if (this.uvs3) {
  32661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32662. }
  32663. if (this.uvs4) {
  32664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32665. }
  32666. if (this.uvs5) {
  32667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32668. }
  32669. if (this.uvs6) {
  32670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32671. }
  32672. if (this.colors) {
  32673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32674. }
  32675. if (this.matricesIndices) {
  32676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32677. }
  32678. if (this.matricesWeights) {
  32679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32680. }
  32681. if (this.matricesIndicesExtra) {
  32682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32683. }
  32684. if (this.matricesWeightsExtra) {
  32685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32686. }
  32687. if (this.indices) {
  32688. meshOrGeometry.setIndices(this.indices, null);
  32689. }
  32690. return this;
  32691. };
  32692. /**
  32693. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32694. * Returns the VertexData.
  32695. */
  32696. VertexData.prototype.transform = function (matrix) {
  32697. var transformed = BABYLON.Vector3.Zero();
  32698. var index;
  32699. if (this.positions) {
  32700. var position = BABYLON.Vector3.Zero();
  32701. for (index = 0; index < this.positions.length; index += 3) {
  32702. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32703. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32704. this.positions[index] = transformed.x;
  32705. this.positions[index + 1] = transformed.y;
  32706. this.positions[index + 2] = transformed.z;
  32707. }
  32708. }
  32709. if (this.normals) {
  32710. var normal = BABYLON.Vector3.Zero();
  32711. for (index = 0; index < this.normals.length; index += 3) {
  32712. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32713. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32714. this.normals[index] = transformed.x;
  32715. this.normals[index + 1] = transformed.y;
  32716. this.normals[index + 2] = transformed.z;
  32717. }
  32718. }
  32719. if (this.tangents) {
  32720. var tangent = BABYLON.Vector4.Zero();
  32721. var tangentTransformed = BABYLON.Vector4.Zero();
  32722. for (index = 0; index < this.tangents.length; index += 4) {
  32723. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32724. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32725. this.tangents[index] = tangentTransformed.x;
  32726. this.tangents[index + 1] = tangentTransformed.y;
  32727. this.tangents[index + 2] = tangentTransformed.z;
  32728. this.tangents[index + 3] = tangentTransformed.w;
  32729. }
  32730. }
  32731. return this;
  32732. };
  32733. /**
  32734. * Merges the passed VertexData into the current one.
  32735. * Returns the modified VertexData.
  32736. */
  32737. VertexData.prototype.merge = function (other) {
  32738. this._validate();
  32739. other._validate();
  32740. if (!this.normals !== !other.normals ||
  32741. !this.tangents !== !other.tangents ||
  32742. !this.uvs !== !other.uvs ||
  32743. !this.uvs2 !== !other.uvs2 ||
  32744. !this.uvs3 !== !other.uvs3 ||
  32745. !this.uvs4 !== !other.uvs4 ||
  32746. !this.uvs5 !== !other.uvs5 ||
  32747. !this.uvs6 !== !other.uvs6 ||
  32748. !this.colors !== !other.colors ||
  32749. !this.matricesIndices !== !other.matricesIndices ||
  32750. !this.matricesWeights !== !other.matricesWeights ||
  32751. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32752. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32753. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32754. }
  32755. if (other.indices) {
  32756. if (!this.indices) {
  32757. this.indices = [];
  32758. }
  32759. var offset = this.positions ? this.positions.length / 3 : 0;
  32760. for (var index = 0; index < other.indices.length; index++) {
  32761. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32762. this.indices.push(other.indices[index] + offset);
  32763. }
  32764. }
  32765. this.positions = this._mergeElement(this.positions, other.positions);
  32766. this.normals = this._mergeElement(this.normals, other.normals);
  32767. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32768. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32769. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32770. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32771. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32772. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32773. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32774. this.colors = this._mergeElement(this.colors, other.colors);
  32775. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32776. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32777. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32778. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32779. return this;
  32780. };
  32781. VertexData.prototype._mergeElement = function (source, other) {
  32782. if (!source) {
  32783. return other;
  32784. }
  32785. if (!other) {
  32786. return source;
  32787. }
  32788. var len = other.length + source.length;
  32789. var isSrcTypedArray = source instanceof Float32Array;
  32790. var isOthTypedArray = other instanceof Float32Array;
  32791. // use non-loop method when the source is Float32Array
  32792. if (isSrcTypedArray) {
  32793. var ret32 = new Float32Array(len);
  32794. ret32.set(source);
  32795. ret32.set(other, source.length);
  32796. return ret32;
  32797. // source is number[], when other is also use concat
  32798. }
  32799. else if (!isOthTypedArray) {
  32800. return source.concat(other);
  32801. // source is a number[], but other is a Float32Array, loop required
  32802. }
  32803. else {
  32804. var ret = source.slice(0); // copy source to a separate array
  32805. for (var i = 0, len = other.length; i < len; i++) {
  32806. ret.push(other[i]);
  32807. }
  32808. return ret;
  32809. }
  32810. };
  32811. VertexData.prototype._validate = function () {
  32812. if (!this.positions) {
  32813. throw new Error("Positions are required");
  32814. }
  32815. var getElementCount = function (kind, values) {
  32816. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32817. if ((values.length % stride) !== 0) {
  32818. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32819. }
  32820. return values.length / stride;
  32821. };
  32822. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32823. var validateElementCount = function (kind, values) {
  32824. var elementCount = getElementCount(kind, values);
  32825. if (elementCount !== positionsElementCount) {
  32826. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32827. }
  32828. };
  32829. if (this.normals)
  32830. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32831. if (this.tangents)
  32832. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32833. if (this.uvs)
  32834. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32835. if (this.uvs2)
  32836. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32837. if (this.uvs3)
  32838. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32839. if (this.uvs4)
  32840. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32841. if (this.uvs5)
  32842. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32843. if (this.uvs6)
  32844. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32845. if (this.colors)
  32846. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32847. if (this.matricesIndices)
  32848. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32849. if (this.matricesWeights)
  32850. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32851. if (this.matricesIndicesExtra)
  32852. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32853. if (this.matricesWeightsExtra)
  32854. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32855. };
  32856. /**
  32857. * Serializes the VertexData.
  32858. * Returns a serialized object.
  32859. */
  32860. VertexData.prototype.serialize = function () {
  32861. var serializationObject = this.serialize();
  32862. if (this.positions) {
  32863. serializationObject.positions = this.positions;
  32864. }
  32865. if (this.normals) {
  32866. serializationObject.normals = this.normals;
  32867. }
  32868. if (this.tangents) {
  32869. serializationObject.tangents = this.tangents;
  32870. }
  32871. if (this.uvs) {
  32872. serializationObject.uvs = this.uvs;
  32873. }
  32874. if (this.uvs2) {
  32875. serializationObject.uvs2 = this.uvs2;
  32876. }
  32877. if (this.uvs3) {
  32878. serializationObject.uvs3 = this.uvs3;
  32879. }
  32880. if (this.uvs4) {
  32881. serializationObject.uvs4 = this.uvs4;
  32882. }
  32883. if (this.uvs5) {
  32884. serializationObject.uvs5 = this.uvs5;
  32885. }
  32886. if (this.uvs6) {
  32887. serializationObject.uvs6 = this.uvs6;
  32888. }
  32889. if (this.colors) {
  32890. serializationObject.colors = this.colors;
  32891. }
  32892. if (this.matricesIndices) {
  32893. serializationObject.matricesIndices = this.matricesIndices;
  32894. serializationObject.matricesIndices._isExpanded = true;
  32895. }
  32896. if (this.matricesWeights) {
  32897. serializationObject.matricesWeights = this.matricesWeights;
  32898. }
  32899. if (this.matricesIndicesExtra) {
  32900. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32901. serializationObject.matricesIndicesExtra._isExpanded = true;
  32902. }
  32903. if (this.matricesWeightsExtra) {
  32904. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32905. }
  32906. serializationObject.indices = this.indices;
  32907. return serializationObject;
  32908. };
  32909. // Statics
  32910. /**
  32911. * Returns the object VertexData associated to the passed mesh.
  32912. */
  32913. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32914. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32915. };
  32916. /**
  32917. * Returns the object VertexData associated to the passed geometry.
  32918. */
  32919. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32920. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32921. };
  32922. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32923. var result = new VertexData();
  32924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32925. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32926. }
  32927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32928. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32929. }
  32930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32931. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32932. }
  32933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32934. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32935. }
  32936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32937. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32938. }
  32939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32940. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32941. }
  32942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32943. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32944. }
  32945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32946. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32947. }
  32948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32949. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32950. }
  32951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32952. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32953. }
  32954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32955. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32956. }
  32957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32958. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32959. }
  32960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32961. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32962. }
  32963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32964. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32965. }
  32966. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32967. return result;
  32968. };
  32969. /**
  32970. * Creates the vertexData of the Ribbon.
  32971. */
  32972. VertexData.CreateRibbon = function (options) {
  32973. var pathArray = options.pathArray;
  32974. var closeArray = options.closeArray || false;
  32975. var closePath = options.closePath || false;
  32976. var invertUV = options.invertUV || false;
  32977. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32978. var offset = options.offset || defaultOffset;
  32979. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32980. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32981. var customUV = options.uvs;
  32982. var customColors = options.colors;
  32983. var positions = [];
  32984. var indices = [];
  32985. var normals = [];
  32986. var uvs = [];
  32987. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32988. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32989. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32990. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32991. var minlg; // minimal length among all paths from pathArray
  32992. var lg = []; // array of path lengths : nb of vertex per path
  32993. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32994. var p; // path iterator
  32995. var i; // point iterator
  32996. var j; // point iterator
  32997. // if single path in pathArray
  32998. if (pathArray.length < 2) {
  32999. var ar1 = [];
  33000. var ar2 = [];
  33001. for (i = 0; i < pathArray[0].length - offset; i++) {
  33002. ar1.push(pathArray[0][i]);
  33003. ar2.push(pathArray[0][i + offset]);
  33004. }
  33005. pathArray = [ar1, ar2];
  33006. }
  33007. // positions and horizontal distances (u)
  33008. var idc = 0;
  33009. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33010. var path;
  33011. var l;
  33012. minlg = pathArray[0].length;
  33013. var vectlg;
  33014. var dist;
  33015. for (p = 0; p < pathArray.length; p++) {
  33016. uTotalDistance[p] = 0;
  33017. us[p] = [0];
  33018. path = pathArray[p];
  33019. l = path.length;
  33020. minlg = (minlg < l) ? minlg : l;
  33021. j = 0;
  33022. while (j < l) {
  33023. positions.push(path[j].x, path[j].y, path[j].z);
  33024. if (j > 0) {
  33025. vectlg = path[j].subtract(path[j - 1]).length();
  33026. dist = vectlg + uTotalDistance[p];
  33027. us[p].push(dist);
  33028. uTotalDistance[p] = dist;
  33029. }
  33030. j++;
  33031. }
  33032. if (closePath) {
  33033. j--;
  33034. positions.push(path[0].x, path[0].y, path[0].z);
  33035. vectlg = path[j].subtract(path[0]).length();
  33036. dist = vectlg + uTotalDistance[p];
  33037. us[p].push(dist);
  33038. uTotalDistance[p] = dist;
  33039. }
  33040. lg[p] = l + closePathCorr;
  33041. idx[p] = idc;
  33042. idc += (l + closePathCorr);
  33043. }
  33044. // vertical distances (v)
  33045. var path1;
  33046. var path2;
  33047. var vertex1 = null;
  33048. var vertex2 = null;
  33049. for (i = 0; i < minlg + closePathCorr; i++) {
  33050. vTotalDistance[i] = 0;
  33051. vs[i] = [0];
  33052. for (p = 0; p < pathArray.length - 1; p++) {
  33053. path1 = pathArray[p];
  33054. path2 = pathArray[p + 1];
  33055. if (i === minlg) {
  33056. vertex1 = path1[0];
  33057. vertex2 = path2[0];
  33058. }
  33059. else {
  33060. vertex1 = path1[i];
  33061. vertex2 = path2[i];
  33062. }
  33063. vectlg = vertex2.subtract(vertex1).length();
  33064. dist = vectlg + vTotalDistance[i];
  33065. vs[i].push(dist);
  33066. vTotalDistance[i] = dist;
  33067. }
  33068. if (closeArray && vertex2 && vertex1) {
  33069. path1 = pathArray[p];
  33070. path2 = pathArray[0];
  33071. if (i === minlg) {
  33072. vertex2 = path2[0];
  33073. }
  33074. vectlg = vertex2.subtract(vertex1).length();
  33075. dist = vectlg + vTotalDistance[i];
  33076. vTotalDistance[i] = dist;
  33077. }
  33078. }
  33079. // uvs
  33080. var u;
  33081. var v;
  33082. if (customUV) {
  33083. for (p = 0; p < customUV.length; p++) {
  33084. uvs.push(customUV[p].x, customUV[p].y);
  33085. }
  33086. }
  33087. else {
  33088. for (p = 0; p < pathArray.length; p++) {
  33089. for (i = 0; i < minlg + closePathCorr; i++) {
  33090. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33091. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33092. if (invertUV) {
  33093. uvs.push(v, u);
  33094. }
  33095. else {
  33096. uvs.push(u, v);
  33097. }
  33098. }
  33099. }
  33100. }
  33101. // indices
  33102. p = 0; // path index
  33103. var pi = 0; // positions array index
  33104. var l1 = lg[p] - 1; // path1 length
  33105. var l2 = lg[p + 1] - 1; // path2 length
  33106. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33107. var shft = idx[1] - idx[0]; // shift
  33108. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33109. while (pi <= min && p < path1nb) {
  33110. // 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
  33111. indices.push(pi, pi + shft, pi + 1);
  33112. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33113. pi += 1;
  33114. if (pi === min) {
  33115. p++;
  33116. if (p === lg.length - 1) {
  33117. shft = idx[0] - idx[p];
  33118. l1 = lg[p] - 1;
  33119. l2 = lg[0] - 1;
  33120. }
  33121. else {
  33122. shft = idx[p + 1] - idx[p];
  33123. l1 = lg[p] - 1;
  33124. l2 = lg[p + 1] - 1;
  33125. }
  33126. pi = idx[p];
  33127. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33128. }
  33129. }
  33130. // normals
  33131. VertexData.ComputeNormals(positions, indices, normals);
  33132. if (closePath) {
  33133. var indexFirst = 0;
  33134. var indexLast = 0;
  33135. for (p = 0; p < pathArray.length; p++) {
  33136. indexFirst = idx[p] * 3;
  33137. if (p + 1 < pathArray.length) {
  33138. indexLast = (idx[p + 1] - 1) * 3;
  33139. }
  33140. else {
  33141. indexLast = normals.length - 3;
  33142. }
  33143. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33144. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33145. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33146. normals[indexLast] = normals[indexFirst];
  33147. normals[indexLast + 1] = normals[indexFirst + 1];
  33148. normals[indexLast + 2] = normals[indexFirst + 2];
  33149. }
  33150. }
  33151. // sides
  33152. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33153. // Colors
  33154. var colors = null;
  33155. if (customColors) {
  33156. colors = new Float32Array(customColors.length * 4);
  33157. for (var c = 0; c < customColors.length; c++) {
  33158. colors[c * 4] = customColors[c].r;
  33159. colors[c * 4 + 1] = customColors[c].g;
  33160. colors[c * 4 + 2] = customColors[c].b;
  33161. colors[c * 4 + 3] = customColors[c].a;
  33162. }
  33163. }
  33164. // Result
  33165. var vertexData = new VertexData();
  33166. var positions32 = new Float32Array(positions);
  33167. var normals32 = new Float32Array(normals);
  33168. var uvs32 = new Float32Array(uvs);
  33169. vertexData.indices = indices;
  33170. vertexData.positions = positions32;
  33171. vertexData.normals = normals32;
  33172. vertexData.uvs = uvs32;
  33173. if (colors) {
  33174. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33175. }
  33176. if (closePath) {
  33177. vertexData._idx = idx;
  33178. }
  33179. return vertexData;
  33180. };
  33181. /**
  33182. * Creates the VertexData of the Box.
  33183. */
  33184. VertexData.CreateBox = function (options) {
  33185. var normalsSource = [
  33186. new BABYLON.Vector3(0, 0, 1),
  33187. new BABYLON.Vector3(0, 0, -1),
  33188. new BABYLON.Vector3(1, 0, 0),
  33189. new BABYLON.Vector3(-1, 0, 0),
  33190. new BABYLON.Vector3(0, 1, 0),
  33191. new BABYLON.Vector3(0, -1, 0)
  33192. ];
  33193. var indices = [];
  33194. var positions = [];
  33195. var normals = [];
  33196. var uvs = [];
  33197. var width = options.width || options.size || 1;
  33198. var height = options.height || options.size || 1;
  33199. var depth = options.depth || options.size || 1;
  33200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33201. var faceUV = options.faceUV || new Array(6);
  33202. var faceColors = options.faceColors;
  33203. var colors = [];
  33204. // default face colors and UV if undefined
  33205. for (var f = 0; f < 6; f++) {
  33206. if (faceUV[f] === undefined) {
  33207. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33208. }
  33209. if (faceColors && faceColors[f] === undefined) {
  33210. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33211. }
  33212. }
  33213. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33214. // Create each face in turn.
  33215. for (var index = 0; index < normalsSource.length; index++) {
  33216. var normal = normalsSource[index];
  33217. // Get two vectors perpendicular to the face normal and to each other.
  33218. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33219. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33220. // Six indices (two triangles) per face.
  33221. var verticesLength = positions.length / 3;
  33222. indices.push(verticesLength);
  33223. indices.push(verticesLength + 1);
  33224. indices.push(verticesLength + 2);
  33225. indices.push(verticesLength);
  33226. indices.push(verticesLength + 2);
  33227. indices.push(verticesLength + 3);
  33228. // Four vertices per face.
  33229. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33230. positions.push(vertex.x, vertex.y, vertex.z);
  33231. normals.push(normal.x, normal.y, normal.z);
  33232. uvs.push(faceUV[index].z, faceUV[index].w);
  33233. if (faceColors) {
  33234. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33235. }
  33236. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33237. positions.push(vertex.x, vertex.y, vertex.z);
  33238. normals.push(normal.x, normal.y, normal.z);
  33239. uvs.push(faceUV[index].x, faceUV[index].w);
  33240. if (faceColors) {
  33241. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33242. }
  33243. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33244. positions.push(vertex.x, vertex.y, vertex.z);
  33245. normals.push(normal.x, normal.y, normal.z);
  33246. uvs.push(faceUV[index].x, faceUV[index].y);
  33247. if (faceColors) {
  33248. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33249. }
  33250. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33251. positions.push(vertex.x, vertex.y, vertex.z);
  33252. normals.push(normal.x, normal.y, normal.z);
  33253. uvs.push(faceUV[index].z, faceUV[index].y);
  33254. if (faceColors) {
  33255. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33256. }
  33257. }
  33258. // sides
  33259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33260. // Result
  33261. var vertexData = new VertexData();
  33262. vertexData.indices = indices;
  33263. vertexData.positions = positions;
  33264. vertexData.normals = normals;
  33265. vertexData.uvs = uvs;
  33266. if (faceColors) {
  33267. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33268. vertexData.colors = totalColors;
  33269. }
  33270. return vertexData;
  33271. };
  33272. /**
  33273. * Creates the VertexData of the Sphere.
  33274. */
  33275. VertexData.CreateSphere = function (options) {
  33276. var segments = options.segments || 32;
  33277. var diameterX = options.diameterX || options.diameter || 1;
  33278. var diameterY = options.diameterY || options.diameter || 1;
  33279. var diameterZ = options.diameterZ || options.diameter || 1;
  33280. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33281. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33282. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33283. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33284. var totalZRotationSteps = 2 + segments;
  33285. var totalYRotationSteps = 2 * totalZRotationSteps;
  33286. var indices = [];
  33287. var positions = [];
  33288. var normals = [];
  33289. var uvs = [];
  33290. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33291. var normalizedZ = zRotationStep / totalZRotationSteps;
  33292. var angleZ = normalizedZ * Math.PI * slice;
  33293. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33294. var normalizedY = yRotationStep / totalYRotationSteps;
  33295. var angleY = normalizedY * Math.PI * 2 * arc;
  33296. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33297. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33298. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33299. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33300. var vertex = complete.multiply(radius);
  33301. var normal = complete.divide(radius).normalize();
  33302. positions.push(vertex.x, vertex.y, vertex.z);
  33303. normals.push(normal.x, normal.y, normal.z);
  33304. uvs.push(normalizedY, normalizedZ);
  33305. }
  33306. if (zRotationStep > 0) {
  33307. var verticesCount = positions.length / 3;
  33308. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33309. indices.push((firstIndex));
  33310. indices.push((firstIndex + 1));
  33311. indices.push(firstIndex + totalYRotationSteps + 1);
  33312. indices.push((firstIndex + totalYRotationSteps + 1));
  33313. indices.push((firstIndex + 1));
  33314. indices.push((firstIndex + totalYRotationSteps + 2));
  33315. }
  33316. }
  33317. }
  33318. // Sides
  33319. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33320. // Result
  33321. var vertexData = new VertexData();
  33322. vertexData.indices = indices;
  33323. vertexData.positions = positions;
  33324. vertexData.normals = normals;
  33325. vertexData.uvs = uvs;
  33326. return vertexData;
  33327. };
  33328. /**
  33329. * Creates the VertexData of the Cylinder or Cone.
  33330. */
  33331. VertexData.CreateCylinder = function (options) {
  33332. var height = options.height || 2;
  33333. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33334. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33335. var tessellation = options.tessellation || 24;
  33336. var subdivisions = options.subdivisions || 1;
  33337. var hasRings = options.hasRings ? true : false;
  33338. var enclose = options.enclose ? true : false;
  33339. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33341. var faceUV = options.faceUV || new Array(3);
  33342. var faceColors = options.faceColors;
  33343. // default face colors and UV if undefined
  33344. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33345. var ringNb = (hasRings) ? subdivisions : 1;
  33346. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33347. var f;
  33348. for (f = 0; f < surfaceNb; f++) {
  33349. if (faceColors && faceColors[f] === undefined) {
  33350. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33351. }
  33352. }
  33353. for (f = 0; f < surfaceNb; f++) {
  33354. if (faceUV && faceUV[f] === undefined) {
  33355. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33356. }
  33357. }
  33358. var indices = new Array();
  33359. var positions = new Array();
  33360. var normals = new Array();
  33361. var uvs = new Array();
  33362. var colors = new Array();
  33363. var angle_step = Math.PI * 2 * arc / tessellation;
  33364. var angle;
  33365. var h;
  33366. var radius;
  33367. var tan = (diameterBottom - diameterTop) / 2 / height;
  33368. var ringVertex = BABYLON.Vector3.Zero();
  33369. var ringNormal = BABYLON.Vector3.Zero();
  33370. var ringFirstVertex = BABYLON.Vector3.Zero();
  33371. var ringFirstNormal = BABYLON.Vector3.Zero();
  33372. var quadNormal = BABYLON.Vector3.Zero();
  33373. var Y = BABYLON.Axis.Y;
  33374. // positions, normals, uvs
  33375. var i;
  33376. var j;
  33377. var r;
  33378. var ringIdx = 1;
  33379. var s = 1; // surface index
  33380. var cs = 0;
  33381. var v = 0;
  33382. for (i = 0; i <= subdivisions; i++) {
  33383. h = i / subdivisions;
  33384. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33385. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33386. for (r = 0; r < ringIdx; r++) {
  33387. if (hasRings) {
  33388. s += r;
  33389. }
  33390. if (enclose) {
  33391. s += 2 * r;
  33392. }
  33393. for (j = 0; j <= tessellation; j++) {
  33394. angle = j * angle_step;
  33395. // position
  33396. ringVertex.x = Math.cos(-angle) * radius;
  33397. ringVertex.y = -height / 2 + h * height;
  33398. ringVertex.z = Math.sin(-angle) * radius;
  33399. // normal
  33400. if (diameterTop === 0 && i === subdivisions) {
  33401. // if no top cap, reuse former normals
  33402. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33403. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33404. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33405. }
  33406. else {
  33407. ringNormal.x = ringVertex.x;
  33408. ringNormal.z = ringVertex.z;
  33409. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33410. ringNormal.normalize();
  33411. }
  33412. // keep first ring vertex values for enclose
  33413. if (j === 0) {
  33414. ringFirstVertex.copyFrom(ringVertex);
  33415. ringFirstNormal.copyFrom(ringNormal);
  33416. }
  33417. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33418. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33419. if (hasRings) {
  33420. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33421. }
  33422. else {
  33423. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33424. }
  33425. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33426. if (faceColors) {
  33427. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33428. }
  33429. }
  33430. // if enclose, add four vertices and their dedicated normals
  33431. if (arc !== 1 && enclose) {
  33432. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33433. positions.push(0, ringVertex.y, 0);
  33434. positions.push(0, ringVertex.y, 0);
  33435. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33436. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33437. quadNormal.normalize();
  33438. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33439. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33440. quadNormal.normalize();
  33441. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33442. if (hasRings) {
  33443. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33444. }
  33445. else {
  33446. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33447. }
  33448. uvs.push(faceUV[s + 1].x, v);
  33449. uvs.push(faceUV[s + 1].z, v);
  33450. if (hasRings) {
  33451. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33452. }
  33453. else {
  33454. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33455. }
  33456. uvs.push(faceUV[s + 2].x, v);
  33457. uvs.push(faceUV[s + 2].z, v);
  33458. if (faceColors) {
  33459. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33460. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33461. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33462. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33463. }
  33464. }
  33465. if (cs !== s) {
  33466. cs = s;
  33467. }
  33468. }
  33469. }
  33470. // indices
  33471. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33472. var s;
  33473. i = 0;
  33474. for (s = 0; s < subdivisions; s++) {
  33475. var i0 = 0;
  33476. var i1 = 0;
  33477. var i2 = 0;
  33478. var i3 = 0;
  33479. for (j = 0; j < tessellation; j++) {
  33480. i0 = i * (e + 1) + j;
  33481. i1 = (i + 1) * (e + 1) + j;
  33482. i2 = i * (e + 1) + (j + 1);
  33483. i3 = (i + 1) * (e + 1) + (j + 1);
  33484. indices.push(i0, i1, i2);
  33485. indices.push(i3, i2, i1);
  33486. }
  33487. if (arc !== 1 && enclose) {
  33488. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33489. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33490. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33491. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33492. }
  33493. i = (hasRings) ? (i + 2) : (i + 1);
  33494. }
  33495. // Caps
  33496. var createCylinderCap = function (isTop) {
  33497. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33498. if (radius === 0) {
  33499. return;
  33500. }
  33501. // Cap positions, normals & uvs
  33502. var angle;
  33503. var circleVector;
  33504. var i;
  33505. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33506. var c = null;
  33507. if (faceColors) {
  33508. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33509. }
  33510. // cap center
  33511. var vbase = positions.length / 3;
  33512. var offset = isTop ? height / 2 : -height / 2;
  33513. var center = new BABYLON.Vector3(0, offset, 0);
  33514. positions.push(center.x, center.y, center.z);
  33515. normals.push(0, isTop ? 1 : -1, 0);
  33516. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33517. if (c) {
  33518. colors.push(c.r, c.g, c.b, c.a);
  33519. }
  33520. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33521. for (i = 0; i <= tessellation; i++) {
  33522. angle = Math.PI * 2 * i * arc / tessellation;
  33523. var cos = Math.cos(-angle);
  33524. var sin = Math.sin(-angle);
  33525. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33526. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33527. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33528. normals.push(0, isTop ? 1 : -1, 0);
  33529. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33530. if (c) {
  33531. colors.push(c.r, c.g, c.b, c.a);
  33532. }
  33533. }
  33534. // Cap indices
  33535. for (i = 0; i < tessellation; i++) {
  33536. if (!isTop) {
  33537. indices.push(vbase);
  33538. indices.push(vbase + (i + 1));
  33539. indices.push(vbase + (i + 2));
  33540. }
  33541. else {
  33542. indices.push(vbase);
  33543. indices.push(vbase + (i + 2));
  33544. indices.push(vbase + (i + 1));
  33545. }
  33546. }
  33547. };
  33548. // add caps to geometry
  33549. createCylinderCap(false);
  33550. createCylinderCap(true);
  33551. // Sides
  33552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33553. var vertexData = new VertexData();
  33554. vertexData.indices = indices;
  33555. vertexData.positions = positions;
  33556. vertexData.normals = normals;
  33557. vertexData.uvs = uvs;
  33558. if (faceColors) {
  33559. vertexData.colors = colors;
  33560. }
  33561. return vertexData;
  33562. };
  33563. /**
  33564. * Creates the VertexData of the Torus.
  33565. */
  33566. VertexData.CreateTorus = function (options) {
  33567. var indices = [];
  33568. var positions = [];
  33569. var normals = [];
  33570. var uvs = [];
  33571. var diameter = options.diameter || 1;
  33572. var thickness = options.thickness || 0.5;
  33573. var tessellation = options.tessellation || 16;
  33574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33575. var stride = tessellation + 1;
  33576. for (var i = 0; i <= tessellation; i++) {
  33577. var u = i / tessellation;
  33578. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33579. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33580. for (var j = 0; j <= tessellation; j++) {
  33581. var v = 1 - j / tessellation;
  33582. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33583. var dx = Math.cos(innerAngle);
  33584. var dy = Math.sin(innerAngle);
  33585. // Create a vertex.
  33586. var normal = new BABYLON.Vector3(dx, dy, 0);
  33587. var position = normal.scale(thickness / 2);
  33588. var textureCoordinate = new BABYLON.Vector2(u, v);
  33589. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33590. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33591. positions.push(position.x, position.y, position.z);
  33592. normals.push(normal.x, normal.y, normal.z);
  33593. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33594. // And create indices for two triangles.
  33595. var nextI = (i + 1) % stride;
  33596. var nextJ = (j + 1) % stride;
  33597. indices.push(i * stride + j);
  33598. indices.push(i * stride + nextJ);
  33599. indices.push(nextI * stride + j);
  33600. indices.push(i * stride + nextJ);
  33601. indices.push(nextI * stride + nextJ);
  33602. indices.push(nextI * stride + j);
  33603. }
  33604. }
  33605. // Sides
  33606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33607. // Result
  33608. var vertexData = new VertexData();
  33609. vertexData.indices = indices;
  33610. vertexData.positions = positions;
  33611. vertexData.normals = normals;
  33612. vertexData.uvs = uvs;
  33613. return vertexData;
  33614. };
  33615. /**
  33616. * Creates the VertexData of the LineSystem.
  33617. */
  33618. VertexData.CreateLineSystem = function (options) {
  33619. var indices = [];
  33620. var positions = [];
  33621. var lines = options.lines;
  33622. var colors = options.colors;
  33623. var vertexColors = [];
  33624. var idx = 0;
  33625. for (var l = 0; l < lines.length; l++) {
  33626. var points = lines[l];
  33627. for (var index = 0; index < points.length; index++) {
  33628. positions.push(points[index].x, points[index].y, points[index].z);
  33629. if (colors) {
  33630. var color = colors[l];
  33631. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33632. }
  33633. if (index > 0) {
  33634. indices.push(idx - 1);
  33635. indices.push(idx);
  33636. }
  33637. idx++;
  33638. }
  33639. }
  33640. var vertexData = new VertexData();
  33641. vertexData.indices = indices;
  33642. vertexData.positions = positions;
  33643. if (colors) {
  33644. vertexData.colors = vertexColors;
  33645. }
  33646. return vertexData;
  33647. };
  33648. /**
  33649. * Create the VertexData of the DashedLines.
  33650. */
  33651. VertexData.CreateDashedLines = function (options) {
  33652. var dashSize = options.dashSize || 3;
  33653. var gapSize = options.gapSize || 1;
  33654. var dashNb = options.dashNb || 200;
  33655. var points = options.points;
  33656. var positions = new Array();
  33657. var indices = new Array();
  33658. var curvect = BABYLON.Vector3.Zero();
  33659. var lg = 0;
  33660. var nb = 0;
  33661. var shft = 0;
  33662. var dashshft = 0;
  33663. var curshft = 0;
  33664. var idx = 0;
  33665. var i = 0;
  33666. for (i = 0; i < points.length - 1; i++) {
  33667. points[i + 1].subtractToRef(points[i], curvect);
  33668. lg += curvect.length();
  33669. }
  33670. shft = lg / dashNb;
  33671. dashshft = dashSize * shft / (dashSize + gapSize);
  33672. for (i = 0; i < points.length - 1; i++) {
  33673. points[i + 1].subtractToRef(points[i], curvect);
  33674. nb = Math.floor(curvect.length() / shft);
  33675. curvect.normalize();
  33676. for (var j = 0; j < nb; j++) {
  33677. curshft = shft * j;
  33678. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33679. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33680. indices.push(idx, idx + 1);
  33681. idx += 2;
  33682. }
  33683. }
  33684. // Result
  33685. var vertexData = new VertexData();
  33686. vertexData.positions = positions;
  33687. vertexData.indices = indices;
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Creates the VertexData of the Ground.
  33692. */
  33693. VertexData.CreateGround = function (options) {
  33694. var indices = [];
  33695. var positions = [];
  33696. var normals = [];
  33697. var uvs = [];
  33698. var row, col;
  33699. var width = options.width || 1;
  33700. var height = options.height || 1;
  33701. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33702. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33703. for (row = 0; row <= subdivisionsY; row++) {
  33704. for (col = 0; col <= subdivisionsX; col++) {
  33705. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33706. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33707. positions.push(position.x, position.y, position.z);
  33708. normals.push(normal.x, normal.y, normal.z);
  33709. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33710. }
  33711. }
  33712. for (row = 0; row < subdivisionsY; row++) {
  33713. for (col = 0; col < subdivisionsX; col++) {
  33714. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33715. indices.push(col + 1 + row * (subdivisionsX + 1));
  33716. indices.push(col + row * (subdivisionsX + 1));
  33717. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33718. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33719. indices.push(col + row * (subdivisionsX + 1));
  33720. }
  33721. }
  33722. // Result
  33723. var vertexData = new VertexData();
  33724. vertexData.indices = indices;
  33725. vertexData.positions = positions;
  33726. vertexData.normals = normals;
  33727. vertexData.uvs = uvs;
  33728. return vertexData;
  33729. };
  33730. /**
  33731. * Creates the VertexData of the TiledGround.
  33732. */
  33733. VertexData.CreateTiledGround = function (options) {
  33734. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33735. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33736. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33737. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33738. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33739. var precision = options.precision || { w: 1, h: 1 };
  33740. var indices = new Array();
  33741. var positions = new Array();
  33742. var normals = new Array();
  33743. var uvs = new Array();
  33744. var row, col, tileRow, tileCol;
  33745. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33746. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33747. precision.w = (precision.w < 1) ? 1 : precision.w;
  33748. precision.h = (precision.h < 1) ? 1 : precision.h;
  33749. var tileSize = {
  33750. 'w': (xmax - xmin) / subdivisions.w,
  33751. 'h': (zmax - zmin) / subdivisions.h
  33752. };
  33753. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33754. // Indices
  33755. var base = positions.length / 3;
  33756. var rowLength = precision.w + 1;
  33757. for (row = 0; row < precision.h; row++) {
  33758. for (col = 0; col < precision.w; col++) {
  33759. var square = [
  33760. base + col + row * rowLength,
  33761. base + (col + 1) + row * rowLength,
  33762. base + (col + 1) + (row + 1) * rowLength,
  33763. base + col + (row + 1) * rowLength
  33764. ];
  33765. indices.push(square[1]);
  33766. indices.push(square[2]);
  33767. indices.push(square[3]);
  33768. indices.push(square[0]);
  33769. indices.push(square[1]);
  33770. indices.push(square[3]);
  33771. }
  33772. }
  33773. // Position, normals and uvs
  33774. var position = BABYLON.Vector3.Zero();
  33775. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33776. for (row = 0; row <= precision.h; row++) {
  33777. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33778. for (col = 0; col <= precision.w; col++) {
  33779. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33780. position.y = 0;
  33781. positions.push(position.x, position.y, position.z);
  33782. normals.push(normal.x, normal.y, normal.z);
  33783. uvs.push(col / precision.w, row / precision.h);
  33784. }
  33785. }
  33786. }
  33787. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33788. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33789. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33790. }
  33791. }
  33792. // Result
  33793. var vertexData = new VertexData();
  33794. vertexData.indices = indices;
  33795. vertexData.positions = positions;
  33796. vertexData.normals = normals;
  33797. vertexData.uvs = uvs;
  33798. return vertexData;
  33799. };
  33800. /**
  33801. * Creates the VertexData of the Ground designed from a heightmap.
  33802. */
  33803. VertexData.CreateGroundFromHeightMap = function (options) {
  33804. var indices = [];
  33805. var positions = [];
  33806. var normals = [];
  33807. var uvs = [];
  33808. var row, col;
  33809. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33810. // Vertices
  33811. for (row = 0; row <= options.subdivisions; row++) {
  33812. for (col = 0; col <= options.subdivisions; col++) {
  33813. 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));
  33814. // Compute height
  33815. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33816. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33817. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33818. var r = options.buffer[pos] / 255.0;
  33819. var g = options.buffer[pos + 1] / 255.0;
  33820. var b = options.buffer[pos + 2] / 255.0;
  33821. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33822. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33823. // Add vertex
  33824. positions.push(position.x, position.y, position.z);
  33825. normals.push(0, 0, 0);
  33826. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33827. }
  33828. }
  33829. // Indices
  33830. for (row = 0; row < options.subdivisions; row++) {
  33831. for (col = 0; col < options.subdivisions; col++) {
  33832. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33833. indices.push(col + 1 + row * (options.subdivisions + 1));
  33834. indices.push(col + row * (options.subdivisions + 1));
  33835. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33836. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33837. indices.push(col + row * (options.subdivisions + 1));
  33838. }
  33839. }
  33840. // Normals
  33841. VertexData.ComputeNormals(positions, indices, normals);
  33842. // Result
  33843. var vertexData = new VertexData();
  33844. vertexData.indices = indices;
  33845. vertexData.positions = positions;
  33846. vertexData.normals = normals;
  33847. vertexData.uvs = uvs;
  33848. return vertexData;
  33849. };
  33850. /**
  33851. * Creates the VertexData of the Plane.
  33852. */
  33853. VertexData.CreatePlane = function (options) {
  33854. var indices = [];
  33855. var positions = [];
  33856. var normals = [];
  33857. var uvs = [];
  33858. var width = options.width || options.size || 1;
  33859. var height = options.height || options.size || 1;
  33860. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33861. // Vertices
  33862. var halfWidth = width / 2.0;
  33863. var halfHeight = height / 2.0;
  33864. positions.push(-halfWidth, -halfHeight, 0);
  33865. normals.push(0, 0, -1.0);
  33866. uvs.push(0.0, 0.0);
  33867. positions.push(halfWidth, -halfHeight, 0);
  33868. normals.push(0, 0, -1.0);
  33869. uvs.push(1.0, 0.0);
  33870. positions.push(halfWidth, halfHeight, 0);
  33871. normals.push(0, 0, -1.0);
  33872. uvs.push(1.0, 1.0);
  33873. positions.push(-halfWidth, halfHeight, 0);
  33874. normals.push(0, 0, -1.0);
  33875. uvs.push(0.0, 1.0);
  33876. // Indices
  33877. indices.push(0);
  33878. indices.push(1);
  33879. indices.push(2);
  33880. indices.push(0);
  33881. indices.push(2);
  33882. indices.push(3);
  33883. // Sides
  33884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33885. // Result
  33886. var vertexData = new VertexData();
  33887. vertexData.indices = indices;
  33888. vertexData.positions = positions;
  33889. vertexData.normals = normals;
  33890. vertexData.uvs = uvs;
  33891. return vertexData;
  33892. };
  33893. /**
  33894. * Creates the VertexData of the Disc or regular Polygon.
  33895. */
  33896. VertexData.CreateDisc = function (options) {
  33897. var positions = new Array();
  33898. var indices = new Array();
  33899. var normals = new Array();
  33900. var uvs = new Array();
  33901. var radius = options.radius || 0.5;
  33902. var tessellation = options.tessellation || 64;
  33903. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33904. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33905. // positions and uvs
  33906. positions.push(0, 0, 0); // disc center first
  33907. uvs.push(0.5, 0.5);
  33908. var theta = Math.PI * 2 * arc;
  33909. var step = theta / tessellation;
  33910. for (var a = 0; a < theta; a += step) {
  33911. var x = Math.cos(a);
  33912. var y = Math.sin(a);
  33913. var u = (x + 1) / 2;
  33914. var v = (1 - y) / 2;
  33915. positions.push(radius * x, radius * y, 0);
  33916. uvs.push(u, v);
  33917. }
  33918. if (arc === 1) {
  33919. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33920. uvs.push(uvs[2], uvs[3]);
  33921. }
  33922. //indices
  33923. var vertexNb = positions.length / 3;
  33924. for (var i = 1; i < vertexNb - 1; i++) {
  33925. indices.push(i + 1, 0, i);
  33926. }
  33927. // result
  33928. VertexData.ComputeNormals(positions, indices, normals);
  33929. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33930. var vertexData = new VertexData();
  33931. vertexData.indices = indices;
  33932. vertexData.positions = positions;
  33933. vertexData.normals = normals;
  33934. vertexData.uvs = uvs;
  33935. return vertexData;
  33936. };
  33937. /**
  33938. * Re-creates the VertexData of the Polygon for sideOrientation.
  33939. */
  33940. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33941. var faceUV = fUV || new Array(3);
  33942. var faceColors = fColors;
  33943. var colors = [];
  33944. // default face colors and UV if undefined
  33945. for (var f = 0; f < 3; f++) {
  33946. if (faceUV[f] === undefined) {
  33947. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33948. }
  33949. if (faceColors && faceColors[f] === undefined) {
  33950. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33951. }
  33952. }
  33953. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33954. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33955. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33956. var indices = polygon.getIndices();
  33957. // set face colours and textures
  33958. var idx = 0;
  33959. var face = 0;
  33960. for (var index = 0; index < normals.length; index += 3) {
  33961. //Edge Face no. 1
  33962. if (Math.abs(normals[index + 1]) < 0.001) {
  33963. face = 1;
  33964. }
  33965. //Top Face no. 0
  33966. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33967. face = 0;
  33968. }
  33969. //Bottom Face no. 2
  33970. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33971. face = 2;
  33972. }
  33973. idx = index / 3;
  33974. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33975. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33976. if (faceColors) {
  33977. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33978. }
  33979. }
  33980. // sides
  33981. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33982. // Result
  33983. var vertexData = new VertexData();
  33984. vertexData.indices = indices;
  33985. vertexData.positions = positions;
  33986. vertexData.normals = normals;
  33987. vertexData.uvs = uvs;
  33988. if (faceColors) {
  33989. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33990. vertexData.colors = totalColors;
  33991. }
  33992. return vertexData;
  33993. };
  33994. /**
  33995. * Creates the VertexData of the IcoSphere.
  33996. */
  33997. VertexData.CreateIcoSphere = function (options) {
  33998. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33999. var radius = options.radius || 1;
  34000. var flat = (options.flat === undefined) ? true : options.flat;
  34001. var subdivisions = options.subdivisions || 4;
  34002. var radiusX = options.radiusX || radius;
  34003. var radiusY = options.radiusY || radius;
  34004. var radiusZ = options.radiusZ || radius;
  34005. var t = (1 + Math.sqrt(5)) / 2;
  34006. // 12 vertex x,y,z
  34007. var ico_vertices = [
  34008. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34009. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34010. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34011. ];
  34012. // index of 3 vertex makes a face of icopshere
  34013. var ico_indices = [
  34014. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34015. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34016. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34017. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34018. ];
  34019. // vertex for uv have aliased position, not for UV
  34020. var vertices_unalias_id = [
  34021. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34022. // vertex alias
  34023. 0,
  34024. 2,
  34025. 3,
  34026. 3,
  34027. 3,
  34028. 4,
  34029. 7,
  34030. 8,
  34031. 9,
  34032. 9,
  34033. 10,
  34034. 11 // 23: B + 12
  34035. ];
  34036. // uv as integer step (not pixels !)
  34037. var ico_vertexuv = [
  34038. 5, 1, 3, 1, 6, 4, 0, 0,
  34039. 5, 3, 4, 2, 2, 2, 4, 0,
  34040. 2, 0, 1, 1, 6, 0, 6, 2,
  34041. // vertex alias (for same vertex on different faces)
  34042. 0, 4,
  34043. 3, 3,
  34044. 4, 4,
  34045. 3, 1,
  34046. 4, 2,
  34047. 4, 4,
  34048. 0, 2,
  34049. 1, 1,
  34050. 2, 2,
  34051. 3, 3,
  34052. 1, 3,
  34053. 2, 4 // 23: B + 12
  34054. ];
  34055. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34056. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34057. // First island of uv mapping
  34058. // v = 4h 3+ 2
  34059. // v = 3h 9+ 4
  34060. // v = 2h 9+ 5 B
  34061. // v = 1h 9 1 0
  34062. // v = 0h 3 8 7 A
  34063. // u = 0 1 2 3 4 5 6 *a
  34064. // Second island of uv mapping
  34065. // v = 4h 0+ B+ 4+
  34066. // v = 3h A+ 2+
  34067. // v = 2h 7+ 6 3+
  34068. // v = 1h 8+ 3+
  34069. // v = 0h
  34070. // u = 0 1 2 3 4 5 6 *a
  34071. // Face layout on texture UV mapping
  34072. // ============
  34073. // \ 4 /\ 16 / ======
  34074. // \ / \ / /\ 11 /
  34075. // \/ 7 \/ / \ /
  34076. // ======= / 10 \/
  34077. // /\ 17 /\ =======
  34078. // / \ / \ \ 15 /\
  34079. // / 8 \/ 12 \ \ / \
  34080. // ============ \/ 6 \
  34081. // \ 18 /\ ============
  34082. // \ / \ \ 5 /\ 0 /
  34083. // \/ 13 \ \ / \ /
  34084. // ======= \/ 1 \/
  34085. // =============
  34086. // /\ 19 /\ 2 /\
  34087. // / \ / \ / \
  34088. // / 14 \/ 9 \/ 3 \
  34089. // ===================
  34090. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34091. var ustep = 138 / 1024;
  34092. var vstep = 239 / 1024;
  34093. var uoffset = 60 / 1024;
  34094. var voffset = 26 / 1024;
  34095. // Second island should have margin, not to touch the first island
  34096. // avoid any borderline artefact in pixel rounding
  34097. var island_u_offset = -40 / 1024;
  34098. var island_v_offset = +20 / 1024;
  34099. // face is either island 0 or 1 :
  34100. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34101. var island = [
  34102. 0, 0, 0, 0, 1,
  34103. 0, 0, 1, 1, 0,
  34104. 0, 0, 1, 1, 0,
  34105. 0, 1, 1, 1, 0 // 15 - 19
  34106. ];
  34107. var indices = new Array();
  34108. var positions = new Array();
  34109. var normals = new Array();
  34110. var uvs = new Array();
  34111. var current_indice = 0;
  34112. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34113. var face_vertex_pos = new Array(3);
  34114. var face_vertex_uv = new Array(3);
  34115. var v012;
  34116. for (v012 = 0; v012 < 3; v012++) {
  34117. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34118. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34119. }
  34120. // create all with normals
  34121. for (var face = 0; face < 20; face++) {
  34122. // 3 vertex per face
  34123. for (v012 = 0; v012 < 3; v012++) {
  34124. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34125. var v_id = ico_indices[3 * face + v012];
  34126. // vertex have 3D position (x,y,z)
  34127. 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]);
  34128. // Normalize to get normal, then scale to radius
  34129. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34130. // uv Coordinates from vertex ID
  34131. 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);
  34132. }
  34133. // Subdivide the face (interpolate pos, norm, uv)
  34134. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34135. // - norm is linear interpolation of vertex corner normal
  34136. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34137. // - uv is linear interpolation
  34138. //
  34139. // Topology is as below for sub-divide by 2
  34140. // vertex shown as v0,v1,v2
  34141. // interp index is i1 to progress in range [v0,v1[
  34142. // interp index is i2 to progress in range [v0,v2[
  34143. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34144. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34145. //
  34146. //
  34147. // i2 v2
  34148. // ^ ^
  34149. // / / \
  34150. // / / \
  34151. // / / \
  34152. // / / (0,1) \
  34153. // / #---------\
  34154. // / / \ (0,0)'/ \
  34155. // / / \ / \
  34156. // / / \ / \
  34157. // / / (0,0) \ / (1,0) \
  34158. // / #---------#---------\
  34159. // v0 v1
  34160. //
  34161. // --------------------> i1
  34162. //
  34163. // interp of (i1,i2):
  34164. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34165. // along i1 : lerp(x0,x1, i1/(S-i2))
  34166. //
  34167. // centroid of triangle is needed to get help normal computation
  34168. // (c1,c2) are used for centroid location
  34169. var interp_vertex = function (i1, i2, c1, c2) {
  34170. // vertex is interpolated from
  34171. // - face_vertex_pos[0..2]
  34172. // - face_vertex_uv[0..2]
  34173. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34174. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34175. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34176. pos_interp.normalize();
  34177. var vertex_normal;
  34178. if (flat) {
  34179. // in flat mode, recalculate normal as face centroid normal
  34180. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34181. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34182. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34183. }
  34184. else {
  34185. // in smooth mode, recalculate normal from each single vertex position
  34186. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34187. }
  34188. // Vertex normal need correction due to X,Y,Z radius scaling
  34189. vertex_normal.x /= radiusX;
  34190. vertex_normal.y /= radiusY;
  34191. vertex_normal.z /= radiusZ;
  34192. vertex_normal.normalize();
  34193. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34194. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34195. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34196. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34197. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34198. uvs.push(uv_interp.x, uv_interp.y);
  34199. // push each vertex has member of a face
  34200. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34201. indices.push(current_indice);
  34202. current_indice++;
  34203. };
  34204. for (var i2 = 0; i2 < subdivisions; i2++) {
  34205. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34206. // face : (i1,i2) for /\ :
  34207. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34208. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34209. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34210. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34211. if (i1 + i2 + 1 < subdivisions) {
  34212. // face : (i1,i2)' for \/ :
  34213. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34214. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34215. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34216. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34217. }
  34218. }
  34219. }
  34220. }
  34221. // Sides
  34222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34223. // Result
  34224. var vertexData = new VertexData();
  34225. vertexData.indices = indices;
  34226. vertexData.positions = positions;
  34227. vertexData.normals = normals;
  34228. vertexData.uvs = uvs;
  34229. return vertexData;
  34230. };
  34231. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34232. /**
  34233. * Creates the VertexData of the Polyhedron.
  34234. */
  34235. VertexData.CreatePolyhedron = function (options) {
  34236. // provided polyhedron types :
  34237. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34238. // 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)
  34239. var polyhedra = [];
  34240. 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]] };
  34241. 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]] };
  34242. polyhedra[2] = {
  34243. 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]],
  34244. 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]]
  34245. };
  34246. polyhedra[3] = {
  34247. 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]],
  34248. 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]]
  34249. };
  34250. polyhedra[4] = {
  34251. 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]],
  34252. 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]]
  34253. };
  34254. 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]] };
  34255. 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]] };
  34256. 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]] };
  34257. 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]] };
  34258. 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]] };
  34259. 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]] };
  34260. 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]] };
  34261. 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]] };
  34262. 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]] };
  34263. polyhedra[14] = {
  34264. 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]],
  34265. 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]]
  34266. };
  34267. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34268. var size = options.size;
  34269. var sizeX = options.sizeX || size || 1;
  34270. var sizeY = options.sizeY || size || 1;
  34271. var sizeZ = options.sizeZ || size || 1;
  34272. var data = options.custom || polyhedra[type];
  34273. var nbfaces = data.face.length;
  34274. var faceUV = options.faceUV || new Array(nbfaces);
  34275. var faceColors = options.faceColors;
  34276. var flat = (options.flat === undefined) ? true : options.flat;
  34277. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34278. var positions = new Array();
  34279. var indices = new Array();
  34280. var normals = new Array();
  34281. var uvs = new Array();
  34282. var colors = new Array();
  34283. var index = 0;
  34284. var faceIdx = 0; // face cursor in the array "indexes"
  34285. var indexes = new Array();
  34286. var i = 0;
  34287. var f = 0;
  34288. var u, v, ang, x, y, tmp;
  34289. // default face colors and UV if undefined
  34290. if (flat) {
  34291. for (f = 0; f < nbfaces; f++) {
  34292. if (faceColors && faceColors[f] === undefined) {
  34293. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34294. }
  34295. if (faceUV && faceUV[f] === undefined) {
  34296. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34297. }
  34298. }
  34299. }
  34300. if (!flat) {
  34301. for (i = 0; i < data.vertex.length; i++) {
  34302. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34303. uvs.push(0, 0);
  34304. }
  34305. for (f = 0; f < nbfaces; f++) {
  34306. for (i = 0; i < data.face[f].length - 2; i++) {
  34307. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34308. }
  34309. }
  34310. }
  34311. else {
  34312. for (f = 0; f < nbfaces; f++) {
  34313. var fl = data.face[f].length; // number of vertices of the current face
  34314. ang = 2 * Math.PI / fl;
  34315. x = 0.5 * Math.tan(ang / 2);
  34316. y = 0.5;
  34317. // positions, uvs, colors
  34318. for (i = 0; i < fl; i++) {
  34319. // positions
  34320. 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);
  34321. indexes.push(index);
  34322. index++;
  34323. // uvs
  34324. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34325. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34326. uvs.push(u, v);
  34327. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34328. y = x * Math.sin(ang) + y * Math.cos(ang);
  34329. x = tmp;
  34330. // colors
  34331. if (faceColors) {
  34332. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34333. }
  34334. }
  34335. // indices from indexes
  34336. for (i = 0; i < fl - 2; i++) {
  34337. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34338. }
  34339. faceIdx += fl;
  34340. }
  34341. }
  34342. VertexData.ComputeNormals(positions, indices, normals);
  34343. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34344. var vertexData = new VertexData();
  34345. vertexData.positions = positions;
  34346. vertexData.indices = indices;
  34347. vertexData.normals = normals;
  34348. vertexData.uvs = uvs;
  34349. if (faceColors && flat) {
  34350. vertexData.colors = colors;
  34351. }
  34352. return vertexData;
  34353. };
  34354. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34355. /**
  34356. * Creates the VertexData of the Torus Knot.
  34357. */
  34358. VertexData.CreateTorusKnot = function (options) {
  34359. var indices = new Array();
  34360. var positions = new Array();
  34361. var normals = new Array();
  34362. var uvs = new Array();
  34363. var radius = options.radius || 2;
  34364. var tube = options.tube || 0.5;
  34365. var radialSegments = options.radialSegments || 32;
  34366. var tubularSegments = options.tubularSegments || 32;
  34367. var p = options.p || 2;
  34368. var q = options.q || 3;
  34369. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34370. // Helper
  34371. var getPos = function (angle) {
  34372. var cu = Math.cos(angle);
  34373. var su = Math.sin(angle);
  34374. var quOverP = q / p * angle;
  34375. var cs = Math.cos(quOverP);
  34376. var tx = radius * (2 + cs) * 0.5 * cu;
  34377. var ty = radius * (2 + cs) * su * 0.5;
  34378. var tz = radius * Math.sin(quOverP) * 0.5;
  34379. return new BABYLON.Vector3(tx, ty, tz);
  34380. };
  34381. // Vertices
  34382. var i;
  34383. var j;
  34384. for (i = 0; i <= radialSegments; i++) {
  34385. var modI = i % radialSegments;
  34386. var u = modI / radialSegments * 2 * p * Math.PI;
  34387. var p1 = getPos(u);
  34388. var p2 = getPos(u + 0.01);
  34389. var tang = p2.subtract(p1);
  34390. var n = p2.add(p1);
  34391. var bitan = BABYLON.Vector3.Cross(tang, n);
  34392. n = BABYLON.Vector3.Cross(bitan, tang);
  34393. bitan.normalize();
  34394. n.normalize();
  34395. for (j = 0; j < tubularSegments; j++) {
  34396. var modJ = j % tubularSegments;
  34397. var v = modJ / tubularSegments * 2 * Math.PI;
  34398. var cx = -tube * Math.cos(v);
  34399. var cy = tube * Math.sin(v);
  34400. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34401. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34402. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34403. uvs.push(i / radialSegments);
  34404. uvs.push(j / tubularSegments);
  34405. }
  34406. }
  34407. for (i = 0; i < radialSegments; i++) {
  34408. for (j = 0; j < tubularSegments; j++) {
  34409. var jNext = (j + 1) % tubularSegments;
  34410. var a = i * tubularSegments + j;
  34411. var b = (i + 1) * tubularSegments + j;
  34412. var c = (i + 1) * tubularSegments + jNext;
  34413. var d = i * tubularSegments + jNext;
  34414. indices.push(d);
  34415. indices.push(b);
  34416. indices.push(a);
  34417. indices.push(d);
  34418. indices.push(c);
  34419. indices.push(b);
  34420. }
  34421. }
  34422. // Normals
  34423. VertexData.ComputeNormals(positions, indices, normals);
  34424. // Sides
  34425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34426. // Result
  34427. var vertexData = new VertexData();
  34428. vertexData.indices = indices;
  34429. vertexData.positions = positions;
  34430. vertexData.normals = normals;
  34431. vertexData.uvs = uvs;
  34432. return vertexData;
  34433. };
  34434. // Tools
  34435. /**
  34436. * @param {any} - positions (number[] or Float32Array)
  34437. * @param {any} - indices (number[] or Uint16Array)
  34438. * @param {any} - normals (number[] or Float32Array)
  34439. * options (optional) :
  34440. * facetPositions : optional array of facet positions (vector3)
  34441. * facetNormals : optional array of facet normals (vector3)
  34442. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34443. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34444. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34445. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34446. * bInfo : optional bounding info, required for facetPartitioning computation
  34447. * useRightHandedSystem: optional boolean to for right handed system computation
  34448. * depthSort : optional boolean to enable the facet depth sort computation
  34449. * distanceTo : optional Vector3 to compute the facet depth from this location
  34450. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34451. */
  34452. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34453. // temporary scalar variables
  34454. var index = 0; // facet index
  34455. var p1p2x = 0.0; // p1p2 vector x coordinate
  34456. var p1p2y = 0.0; // p1p2 vector y coordinate
  34457. var p1p2z = 0.0; // p1p2 vector z coordinate
  34458. var p3p2x = 0.0; // p3p2 vector x coordinate
  34459. var p3p2y = 0.0; // p3p2 vector y coordinate
  34460. var p3p2z = 0.0; // p3p2 vector z coordinate
  34461. var faceNormalx = 0.0; // facet normal x coordinate
  34462. var faceNormaly = 0.0; // facet normal y coordinate
  34463. var faceNormalz = 0.0; // facet normal z coordinate
  34464. var length = 0.0; // facet normal length before normalization
  34465. var v1x = 0; // vector1 x index in the positions array
  34466. var v1y = 0; // vector1 y index in the positions array
  34467. var v1z = 0; // vector1 z index in the positions array
  34468. var v2x = 0; // vector2 x index in the positions array
  34469. var v2y = 0; // vector2 y index in the positions array
  34470. var v2z = 0; // vector2 z index in the positions array
  34471. var v3x = 0; // vector3 x index in the positions array
  34472. var v3y = 0; // vector3 y index in the positions array
  34473. var v3z = 0; // vector3 z index in the positions array
  34474. var computeFacetNormals = false;
  34475. var computeFacetPositions = false;
  34476. var computeFacetPartitioning = false;
  34477. var computeDepthSort = false;
  34478. var faceNormalSign = 1;
  34479. var ratio = 0;
  34480. var distanceTo = null;
  34481. if (options) {
  34482. computeFacetNormals = (options.facetNormals) ? true : false;
  34483. computeFacetPositions = (options.facetPositions) ? true : false;
  34484. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34485. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34486. ratio = options.ratio || 0;
  34487. computeDepthSort = (options.depthSort) ? true : false;
  34488. distanceTo = (options.distanceTo);
  34489. if (computeDepthSort) {
  34490. if (distanceTo === undefined) {
  34491. distanceTo = BABYLON.Vector3.Zero();
  34492. }
  34493. var depthSortedFacets = options.depthSortedFacets;
  34494. }
  34495. }
  34496. // facetPartitioning reinit if needed
  34497. var xSubRatio = 0;
  34498. var ySubRatio = 0;
  34499. var zSubRatio = 0;
  34500. var subSq = 0;
  34501. if (computeFacetPartitioning && options && options.bbSize) {
  34502. var ox = 0; // X partitioning index for facet position
  34503. var oy = 0; // Y partinioning index for facet position
  34504. var oz = 0; // Z partinioning index for facet position
  34505. var b1x = 0; // X partitioning index for facet v1 vertex
  34506. var b1y = 0; // Y partitioning index for facet v1 vertex
  34507. var b1z = 0; // z partitioning index for facet v1 vertex
  34508. var b2x = 0; // X partitioning index for facet v2 vertex
  34509. var b2y = 0; // Y partitioning index for facet v2 vertex
  34510. var b2z = 0; // Z partitioning index for facet v2 vertex
  34511. var b3x = 0; // X partitioning index for facet v3 vertex
  34512. var b3y = 0; // Y partitioning index for facet v3 vertex
  34513. var b3z = 0; // Z partitioning index for facet v3 vertex
  34514. var block_idx_o = 0; // facet barycenter block index
  34515. var block_idx_v1 = 0; // v1 vertex block index
  34516. var block_idx_v2 = 0; // v2 vertex block index
  34517. var block_idx_v3 = 0; // v3 vertex block index
  34518. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34519. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34520. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34521. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34522. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34523. subSq = options.subDiv.max * options.subDiv.max;
  34524. options.facetPartitioning.length = 0;
  34525. }
  34526. // reset the normals
  34527. for (index = 0; index < positions.length; index++) {
  34528. normals[index] = 0.0;
  34529. }
  34530. // Loop : 1 indice triplet = 1 facet
  34531. var nbFaces = (indices.length / 3) | 0;
  34532. for (index = 0; index < nbFaces; index++) {
  34533. // get the indexes of the coordinates of each vertex of the facet
  34534. v1x = indices[index * 3] * 3;
  34535. v1y = v1x + 1;
  34536. v1z = v1x + 2;
  34537. v2x = indices[index * 3 + 1] * 3;
  34538. v2y = v2x + 1;
  34539. v2z = v2x + 2;
  34540. v3x = indices[index * 3 + 2] * 3;
  34541. v3y = v3x + 1;
  34542. v3z = v3x + 2;
  34543. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34544. p1p2y = positions[v1y] - positions[v2y];
  34545. p1p2z = positions[v1z] - positions[v2z];
  34546. p3p2x = positions[v3x] - positions[v2x];
  34547. p3p2y = positions[v3y] - positions[v2y];
  34548. p3p2z = positions[v3z] - positions[v2z];
  34549. // compute the face normal with the cross product
  34550. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34551. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34552. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34553. // normalize this normal and store it in the array facetData
  34554. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34555. length = (length === 0) ? 1.0 : length;
  34556. faceNormalx /= length;
  34557. faceNormaly /= length;
  34558. faceNormalz /= length;
  34559. if (computeFacetNormals && options) {
  34560. options.facetNormals[index].x = faceNormalx;
  34561. options.facetNormals[index].y = faceNormaly;
  34562. options.facetNormals[index].z = faceNormalz;
  34563. }
  34564. if (computeFacetPositions && options) {
  34565. // compute and the facet barycenter coordinates in the array facetPositions
  34566. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34567. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34568. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34569. }
  34570. if (computeFacetPartitioning && options) {
  34571. // store the facet indexes in arrays in the main facetPartitioning array :
  34572. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34573. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34574. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34575. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34576. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34577. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34578. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34579. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34580. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34581. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34582. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34583. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34584. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34585. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34586. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34587. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34588. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34589. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34590. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34591. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34592. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34593. // push each facet index in each block containing the vertex
  34594. options.facetPartitioning[block_idx_v1].push(index);
  34595. if (block_idx_v2 != block_idx_v1) {
  34596. options.facetPartitioning[block_idx_v2].push(index);
  34597. }
  34598. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34599. options.facetPartitioning[block_idx_v3].push(index);
  34600. }
  34601. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34602. options.facetPartitioning[block_idx_o].push(index);
  34603. }
  34604. }
  34605. if (computeDepthSort && options && options.facetPositions) {
  34606. var dsf = depthSortedFacets[index];
  34607. dsf.ind = index * 3;
  34608. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34609. }
  34610. // compute the normals anyway
  34611. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34612. normals[v1y] += faceNormaly;
  34613. normals[v1z] += faceNormalz;
  34614. normals[v2x] += faceNormalx;
  34615. normals[v2y] += faceNormaly;
  34616. normals[v2z] += faceNormalz;
  34617. normals[v3x] += faceNormalx;
  34618. normals[v3y] += faceNormaly;
  34619. normals[v3z] += faceNormalz;
  34620. }
  34621. // last normalization of each normal
  34622. for (index = 0; index < normals.length / 3; index++) {
  34623. faceNormalx = normals[index * 3];
  34624. faceNormaly = normals[index * 3 + 1];
  34625. faceNormalz = normals[index * 3 + 2];
  34626. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34627. length = (length === 0) ? 1.0 : length;
  34628. faceNormalx /= length;
  34629. faceNormaly /= length;
  34630. faceNormalz /= length;
  34631. normals[index * 3] = faceNormalx;
  34632. normals[index * 3 + 1] = faceNormaly;
  34633. normals[index * 3 + 2] = faceNormalz;
  34634. }
  34635. };
  34636. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34637. var li = indices.length;
  34638. var ln = normals.length;
  34639. var i;
  34640. var n;
  34641. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34642. switch (sideOrientation) {
  34643. case BABYLON.Mesh.FRONTSIDE:
  34644. // nothing changed
  34645. break;
  34646. case BABYLON.Mesh.BACKSIDE:
  34647. var tmp;
  34648. // indices
  34649. for (i = 0; i < li; i += 3) {
  34650. tmp = indices[i];
  34651. indices[i] = indices[i + 2];
  34652. indices[i + 2] = tmp;
  34653. }
  34654. // normals
  34655. for (n = 0; n < ln; n++) {
  34656. normals[n] = -normals[n];
  34657. }
  34658. break;
  34659. case BABYLON.Mesh.DOUBLESIDE:
  34660. // positions
  34661. var lp = positions.length;
  34662. var l = lp / 3;
  34663. for (var p = 0; p < lp; p++) {
  34664. positions[lp + p] = positions[p];
  34665. }
  34666. // indices
  34667. for (i = 0; i < li; i += 3) {
  34668. indices[i + li] = indices[i + 2] + l;
  34669. indices[i + 1 + li] = indices[i + 1] + l;
  34670. indices[i + 2 + li] = indices[i] + l;
  34671. }
  34672. // normals
  34673. for (n = 0; n < ln; n++) {
  34674. normals[ln + n] = -normals[n];
  34675. }
  34676. // uvs
  34677. var lu = uvs.length;
  34678. var u = 0;
  34679. for (u = 0; u < lu; u++) {
  34680. uvs[u + lu] = uvs[u];
  34681. }
  34682. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34683. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34684. u = 0;
  34685. for (i = 0; i < lu / 2; i++) {
  34686. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34687. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34688. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34689. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34690. u += 2;
  34691. }
  34692. break;
  34693. }
  34694. };
  34695. /**
  34696. * Creates a new VertexData from the imported parameters.
  34697. */
  34698. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34699. var vertexData = new VertexData();
  34700. // positions
  34701. var positions = parsedVertexData.positions;
  34702. if (positions) {
  34703. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34704. }
  34705. // normals
  34706. var normals = parsedVertexData.normals;
  34707. if (normals) {
  34708. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34709. }
  34710. // tangents
  34711. var tangents = parsedVertexData.tangents;
  34712. if (tangents) {
  34713. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34714. }
  34715. // uvs
  34716. var uvs = parsedVertexData.uvs;
  34717. if (uvs) {
  34718. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34719. }
  34720. // uv2s
  34721. var uv2s = parsedVertexData.uv2s;
  34722. if (uv2s) {
  34723. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34724. }
  34725. // uv3s
  34726. var uv3s = parsedVertexData.uv3s;
  34727. if (uv3s) {
  34728. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34729. }
  34730. // uv4s
  34731. var uv4s = parsedVertexData.uv4s;
  34732. if (uv4s) {
  34733. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34734. }
  34735. // uv5s
  34736. var uv5s = parsedVertexData.uv5s;
  34737. if (uv5s) {
  34738. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34739. }
  34740. // uv6s
  34741. var uv6s = parsedVertexData.uv6s;
  34742. if (uv6s) {
  34743. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34744. }
  34745. // colors
  34746. var colors = parsedVertexData.colors;
  34747. if (colors) {
  34748. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34749. }
  34750. // matricesIndices
  34751. var matricesIndices = parsedVertexData.matricesIndices;
  34752. if (matricesIndices) {
  34753. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34754. }
  34755. // matricesWeights
  34756. var matricesWeights = parsedVertexData.matricesWeights;
  34757. if (matricesWeights) {
  34758. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34759. }
  34760. // indices
  34761. var indices = parsedVertexData.indices;
  34762. if (indices) {
  34763. vertexData.indices = indices;
  34764. }
  34765. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34766. };
  34767. return VertexData;
  34768. }());
  34769. BABYLON.VertexData = VertexData;
  34770. })(BABYLON || (BABYLON = {}));
  34771. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34772. var BABYLON;
  34773. (function (BABYLON) {
  34774. /**
  34775. * Class used to store geometry data (vertex buffers + index buffer)
  34776. */
  34777. var Geometry = /** @class */ (function () {
  34778. /**
  34779. * Creates a new geometry
  34780. * @param id defines the unique ID
  34781. * @param scene defines the hosting scene
  34782. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34783. * @param updatable defines if geometry must be updatable (false by default)
  34784. * @param mesh defines the mesh that will be associated with the geometry
  34785. */
  34786. function Geometry(id, scene, vertexData, updatable, mesh) {
  34787. if (updatable === void 0) { updatable = false; }
  34788. if (mesh === void 0) { mesh = null; }
  34789. /**
  34790. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34791. */
  34792. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34793. this._totalVertices = 0;
  34794. this._isDisposed = false;
  34795. this._indexBufferIsUpdatable = false;
  34796. this.id = id;
  34797. this._engine = scene.getEngine();
  34798. this._meshes = [];
  34799. this._scene = scene;
  34800. //Init vertex buffer cache
  34801. this._vertexBuffers = {};
  34802. this._indices = [];
  34803. this._updatable = updatable;
  34804. // vertexData
  34805. if (vertexData) {
  34806. this.setAllVerticesData(vertexData, updatable);
  34807. }
  34808. else {
  34809. this._totalVertices = 0;
  34810. this._indices = [];
  34811. }
  34812. if (this._engine.getCaps().vertexArrayObject) {
  34813. this._vertexArrayObjects = {};
  34814. }
  34815. // applyToMesh
  34816. if (mesh) {
  34817. if (mesh.getClassName() === "LinesMesh") {
  34818. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34819. this.updateExtend();
  34820. }
  34821. this.applyToMesh(mesh);
  34822. mesh.computeWorldMatrix(true);
  34823. }
  34824. }
  34825. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34826. /**
  34827. * 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
  34828. */
  34829. get: function () {
  34830. return this._boundingBias;
  34831. },
  34832. /**
  34833. * 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
  34834. */
  34835. set: function (value) {
  34836. if (this._boundingBias && this._boundingBias.equals(value)) {
  34837. return;
  34838. }
  34839. this._boundingBias = value.clone();
  34840. this.updateBoundingInfo(true, null);
  34841. },
  34842. enumerable: true,
  34843. configurable: true
  34844. });
  34845. /**
  34846. * Static function used to attach a new empty geometry to a mesh
  34847. * @param mesh defines the mesh to attach the geometry to
  34848. * @returns the new {BABYLON.Geometry}
  34849. */
  34850. Geometry.CreateGeometryForMesh = function (mesh) {
  34851. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34852. geometry.applyToMesh(mesh);
  34853. return geometry;
  34854. };
  34855. Object.defineProperty(Geometry.prototype, "extend", {
  34856. /**
  34857. * Gets the current extend of the geometry
  34858. */
  34859. get: function () {
  34860. return this._extend;
  34861. },
  34862. enumerable: true,
  34863. configurable: true
  34864. });
  34865. /**
  34866. * Gets the hosting scene
  34867. * @returns the hosting {BABYLON.Scene}
  34868. */
  34869. Geometry.prototype.getScene = function () {
  34870. return this._scene;
  34871. };
  34872. /**
  34873. * Gets the hosting engine
  34874. * @returns the hosting {BABYLON.Engine}
  34875. */
  34876. Geometry.prototype.getEngine = function () {
  34877. return this._engine;
  34878. };
  34879. /**
  34880. * Defines if the geometry is ready to use
  34881. * @returns true if the geometry is ready to be used
  34882. */
  34883. Geometry.prototype.isReady = function () {
  34884. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34885. };
  34886. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34887. /**
  34888. * Gets a value indicating that the geometry should not be serialized
  34889. */
  34890. get: function () {
  34891. for (var index = 0; index < this._meshes.length; index++) {
  34892. if (!this._meshes[index].doNotSerialize) {
  34893. return false;
  34894. }
  34895. }
  34896. return true;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. /** @ignore */
  34902. Geometry.prototype._rebuild = function () {
  34903. if (this._vertexArrayObjects) {
  34904. this._vertexArrayObjects = {};
  34905. }
  34906. // Index buffer
  34907. if (this._meshes.length !== 0 && this._indices) {
  34908. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34909. }
  34910. // Vertex buffers
  34911. for (var key in this._vertexBuffers) {
  34912. var vertexBuffer = this._vertexBuffers[key];
  34913. vertexBuffer._rebuild();
  34914. }
  34915. };
  34916. /**
  34917. * Affects all gemetry data in one call
  34918. * @param vertexData defines the geometry data
  34919. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34920. */
  34921. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34922. vertexData.applyToGeometry(this, updatable);
  34923. this.notifyUpdate();
  34924. };
  34925. /**
  34926. * Set specific vertex data
  34927. * @param kind defines the data kind (Position, normal, etc...)
  34928. * @param data defines the vertex data to use
  34929. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34930. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34931. */
  34932. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34933. if (updatable === void 0) { updatable = false; }
  34934. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34935. this.setVerticesBuffer(buffer);
  34936. };
  34937. /**
  34938. * Removes a specific vertex data
  34939. * @param kind defines the data kind (Position, normal, etc...)
  34940. */
  34941. Geometry.prototype.removeVerticesData = function (kind) {
  34942. if (this._vertexBuffers[kind]) {
  34943. this._vertexBuffers[kind].dispose();
  34944. delete this._vertexBuffers[kind];
  34945. }
  34946. };
  34947. /**
  34948. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34949. * @param buffer defines the vertex buffer to use
  34950. */
  34951. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34952. var kind = buffer.getKind();
  34953. if (this._vertexBuffers[kind]) {
  34954. this._vertexBuffers[kind].dispose();
  34955. }
  34956. this._vertexBuffers[kind] = buffer;
  34957. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34958. var data = buffer.getData();
  34959. var stride = buffer.getStrideSize();
  34960. this._totalVertices = data.length / stride;
  34961. this.updateExtend(data, stride);
  34962. this._resetPointsArrayCache();
  34963. var meshes = this._meshes;
  34964. var numOfMeshes = meshes.length;
  34965. for (var index = 0; index < numOfMeshes; index++) {
  34966. var mesh = meshes[index];
  34967. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34968. mesh._createGlobalSubMesh(false);
  34969. mesh.computeWorldMatrix(true);
  34970. }
  34971. }
  34972. this.notifyUpdate(kind);
  34973. if (this._vertexArrayObjects) {
  34974. this._disposeVertexArrayObjects();
  34975. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34976. }
  34977. };
  34978. /**
  34979. * Update a specific vertex buffer
  34980. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34981. * It will do nothing if the buffer is not updatable
  34982. * @param kind defines the data kind (Position, normal, etc...)
  34983. * @param data defines the data to use
  34984. * @param offset defines the offset in the target buffer where to store the data
  34985. */
  34986. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34987. var vertexBuffer = this.getVertexBuffer(kind);
  34988. if (!vertexBuffer) {
  34989. return;
  34990. }
  34991. vertexBuffer.updateDirectly(data, offset);
  34992. this.notifyUpdate(kind);
  34993. };
  34994. /**
  34995. * Update a specific vertex buffer
  34996. * This function will create a new buffer if the current one is not updatable
  34997. * @param kind defines the data kind (Position, normal, etc...)
  34998. * @param data defines the data to use
  34999. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35000. */
  35001. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35002. if (updateExtends === void 0) { updateExtends = false; }
  35003. var vertexBuffer = this.getVertexBuffer(kind);
  35004. if (!vertexBuffer) {
  35005. return;
  35006. }
  35007. vertexBuffer.update(data);
  35008. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35009. var stride = vertexBuffer.getStrideSize();
  35010. this._totalVertices = data.length / stride;
  35011. this.updateBoundingInfo(updateExtends, data);
  35012. }
  35013. this.notifyUpdate(kind);
  35014. };
  35015. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35016. if (updateExtends) {
  35017. this.updateExtend(data);
  35018. }
  35019. var meshes = this._meshes;
  35020. var numOfMeshes = meshes.length;
  35021. this._resetPointsArrayCache();
  35022. for (var index = 0; index < numOfMeshes; index++) {
  35023. var mesh = meshes[index];
  35024. if (updateExtends) {
  35025. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35026. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35027. var subMesh = mesh.subMeshes[subIndex];
  35028. subMesh.refreshBoundingInfo();
  35029. }
  35030. }
  35031. }
  35032. };
  35033. /** @ignore */
  35034. Geometry.prototype._bind = function (effect, indexToBind) {
  35035. if (!effect) {
  35036. return;
  35037. }
  35038. if (indexToBind === undefined) {
  35039. indexToBind = this._indexBuffer;
  35040. }
  35041. var vbs = this.getVertexBuffers();
  35042. if (!vbs) {
  35043. return;
  35044. }
  35045. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35046. this._engine.bindBuffers(vbs, indexToBind, effect);
  35047. return;
  35048. }
  35049. // Using VAO
  35050. if (!this._vertexArrayObjects[effect.key]) {
  35051. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35052. }
  35053. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35054. };
  35055. /**
  35056. * Gets total number of vertices
  35057. * @returns the total number of vertices
  35058. */
  35059. Geometry.prototype.getTotalVertices = function () {
  35060. if (!this.isReady()) {
  35061. return 0;
  35062. }
  35063. return this._totalVertices;
  35064. };
  35065. /**
  35066. * Gets a specific vertex data attached to this geometry
  35067. * @param kind defines the data kind (Position, normal, etc...)
  35068. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35069. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35070. * @returns a float array containing vertex data
  35071. */
  35072. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35073. var vertexBuffer = this.getVertexBuffer(kind);
  35074. if (!vertexBuffer) {
  35075. return null;
  35076. }
  35077. var orig = vertexBuffer.getData();
  35078. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35079. return orig;
  35080. }
  35081. else {
  35082. var len = orig.length;
  35083. var copy = [];
  35084. for (var i = 0; i < len; i++) {
  35085. copy.push(orig[i]);
  35086. }
  35087. return copy;
  35088. }
  35089. };
  35090. /**
  35091. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35092. * @param kind defines the data kind (Position, normal, etc...)
  35093. * @returns true if the vertex buffer with the specified kind is updatable
  35094. */
  35095. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35096. var vb = this._vertexBuffers[kind];
  35097. if (!vb) {
  35098. return false;
  35099. }
  35100. return vb.isUpdatable();
  35101. };
  35102. /**
  35103. * Gets a specific vertex buffer
  35104. * @param kind defines the data kind (Position, normal, etc...)
  35105. * @returns a {BABYLON.VertexBuffer}
  35106. */
  35107. Geometry.prototype.getVertexBuffer = function (kind) {
  35108. if (!this.isReady()) {
  35109. return null;
  35110. }
  35111. return this._vertexBuffers[kind];
  35112. };
  35113. /**
  35114. * Returns all vertex buffers
  35115. * @return an object holding all vertex buffers indexed by kind
  35116. */
  35117. Geometry.prototype.getVertexBuffers = function () {
  35118. if (!this.isReady()) {
  35119. return null;
  35120. }
  35121. return this._vertexBuffers;
  35122. };
  35123. /**
  35124. * Gets a boolean indicating if specific vertex buffer is present
  35125. * @param kind defines the data kind (Position, normal, etc...)
  35126. * @returns true if data is present
  35127. */
  35128. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35129. if (!this._vertexBuffers) {
  35130. if (this._delayInfo) {
  35131. return this._delayInfo.indexOf(kind) !== -1;
  35132. }
  35133. return false;
  35134. }
  35135. return this._vertexBuffers[kind] !== undefined;
  35136. };
  35137. /**
  35138. * Gets a list of all attached data kinds (Position, normal, etc...)
  35139. * @returns a list of string containing all kinds
  35140. */
  35141. Geometry.prototype.getVerticesDataKinds = function () {
  35142. var result = [];
  35143. var kind;
  35144. if (!this._vertexBuffers && this._delayInfo) {
  35145. for (kind in this._delayInfo) {
  35146. result.push(kind);
  35147. }
  35148. }
  35149. else {
  35150. for (kind in this._vertexBuffers) {
  35151. result.push(kind);
  35152. }
  35153. }
  35154. return result;
  35155. };
  35156. /**
  35157. * Update index buffer
  35158. * @param indices defines the indices to store in the index buffer
  35159. * @param offset defines the offset in the target buffer where to store the data
  35160. */
  35161. Geometry.prototype.updateIndices = function (indices, offset) {
  35162. if (!this._indexBuffer) {
  35163. return;
  35164. }
  35165. if (!this._indexBufferIsUpdatable) {
  35166. this.setIndices(indices, null, true);
  35167. }
  35168. else {
  35169. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35170. }
  35171. };
  35172. /**
  35173. * Creates a new index buffer
  35174. * @param indices defines the indices to store in the index buffer
  35175. * @param totalVertices defines the total number of vertices (could be null)
  35176. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35177. */
  35178. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35179. if (totalVertices === void 0) { totalVertices = null; }
  35180. if (updatable === void 0) { updatable = false; }
  35181. if (this._indexBuffer) {
  35182. this._engine._releaseBuffer(this._indexBuffer);
  35183. }
  35184. this._disposeVertexArrayObjects();
  35185. this._indices = indices;
  35186. this._indexBufferIsUpdatable = updatable;
  35187. if (this._meshes.length !== 0 && this._indices) {
  35188. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35189. }
  35190. if (totalVertices != undefined) {
  35191. this._totalVertices = totalVertices;
  35192. }
  35193. var meshes = this._meshes;
  35194. var numOfMeshes = meshes.length;
  35195. for (var index = 0; index < numOfMeshes; index++) {
  35196. meshes[index]._createGlobalSubMesh(true);
  35197. }
  35198. this.notifyUpdate();
  35199. };
  35200. /**
  35201. * Return the total number of indices
  35202. * @returns the total number of indices
  35203. */
  35204. Geometry.prototype.getTotalIndices = function () {
  35205. if (!this.isReady()) {
  35206. return 0;
  35207. }
  35208. return this._indices.length;
  35209. };
  35210. /**
  35211. * Gets the index buffer array
  35212. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35213. * @returns the index buffer array
  35214. */
  35215. Geometry.prototype.getIndices = function (copyWhenShared) {
  35216. if (!this.isReady()) {
  35217. return null;
  35218. }
  35219. var orig = this._indices;
  35220. if (!copyWhenShared || this._meshes.length === 1) {
  35221. return orig;
  35222. }
  35223. else {
  35224. var len = orig.length;
  35225. var copy = [];
  35226. for (var i = 0; i < len; i++) {
  35227. copy.push(orig[i]);
  35228. }
  35229. return copy;
  35230. }
  35231. };
  35232. /**
  35233. * Gets the index buffer
  35234. * @return the index buffer
  35235. */
  35236. Geometry.prototype.getIndexBuffer = function () {
  35237. if (!this.isReady()) {
  35238. return null;
  35239. }
  35240. return this._indexBuffer;
  35241. };
  35242. /** @ignore */
  35243. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35244. if (effect === void 0) { effect = null; }
  35245. if (!effect || !this._vertexArrayObjects) {
  35246. return;
  35247. }
  35248. if (this._vertexArrayObjects[effect.key]) {
  35249. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35250. delete this._vertexArrayObjects[effect.key];
  35251. }
  35252. };
  35253. /**
  35254. * Release the associated resources for a specific mesh
  35255. * @param mesh defines the source mesh
  35256. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35257. */
  35258. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35259. var meshes = this._meshes;
  35260. var index = meshes.indexOf(mesh);
  35261. if (index === -1) {
  35262. return;
  35263. }
  35264. meshes.splice(index, 1);
  35265. mesh._geometry = null;
  35266. if (meshes.length === 0 && shouldDispose) {
  35267. this.dispose();
  35268. }
  35269. };
  35270. /**
  35271. * Apply current geometry to a given mesh
  35272. * @param mesh defines the mesh to apply geometry to
  35273. */
  35274. Geometry.prototype.applyToMesh = function (mesh) {
  35275. if (mesh._geometry === this) {
  35276. return;
  35277. }
  35278. var previousGeometry = mesh._geometry;
  35279. if (previousGeometry) {
  35280. previousGeometry.releaseForMesh(mesh);
  35281. }
  35282. var meshes = this._meshes;
  35283. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35284. mesh._geometry = this;
  35285. this._scene.pushGeometry(this);
  35286. meshes.push(mesh);
  35287. if (this.isReady()) {
  35288. this._applyToMesh(mesh);
  35289. }
  35290. else {
  35291. mesh._boundingInfo = this._boundingInfo;
  35292. }
  35293. };
  35294. Geometry.prototype.updateExtend = function (data, stride) {
  35295. if (data === void 0) { data = null; }
  35296. if (!data) {
  35297. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35298. }
  35299. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35300. };
  35301. Geometry.prototype._applyToMesh = function (mesh) {
  35302. var numOfMeshes = this._meshes.length;
  35303. // vertexBuffers
  35304. for (var kind in this._vertexBuffers) {
  35305. if (numOfMeshes === 1) {
  35306. this._vertexBuffers[kind].create();
  35307. }
  35308. var buffer = this._vertexBuffers[kind].getBuffer();
  35309. if (buffer)
  35310. buffer.references = numOfMeshes;
  35311. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35312. if (!this._extend) {
  35313. this.updateExtend(this._vertexBuffers[kind].getData());
  35314. }
  35315. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35316. mesh._createGlobalSubMesh(false);
  35317. //bounding info was just created again, world matrix should be applied again.
  35318. mesh._updateBoundingInfo();
  35319. }
  35320. }
  35321. // indexBuffer
  35322. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35323. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35324. }
  35325. if (this._indexBuffer) {
  35326. this._indexBuffer.references = numOfMeshes;
  35327. }
  35328. };
  35329. Geometry.prototype.notifyUpdate = function (kind) {
  35330. if (this.onGeometryUpdated) {
  35331. this.onGeometryUpdated(this, kind);
  35332. }
  35333. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35334. var mesh = _a[_i];
  35335. mesh._markSubMeshesAsAttributesDirty();
  35336. }
  35337. };
  35338. /**
  35339. * Load the geometry if it was flagged as delay loaded
  35340. * @param scene defines the hosting scene
  35341. * @param onLoaded defines a callback called when the geometry is loaded
  35342. */
  35343. Geometry.prototype.load = function (scene, onLoaded) {
  35344. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35345. return;
  35346. }
  35347. if (this.isReady()) {
  35348. if (onLoaded) {
  35349. onLoaded();
  35350. }
  35351. return;
  35352. }
  35353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35354. this._queueLoad(scene, onLoaded);
  35355. };
  35356. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35357. var _this = this;
  35358. if (!this.delayLoadingFile) {
  35359. return;
  35360. }
  35361. scene._addPendingData(this);
  35362. scene._loadFile(this.delayLoadingFile, function (data) {
  35363. if (!_this._delayLoadingFunction) {
  35364. return;
  35365. }
  35366. _this._delayLoadingFunction(JSON.parse(data), _this);
  35367. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35368. _this._delayInfo = [];
  35369. scene._removePendingData(_this);
  35370. var meshes = _this._meshes;
  35371. var numOfMeshes = meshes.length;
  35372. for (var index = 0; index < numOfMeshes; index++) {
  35373. _this._applyToMesh(meshes[index]);
  35374. }
  35375. if (onLoaded) {
  35376. onLoaded();
  35377. }
  35378. }, undefined, true);
  35379. };
  35380. /**
  35381. * Invert the geometry to move from a right handed system to a left handed one.
  35382. */
  35383. Geometry.prototype.toLeftHanded = function () {
  35384. // Flip faces
  35385. var tIndices = this.getIndices(false);
  35386. if (tIndices != null && tIndices.length > 0) {
  35387. for (var i = 0; i < tIndices.length; i += 3) {
  35388. var tTemp = tIndices[i + 0];
  35389. tIndices[i + 0] = tIndices[i + 2];
  35390. tIndices[i + 2] = tTemp;
  35391. }
  35392. this.setIndices(tIndices);
  35393. }
  35394. // Negate position.z
  35395. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35396. if (tPositions != null && tPositions.length > 0) {
  35397. for (var i = 0; i < tPositions.length; i += 3) {
  35398. tPositions[i + 2] = -tPositions[i + 2];
  35399. }
  35400. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35401. }
  35402. // Negate normal.z
  35403. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35404. if (tNormals != null && tNormals.length > 0) {
  35405. for (var i = 0; i < tNormals.length; i += 3) {
  35406. tNormals[i + 2] = -tNormals[i + 2];
  35407. }
  35408. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35409. }
  35410. };
  35411. // Cache
  35412. /** @ignore */
  35413. Geometry.prototype._resetPointsArrayCache = function () {
  35414. this._positions = null;
  35415. };
  35416. /** @ignore */
  35417. Geometry.prototype._generatePointsArray = function () {
  35418. if (this._positions)
  35419. return true;
  35420. this._positions = [];
  35421. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35422. if (!data) {
  35423. return false;
  35424. }
  35425. for (var index = 0; index < data.length; index += 3) {
  35426. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35427. }
  35428. return true;
  35429. };
  35430. /**
  35431. * Gets a value indicating if the geometry is disposed
  35432. * @returns true if the geometry was disposed
  35433. */
  35434. Geometry.prototype.isDisposed = function () {
  35435. return this._isDisposed;
  35436. };
  35437. Geometry.prototype._disposeVertexArrayObjects = function () {
  35438. if (this._vertexArrayObjects) {
  35439. for (var kind in this._vertexArrayObjects) {
  35440. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35441. }
  35442. this._vertexArrayObjects = {};
  35443. }
  35444. };
  35445. /**
  35446. * Free all associated resources
  35447. */
  35448. Geometry.prototype.dispose = function () {
  35449. var meshes = this._meshes;
  35450. var numOfMeshes = meshes.length;
  35451. var index;
  35452. for (index = 0; index < numOfMeshes; index++) {
  35453. this.releaseForMesh(meshes[index]);
  35454. }
  35455. this._meshes = [];
  35456. this._disposeVertexArrayObjects();
  35457. for (var kind in this._vertexBuffers) {
  35458. this._vertexBuffers[kind].dispose();
  35459. }
  35460. this._vertexBuffers = {};
  35461. this._totalVertices = 0;
  35462. if (this._indexBuffer) {
  35463. this._engine._releaseBuffer(this._indexBuffer);
  35464. }
  35465. this._indexBuffer = null;
  35466. this._indices = [];
  35467. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35468. this.delayLoadingFile = null;
  35469. this._delayLoadingFunction = null;
  35470. this._delayInfo = [];
  35471. this._boundingInfo = null;
  35472. this._scene.removeGeometry(this);
  35473. this._isDisposed = true;
  35474. };
  35475. /**
  35476. * Clone the current geometry into a new geometry
  35477. * @param id defines the unique ID of the new geometry
  35478. * @returns a new geometry object
  35479. */
  35480. Geometry.prototype.copy = function (id) {
  35481. var vertexData = new BABYLON.VertexData();
  35482. vertexData.indices = [];
  35483. var indices = this.getIndices();
  35484. if (indices) {
  35485. for (var index = 0; index < indices.length; index++) {
  35486. vertexData.indices.push(indices[index]);
  35487. }
  35488. }
  35489. var updatable = false;
  35490. var stopChecking = false;
  35491. var kind;
  35492. for (kind in this._vertexBuffers) {
  35493. // using slice() to make a copy of the array and not just reference it
  35494. var data = this.getVerticesData(kind);
  35495. if (data instanceof Float32Array) {
  35496. vertexData.set(new Float32Array(data), kind);
  35497. }
  35498. else {
  35499. vertexData.set(data.slice(0), kind);
  35500. }
  35501. if (!stopChecking) {
  35502. var vb = this.getVertexBuffer(kind);
  35503. if (vb) {
  35504. updatable = vb.isUpdatable();
  35505. stopChecking = !updatable;
  35506. }
  35507. }
  35508. }
  35509. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35510. geometry.delayLoadState = this.delayLoadState;
  35511. geometry.delayLoadingFile = this.delayLoadingFile;
  35512. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35513. for (kind in this._delayInfo) {
  35514. geometry._delayInfo = geometry._delayInfo || [];
  35515. geometry._delayInfo.push(kind);
  35516. }
  35517. // Bounding info
  35518. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35519. return geometry;
  35520. };
  35521. /**
  35522. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35523. * @return a JSON representation of the current geometry data (without the vertices data)
  35524. */
  35525. Geometry.prototype.serialize = function () {
  35526. var serializationObject = {};
  35527. serializationObject.id = this.id;
  35528. serializationObject.updatable = this._updatable;
  35529. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35530. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35531. }
  35532. return serializationObject;
  35533. };
  35534. Geometry.prototype.toNumberArray = function (origin) {
  35535. if (Array.isArray(origin)) {
  35536. return origin;
  35537. }
  35538. else {
  35539. return Array.prototype.slice.call(origin);
  35540. }
  35541. };
  35542. /**
  35543. * Serialize all vertices data into a JSON oject
  35544. * @returns a JSON representation of the current geometry data
  35545. */
  35546. Geometry.prototype.serializeVerticeData = function () {
  35547. var serializationObject = this.serialize();
  35548. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35549. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35550. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35551. serializationObject.positions._updatable = true;
  35552. }
  35553. }
  35554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35555. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35556. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35557. serializationObject.normals._updatable = true;
  35558. }
  35559. }
  35560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35561. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35562. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35563. serializationObject.tangets._updatable = true;
  35564. }
  35565. }
  35566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35567. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35568. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35569. serializationObject.uvs._updatable = true;
  35570. }
  35571. }
  35572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35573. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35574. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35575. serializationObject.uv2s._updatable = true;
  35576. }
  35577. }
  35578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35579. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35580. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35581. serializationObject.uv3s._updatable = true;
  35582. }
  35583. }
  35584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35585. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35586. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35587. serializationObject.uv4s._updatable = true;
  35588. }
  35589. }
  35590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35591. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35593. serializationObject.uv5s._updatable = true;
  35594. }
  35595. }
  35596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35597. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35599. serializationObject.uv6s._updatable = true;
  35600. }
  35601. }
  35602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35603. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35605. serializationObject.colors._updatable = true;
  35606. }
  35607. }
  35608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35609. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35610. serializationObject.matricesIndices._isExpanded = true;
  35611. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35612. serializationObject.matricesIndices._updatable = true;
  35613. }
  35614. }
  35615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35616. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35617. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35618. serializationObject.matricesWeights._updatable = true;
  35619. }
  35620. }
  35621. serializationObject.indices = this.toNumberArray(this.getIndices());
  35622. return serializationObject;
  35623. };
  35624. // Statics
  35625. /**
  35626. * Extracts a clone of a mesh geometry
  35627. * @param mesh defines the source mesh
  35628. * @param id defines the unique ID of the new geometry object
  35629. * @returns the new geometry object
  35630. */
  35631. Geometry.ExtractFromMesh = function (mesh, id) {
  35632. var geometry = mesh._geometry;
  35633. if (!geometry) {
  35634. return null;
  35635. }
  35636. return geometry.copy(id);
  35637. };
  35638. /**
  35639. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35640. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35641. * Be aware Math.random() could cause collisions, but:
  35642. * "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"
  35643. * @returns a string containing a new GUID
  35644. */
  35645. Geometry.RandomId = function () {
  35646. return BABYLON.Tools.RandomId();
  35647. };
  35648. /** @ignore */
  35649. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35650. var scene = mesh.getScene();
  35651. // Geometry
  35652. var geometryId = parsedGeometry.geometryId;
  35653. if (geometryId) {
  35654. var geometry = scene.getGeometryByID(geometryId);
  35655. if (geometry) {
  35656. geometry.applyToMesh(mesh);
  35657. }
  35658. }
  35659. else if (parsedGeometry instanceof ArrayBuffer) {
  35660. var binaryInfo = mesh._binaryInfo;
  35661. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35662. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35663. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35664. }
  35665. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35666. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35667. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35668. }
  35669. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35670. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35671. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35672. }
  35673. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35674. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35675. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35676. }
  35677. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35678. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35679. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35680. }
  35681. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35682. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35683. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35684. }
  35685. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35686. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35687. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35688. }
  35689. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35690. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35691. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35692. }
  35693. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35694. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35695. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35696. }
  35697. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35698. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35699. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35700. }
  35701. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35702. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35704. }
  35705. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35706. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35708. }
  35709. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35710. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35711. mesh.setIndices(indicesData, null);
  35712. }
  35713. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35714. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35715. mesh.subMeshes = [];
  35716. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35717. var materialIndex = subMeshesData[(i * 5) + 0];
  35718. var verticesStart = subMeshesData[(i * 5) + 1];
  35719. var verticesCount = subMeshesData[(i * 5) + 2];
  35720. var indexStart = subMeshesData[(i * 5) + 3];
  35721. var indexCount = subMeshesData[(i * 5) + 4];
  35722. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35723. }
  35724. }
  35725. }
  35726. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35727. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35728. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35729. if (parsedGeometry.tangents) {
  35730. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35731. }
  35732. if (parsedGeometry.uvs) {
  35733. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35734. }
  35735. if (parsedGeometry.uvs2) {
  35736. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35737. }
  35738. if (parsedGeometry.uvs3) {
  35739. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35740. }
  35741. if (parsedGeometry.uvs4) {
  35742. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35743. }
  35744. if (parsedGeometry.uvs5) {
  35745. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35746. }
  35747. if (parsedGeometry.uvs6) {
  35748. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35749. }
  35750. if (parsedGeometry.colors) {
  35751. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35752. }
  35753. if (parsedGeometry.matricesIndices) {
  35754. if (!parsedGeometry.matricesIndices._isExpanded) {
  35755. var floatIndices = [];
  35756. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35757. var matricesIndex = parsedGeometry.matricesIndices[i];
  35758. floatIndices.push(matricesIndex & 0x000000FF);
  35759. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35760. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35761. floatIndices.push(matricesIndex >> 24);
  35762. }
  35763. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35764. }
  35765. else {
  35766. delete parsedGeometry.matricesIndices._isExpanded;
  35767. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35768. }
  35769. }
  35770. if (parsedGeometry.matricesIndicesExtra) {
  35771. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35772. var floatIndices = [];
  35773. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35774. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35775. floatIndices.push(matricesIndex & 0x000000FF);
  35776. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35777. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35778. floatIndices.push(matricesIndex >> 24);
  35779. }
  35780. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35781. }
  35782. else {
  35783. delete parsedGeometry.matricesIndices._isExpanded;
  35784. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35785. }
  35786. }
  35787. if (parsedGeometry.matricesWeights) {
  35788. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35789. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35790. }
  35791. if (parsedGeometry.matricesWeightsExtra) {
  35792. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35793. }
  35794. mesh.setIndices(parsedGeometry.indices, null);
  35795. }
  35796. // SubMeshes
  35797. if (parsedGeometry.subMeshes) {
  35798. mesh.subMeshes = [];
  35799. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35800. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35801. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35802. }
  35803. }
  35804. // Flat shading
  35805. if (mesh._shouldGenerateFlatShading) {
  35806. mesh.convertToFlatShadedMesh();
  35807. delete mesh._shouldGenerateFlatShading;
  35808. }
  35809. // Update
  35810. mesh.computeWorldMatrix(true);
  35811. // Octree
  35812. var sceneOctree = scene.selectionOctree;
  35813. if (sceneOctree !== undefined && sceneOctree !== null) {
  35814. sceneOctree.addMesh(mesh);
  35815. }
  35816. };
  35817. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35818. var epsilon = 1e-3;
  35819. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35820. return;
  35821. }
  35822. var noInfluenceBoneIndex = 0.0;
  35823. if (parsedGeometry.skeletonId > -1) {
  35824. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35825. if (!skeleton) {
  35826. return;
  35827. }
  35828. noInfluenceBoneIndex = skeleton.bones.length;
  35829. }
  35830. else {
  35831. return;
  35832. }
  35833. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35834. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35835. var matricesWeights = parsedGeometry.matricesWeights;
  35836. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35837. var influencers = parsedGeometry.numBoneInfluencer;
  35838. var size = matricesWeights.length;
  35839. for (var i = 0; i < size; i += 4) {
  35840. var weight = 0.0;
  35841. var firstZeroWeight = -1;
  35842. for (var j = 0; j < 4; j++) {
  35843. var w = matricesWeights[i + j];
  35844. weight += w;
  35845. if (w < epsilon && firstZeroWeight < 0) {
  35846. firstZeroWeight = j;
  35847. }
  35848. }
  35849. if (matricesWeightsExtra) {
  35850. for (var j = 0; j < 4; j++) {
  35851. var w = matricesWeightsExtra[i + j];
  35852. weight += w;
  35853. if (w < epsilon && firstZeroWeight < 0) {
  35854. firstZeroWeight = j + 4;
  35855. }
  35856. }
  35857. }
  35858. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35859. firstZeroWeight = influencers - 1;
  35860. }
  35861. if (weight > epsilon) {
  35862. var mweight = 1.0 / weight;
  35863. for (var j = 0; j < 4; j++) {
  35864. matricesWeights[i + j] *= mweight;
  35865. }
  35866. if (matricesWeightsExtra) {
  35867. for (var j = 0; j < 4; j++) {
  35868. matricesWeightsExtra[i + j] *= mweight;
  35869. }
  35870. }
  35871. }
  35872. else {
  35873. if (firstZeroWeight >= 4) {
  35874. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35875. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35876. }
  35877. else {
  35878. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35879. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35880. }
  35881. }
  35882. }
  35883. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35884. if (parsedGeometry.matricesWeightsExtra) {
  35885. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35886. }
  35887. };
  35888. /**
  35889. * Create a new geometry from persisted data (Using .babylon file format)
  35890. * @param parsedVertexData defines the persisted data
  35891. * @param scene defines the hosting scene
  35892. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35893. * @returns the new geometry object
  35894. */
  35895. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35896. if (scene.getGeometryByID(parsedVertexData.id)) {
  35897. return null; // null since geometry could be something else than a box...
  35898. }
  35899. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35900. if (BABYLON.Tags) {
  35901. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35902. }
  35903. if (parsedVertexData.delayLoadingFile) {
  35904. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35905. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35906. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35907. geometry._delayInfo = [];
  35908. if (parsedVertexData.hasUVs) {
  35909. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35910. }
  35911. if (parsedVertexData.hasUVs2) {
  35912. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35913. }
  35914. if (parsedVertexData.hasUVs3) {
  35915. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35916. }
  35917. if (parsedVertexData.hasUVs4) {
  35918. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35919. }
  35920. if (parsedVertexData.hasUVs5) {
  35921. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35922. }
  35923. if (parsedVertexData.hasUVs6) {
  35924. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35925. }
  35926. if (parsedVertexData.hasColors) {
  35927. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35928. }
  35929. if (parsedVertexData.hasMatricesIndices) {
  35930. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35931. }
  35932. if (parsedVertexData.hasMatricesWeights) {
  35933. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35934. }
  35935. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35936. }
  35937. else {
  35938. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35939. }
  35940. scene.pushGeometry(geometry, true);
  35941. return geometry;
  35942. };
  35943. return Geometry;
  35944. }());
  35945. BABYLON.Geometry = Geometry;
  35946. // Primitives
  35947. /// Abstract class
  35948. /**
  35949. * Abstract class used to provide common services for all typed geometries
  35950. */
  35951. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35952. __extends(_PrimitiveGeometry, _super);
  35953. /**
  35954. * Creates a new typed geometry
  35955. * @param id defines the unique ID of the geometry
  35956. * @param scene defines the hosting scene
  35957. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35958. * @param mesh defines the hosting mesh (can be null)
  35959. */
  35960. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35961. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35962. if (mesh === void 0) { mesh = null; }
  35963. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35964. _this._canBeRegenerated = _canBeRegenerated;
  35965. _this._beingRegenerated = true;
  35966. _this.regenerate();
  35967. _this._beingRegenerated = false;
  35968. return _this;
  35969. }
  35970. /**
  35971. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35972. * @returns true if the geometry can be regenerated
  35973. */
  35974. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35975. return this._canBeRegenerated;
  35976. };
  35977. /**
  35978. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35979. */
  35980. _PrimitiveGeometry.prototype.regenerate = function () {
  35981. if (!this._canBeRegenerated) {
  35982. return;
  35983. }
  35984. this._beingRegenerated = true;
  35985. this.setAllVerticesData(this._regenerateVertexData(), false);
  35986. this._beingRegenerated = false;
  35987. };
  35988. /**
  35989. * Clone the geometry
  35990. * @param id defines the unique ID of the new geometry
  35991. * @returns the new geometry
  35992. */
  35993. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35994. return _super.prototype.copy.call(this, id);
  35995. };
  35996. // overrides
  35997. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35998. if (!this._beingRegenerated) {
  35999. return;
  36000. }
  36001. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36002. };
  36003. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36004. if (!this._beingRegenerated) {
  36005. return;
  36006. }
  36007. _super.prototype.setVerticesData.call(this, kind, data, false);
  36008. };
  36009. // to override
  36010. /** @ignore */
  36011. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36012. throw new Error("Abstract method");
  36013. };
  36014. _PrimitiveGeometry.prototype.copy = function (id) {
  36015. throw new Error("Must be overriden in sub-classes.");
  36016. };
  36017. _PrimitiveGeometry.prototype.serialize = function () {
  36018. var serializationObject = _super.prototype.serialize.call(this);
  36019. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36020. return serializationObject;
  36021. };
  36022. return _PrimitiveGeometry;
  36023. }(Geometry));
  36024. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36025. /**
  36026. * Creates a ribbon geometry
  36027. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36028. */
  36029. var RibbonGeometry = /** @class */ (function (_super) {
  36030. __extends(RibbonGeometry, _super);
  36031. /**
  36032. * Creates a ribbon geometry
  36033. * @param id defines the unique ID of the geometry
  36034. * @param scene defines the hosting scene
  36035. * @param pathArray defines the array of paths to use
  36036. * @param closeArray defines if the last path and the first path must be joined
  36037. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36038. * @param offset defines the offset between points
  36039. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36040. * @param mesh defines the hosting mesh (can be null)
  36041. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36042. */
  36043. function RibbonGeometry(id, scene,
  36044. /**
  36045. * Defines the array of paths to use
  36046. */
  36047. pathArray,
  36048. /**
  36049. * Defines if the last and first points of each path in your pathArray must be joined
  36050. */
  36051. closeArray,
  36052. /**
  36053. * Defines if the last and first points of each path in your pathArray must be joined
  36054. */
  36055. closePath,
  36056. /**
  36057. * Defines the offset between points
  36058. */
  36059. offset, canBeRegenerated, mesh,
  36060. /**
  36061. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36062. */
  36063. side) {
  36064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36065. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36066. _this.pathArray = pathArray;
  36067. _this.closeArray = closeArray;
  36068. _this.closePath = closePath;
  36069. _this.offset = offset;
  36070. _this.side = side;
  36071. return _this;
  36072. }
  36073. /** @ignore */
  36074. RibbonGeometry.prototype._regenerateVertexData = function () {
  36075. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36076. };
  36077. RibbonGeometry.prototype.copy = function (id) {
  36078. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36079. };
  36080. return RibbonGeometry;
  36081. }(_PrimitiveGeometry));
  36082. BABYLON.RibbonGeometry = RibbonGeometry;
  36083. /**
  36084. * Creates a box geometry
  36085. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36086. */
  36087. var BoxGeometry = /** @class */ (function (_super) {
  36088. __extends(BoxGeometry, _super);
  36089. /**
  36090. * Creates a box geometry
  36091. * @param id defines the unique ID of the geometry
  36092. * @param scene defines the hosting scene
  36093. * @param size defines the zise of the box (width, height and depth are the same)
  36094. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36095. * @param mesh defines the hosting mesh (can be null)
  36096. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36097. */
  36098. function BoxGeometry(id, scene,
  36099. /**
  36100. * Defines the zise of the box (width, height and depth are the same)
  36101. */
  36102. size, canBeRegenerated, mesh,
  36103. /**
  36104. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36105. */
  36106. side) {
  36107. if (mesh === void 0) { mesh = null; }
  36108. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36109. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36110. _this.size = size;
  36111. _this.side = side;
  36112. return _this;
  36113. }
  36114. BoxGeometry.prototype._regenerateVertexData = function () {
  36115. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36116. };
  36117. BoxGeometry.prototype.copy = function (id) {
  36118. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36119. };
  36120. BoxGeometry.prototype.serialize = function () {
  36121. var serializationObject = _super.prototype.serialize.call(this);
  36122. serializationObject.size = this.size;
  36123. return serializationObject;
  36124. };
  36125. BoxGeometry.Parse = function (parsedBox, scene) {
  36126. if (scene.getGeometryByID(parsedBox.id)) {
  36127. return null; // null since geometry could be something else than a box...
  36128. }
  36129. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36130. if (BABYLON.Tags) {
  36131. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36132. }
  36133. scene.pushGeometry(box, true);
  36134. return box;
  36135. };
  36136. return BoxGeometry;
  36137. }(_PrimitiveGeometry));
  36138. BABYLON.BoxGeometry = BoxGeometry;
  36139. /**
  36140. * Creates a sphere geometry
  36141. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36142. */
  36143. var SphereGeometry = /** @class */ (function (_super) {
  36144. __extends(SphereGeometry, _super);
  36145. /**
  36146. * Create a new sphere geometry
  36147. * @param id defines the unique ID of the geometry
  36148. * @param scene defines the hosting scene
  36149. * @param segments defines the number of segments to use to create the sphere
  36150. * @param diameter defines the diameter of the sphere
  36151. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36152. * @param mesh defines the hosting mesh (can be null)
  36153. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36154. */
  36155. function SphereGeometry(id, scene,
  36156. /**
  36157. * Defines the number of segments to use to create the sphere
  36158. */
  36159. segments,
  36160. /**
  36161. * Defines the diameter of the sphere
  36162. */
  36163. diameter, canBeRegenerated, mesh,
  36164. /**
  36165. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36166. */
  36167. side) {
  36168. if (mesh === void 0) { mesh = null; }
  36169. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36170. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36171. _this.segments = segments;
  36172. _this.diameter = diameter;
  36173. _this.side = side;
  36174. return _this;
  36175. }
  36176. SphereGeometry.prototype._regenerateVertexData = function () {
  36177. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36178. };
  36179. SphereGeometry.prototype.copy = function (id) {
  36180. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36181. };
  36182. SphereGeometry.prototype.serialize = function () {
  36183. var serializationObject = _super.prototype.serialize.call(this);
  36184. serializationObject.segments = this.segments;
  36185. serializationObject.diameter = this.diameter;
  36186. return serializationObject;
  36187. };
  36188. SphereGeometry.Parse = function (parsedSphere, scene) {
  36189. if (scene.getGeometryByID(parsedSphere.id)) {
  36190. return null; // null since geometry could be something else than a sphere...
  36191. }
  36192. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36193. if (BABYLON.Tags) {
  36194. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36195. }
  36196. scene.pushGeometry(sphere, true);
  36197. return sphere;
  36198. };
  36199. return SphereGeometry;
  36200. }(_PrimitiveGeometry));
  36201. BABYLON.SphereGeometry = SphereGeometry;
  36202. /**
  36203. * Creates a disc geometry
  36204. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36205. */
  36206. var DiscGeometry = /** @class */ (function (_super) {
  36207. __extends(DiscGeometry, _super);
  36208. /**
  36209. * Creates a new disc geometry
  36210. * @param id defines the unique ID of the geometry
  36211. * @param scene defines the hosting scene
  36212. * @param radius defines the radius of the disc
  36213. * @param tessellation defines the tesselation factor to apply to the disc
  36214. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36215. * @param mesh defines the hosting mesh (can be null)
  36216. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36217. */
  36218. function DiscGeometry(id, scene,
  36219. /**
  36220. * Defines the radius of the disc
  36221. */
  36222. radius,
  36223. /**
  36224. * Defines the tesselation factor to apply to the disc
  36225. */
  36226. tessellation, canBeRegenerated, mesh,
  36227. /**
  36228. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36229. */
  36230. side) {
  36231. if (mesh === void 0) { mesh = null; }
  36232. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36234. _this.radius = radius;
  36235. _this.tessellation = tessellation;
  36236. _this.side = side;
  36237. return _this;
  36238. }
  36239. DiscGeometry.prototype._regenerateVertexData = function () {
  36240. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36241. };
  36242. DiscGeometry.prototype.copy = function (id) {
  36243. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36244. };
  36245. return DiscGeometry;
  36246. }(_PrimitiveGeometry));
  36247. BABYLON.DiscGeometry = DiscGeometry;
  36248. /**
  36249. * Creates a new cylinder geometry
  36250. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36251. */
  36252. var CylinderGeometry = /** @class */ (function (_super) {
  36253. __extends(CylinderGeometry, _super);
  36254. /**
  36255. * Creates a new cylinder geometry
  36256. * @param id defines the unique ID of the geometry
  36257. * @param scene defines the hosting scene
  36258. * @param height defines the height of the cylinder
  36259. * @param diameterTop defines the diameter of the cylinder's top cap
  36260. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36261. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36262. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36263. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36264. * @param mesh defines the hosting mesh (can be null)
  36265. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36266. */
  36267. function CylinderGeometry(id, scene,
  36268. /**
  36269. * Defines the height of the cylinder
  36270. */
  36271. height,
  36272. /**
  36273. * Defines the diameter of the cylinder's top cap
  36274. */
  36275. diameterTop,
  36276. /**
  36277. * Defines the diameter of the cylinder's bottom cap
  36278. */
  36279. diameterBottom,
  36280. /**
  36281. * Defines the tessellation factor to apply to the cylinder
  36282. */
  36283. tessellation,
  36284. /**
  36285. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36286. */
  36287. subdivisions, canBeRegenerated, mesh,
  36288. /**
  36289. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36290. */
  36291. side) {
  36292. if (subdivisions === void 0) { subdivisions = 1; }
  36293. if (mesh === void 0) { mesh = null; }
  36294. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36295. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36296. _this.height = height;
  36297. _this.diameterTop = diameterTop;
  36298. _this.diameterBottom = diameterBottom;
  36299. _this.tessellation = tessellation;
  36300. _this.subdivisions = subdivisions;
  36301. _this.side = side;
  36302. return _this;
  36303. }
  36304. CylinderGeometry.prototype._regenerateVertexData = function () {
  36305. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36306. };
  36307. CylinderGeometry.prototype.copy = function (id) {
  36308. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36309. };
  36310. CylinderGeometry.prototype.serialize = function () {
  36311. var serializationObject = _super.prototype.serialize.call(this);
  36312. serializationObject.height = this.height;
  36313. serializationObject.diameterTop = this.diameterTop;
  36314. serializationObject.diameterBottom = this.diameterBottom;
  36315. serializationObject.tessellation = this.tessellation;
  36316. return serializationObject;
  36317. };
  36318. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36319. if (scene.getGeometryByID(parsedCylinder.id)) {
  36320. return null; // null since geometry could be something else than a cylinder...
  36321. }
  36322. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36323. if (BABYLON.Tags) {
  36324. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36325. }
  36326. scene.pushGeometry(cylinder, true);
  36327. return cylinder;
  36328. };
  36329. return CylinderGeometry;
  36330. }(_PrimitiveGeometry));
  36331. BABYLON.CylinderGeometry = CylinderGeometry;
  36332. /**
  36333. * Creates a new torus geometry
  36334. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36335. */
  36336. var TorusGeometry = /** @class */ (function (_super) {
  36337. __extends(TorusGeometry, _super);
  36338. /**
  36339. * Creates a new torus geometry
  36340. * @param id defines the unique ID of the geometry
  36341. * @param scene defines the hosting scene
  36342. * @param diameter defines the diameter of the torus
  36343. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36344. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36345. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36346. * @param mesh defines the hosting mesh (can be null)
  36347. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36348. */
  36349. function TorusGeometry(id, scene,
  36350. /**
  36351. * Defines the diameter of the torus
  36352. */
  36353. diameter,
  36354. /**
  36355. * Defines the thickness of the torus (ie. internal diameter)
  36356. */
  36357. thickness,
  36358. /**
  36359. * Defines the tesselation factor to apply to the torus
  36360. */
  36361. tessellation, canBeRegenerated, mesh,
  36362. /**
  36363. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36364. */
  36365. side) {
  36366. if (mesh === void 0) { mesh = null; }
  36367. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36368. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36369. _this.diameter = diameter;
  36370. _this.thickness = thickness;
  36371. _this.tessellation = tessellation;
  36372. _this.side = side;
  36373. return _this;
  36374. }
  36375. TorusGeometry.prototype._regenerateVertexData = function () {
  36376. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36377. };
  36378. TorusGeometry.prototype.copy = function (id) {
  36379. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36380. };
  36381. TorusGeometry.prototype.serialize = function () {
  36382. var serializationObject = _super.prototype.serialize.call(this);
  36383. serializationObject.diameter = this.diameter;
  36384. serializationObject.thickness = this.thickness;
  36385. serializationObject.tessellation = this.tessellation;
  36386. return serializationObject;
  36387. };
  36388. TorusGeometry.Parse = function (parsedTorus, scene) {
  36389. if (scene.getGeometryByID(parsedTorus.id)) {
  36390. return null; // null since geometry could be something else than a torus...
  36391. }
  36392. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36393. if (BABYLON.Tags) {
  36394. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36395. }
  36396. scene.pushGeometry(torus, true);
  36397. return torus;
  36398. };
  36399. return TorusGeometry;
  36400. }(_PrimitiveGeometry));
  36401. BABYLON.TorusGeometry = TorusGeometry;
  36402. /**
  36403. * Creates a new ground geometry
  36404. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36405. */
  36406. var GroundGeometry = /** @class */ (function (_super) {
  36407. __extends(GroundGeometry, _super);
  36408. /**
  36409. * Creates a new ground geometry
  36410. * @param id defines the unique ID of the geometry
  36411. * @param scene defines the hosting scene
  36412. * @param width defines the width of the ground
  36413. * @param height defines the height of the ground
  36414. * @param subdivisions defines the subdivisions to apply to the ground
  36415. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36416. * @param mesh defines the hosting mesh (can be null)
  36417. */
  36418. function GroundGeometry(id, scene,
  36419. /**
  36420. * Defines the width of the ground
  36421. */
  36422. width,
  36423. /**
  36424. * Defines the height of the ground
  36425. */
  36426. height,
  36427. /**
  36428. * Defines the subdivisions to apply to the ground
  36429. */
  36430. subdivisions, canBeRegenerated, mesh) {
  36431. if (mesh === void 0) { mesh = null; }
  36432. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36433. _this.width = width;
  36434. _this.height = height;
  36435. _this.subdivisions = subdivisions;
  36436. return _this;
  36437. }
  36438. GroundGeometry.prototype._regenerateVertexData = function () {
  36439. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36440. };
  36441. GroundGeometry.prototype.copy = function (id) {
  36442. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36443. };
  36444. GroundGeometry.prototype.serialize = function () {
  36445. var serializationObject = _super.prototype.serialize.call(this);
  36446. serializationObject.width = this.width;
  36447. serializationObject.height = this.height;
  36448. serializationObject.subdivisions = this.subdivisions;
  36449. return serializationObject;
  36450. };
  36451. GroundGeometry.Parse = function (parsedGround, scene) {
  36452. if (scene.getGeometryByID(parsedGround.id)) {
  36453. return null; // null since geometry could be something else than a ground...
  36454. }
  36455. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36456. if (BABYLON.Tags) {
  36457. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36458. }
  36459. scene.pushGeometry(ground, true);
  36460. return ground;
  36461. };
  36462. return GroundGeometry;
  36463. }(_PrimitiveGeometry));
  36464. BABYLON.GroundGeometry = GroundGeometry;
  36465. /**
  36466. * Creates a tiled ground geometry
  36467. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36468. */
  36469. var TiledGroundGeometry = /** @class */ (function (_super) {
  36470. __extends(TiledGroundGeometry, _super);
  36471. /**
  36472. * Creates a tiled ground geometry
  36473. * @param id defines the unique ID of the geometry
  36474. * @param scene defines the hosting scene
  36475. * @param xmin defines the minimum value on X axis
  36476. * @param zmin defines the minimum value on Z axis
  36477. * @param xmax defines the maximum value on X axis
  36478. * @param zmax defines the maximum value on Z axis
  36479. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36480. * @param precision defines the precision to use when computing the tiles
  36481. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36482. * @param mesh defines the hosting mesh (can be null)
  36483. */
  36484. function TiledGroundGeometry(id, scene,
  36485. /**
  36486. * Defines the minimum value on X axis
  36487. */
  36488. xmin,
  36489. /**
  36490. * Defines the minimum value on Z axis
  36491. */
  36492. zmin,
  36493. /**
  36494. * Defines the maximum value on X axis
  36495. */
  36496. xmax,
  36497. /**
  36498. * Defines the maximum value on Z axis
  36499. */
  36500. zmax,
  36501. /**
  36502. * Defines the subdivisions to apply to the ground
  36503. */
  36504. subdivisions,
  36505. /**
  36506. * Defines the precision to use when computing the tiles
  36507. */
  36508. precision, canBeRegenerated, mesh) {
  36509. if (mesh === void 0) { mesh = null; }
  36510. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36511. _this.xmin = xmin;
  36512. _this.zmin = zmin;
  36513. _this.xmax = xmax;
  36514. _this.zmax = zmax;
  36515. _this.subdivisions = subdivisions;
  36516. _this.precision = precision;
  36517. return _this;
  36518. }
  36519. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36520. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36521. };
  36522. TiledGroundGeometry.prototype.copy = function (id) {
  36523. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36524. };
  36525. return TiledGroundGeometry;
  36526. }(_PrimitiveGeometry));
  36527. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36528. /**
  36529. * Creates a plane geometry
  36530. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36531. */
  36532. var PlaneGeometry = /** @class */ (function (_super) {
  36533. __extends(PlaneGeometry, _super);
  36534. /**
  36535. * Creates a plane geometry
  36536. * @param id defines the unique ID of the geometry
  36537. * @param scene defines the hosting scene
  36538. * @param size defines the size of the plane (width === height)
  36539. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36540. * @param mesh defines the hosting mesh (can be null)
  36541. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36542. */
  36543. function PlaneGeometry(id, scene,
  36544. /**
  36545. * Defines the size of the plane (width === height)
  36546. */
  36547. size, canBeRegenerated, mesh,
  36548. /**
  36549. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36550. */
  36551. side) {
  36552. if (mesh === void 0) { mesh = null; }
  36553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36555. _this.size = size;
  36556. _this.side = side;
  36557. return _this;
  36558. }
  36559. PlaneGeometry.prototype._regenerateVertexData = function () {
  36560. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36561. };
  36562. PlaneGeometry.prototype.copy = function (id) {
  36563. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36564. };
  36565. PlaneGeometry.prototype.serialize = function () {
  36566. var serializationObject = _super.prototype.serialize.call(this);
  36567. serializationObject.size = this.size;
  36568. return serializationObject;
  36569. };
  36570. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36571. if (scene.getGeometryByID(parsedPlane.id)) {
  36572. return null; // null since geometry could be something else than a ground...
  36573. }
  36574. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36575. if (BABYLON.Tags) {
  36576. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36577. }
  36578. scene.pushGeometry(plane, true);
  36579. return plane;
  36580. };
  36581. return PlaneGeometry;
  36582. }(_PrimitiveGeometry));
  36583. BABYLON.PlaneGeometry = PlaneGeometry;
  36584. /**
  36585. * Creates a torus knot geometry
  36586. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36587. */
  36588. var TorusKnotGeometry = /** @class */ (function (_super) {
  36589. __extends(TorusKnotGeometry, _super);
  36590. /**
  36591. * Creates a torus knot geometry
  36592. * @param id defines the unique ID of the geometry
  36593. * @param scene defines the hosting scene
  36594. * @param radius defines the radius of the torus knot
  36595. * @param tube defines the thickness of the torus knot tube
  36596. * @param radialSegments defines the number of radial segments
  36597. * @param tubularSegments defines the number of tubular segments
  36598. * @param p defines the first number of windings
  36599. * @param q defines the second number of windings
  36600. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36601. * @param mesh defines the hosting mesh (can be null)
  36602. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36603. */
  36604. function TorusKnotGeometry(id, scene,
  36605. /**
  36606. * Defines the radius of the torus knot
  36607. */
  36608. radius,
  36609. /**
  36610. * Defines the thickness of the torus knot tube
  36611. */
  36612. tube,
  36613. /**
  36614. * Defines the number of radial segments
  36615. */
  36616. radialSegments,
  36617. /**
  36618. * Defines the number of tubular segments
  36619. */
  36620. tubularSegments,
  36621. /**
  36622. * Defines the first number of windings
  36623. */
  36624. p,
  36625. /**
  36626. * Defines the second number of windings
  36627. */
  36628. q, canBeRegenerated, mesh,
  36629. /**
  36630. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36631. */
  36632. side) {
  36633. if (mesh === void 0) { mesh = null; }
  36634. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36635. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36636. _this.radius = radius;
  36637. _this.tube = tube;
  36638. _this.radialSegments = radialSegments;
  36639. _this.tubularSegments = tubularSegments;
  36640. _this.p = p;
  36641. _this.q = q;
  36642. _this.side = side;
  36643. return _this;
  36644. }
  36645. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36646. 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 });
  36647. };
  36648. TorusKnotGeometry.prototype.copy = function (id) {
  36649. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36650. };
  36651. TorusKnotGeometry.prototype.serialize = function () {
  36652. var serializationObject = _super.prototype.serialize.call(this);
  36653. serializationObject.radius = this.radius;
  36654. serializationObject.tube = this.tube;
  36655. serializationObject.radialSegments = this.radialSegments;
  36656. serializationObject.tubularSegments = this.tubularSegments;
  36657. serializationObject.p = this.p;
  36658. serializationObject.q = this.q;
  36659. return serializationObject;
  36660. };
  36661. ;
  36662. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36663. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36664. return null; // null since geometry could be something else than a ground...
  36665. }
  36666. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36667. if (BABYLON.Tags) {
  36668. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36669. }
  36670. scene.pushGeometry(torusKnot, true);
  36671. return torusKnot;
  36672. };
  36673. return TorusKnotGeometry;
  36674. }(_PrimitiveGeometry));
  36675. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36676. //}
  36677. })(BABYLON || (BABYLON = {}));
  36678. //# sourceMappingURL=babylon.geometry.js.map
  36679. var BABYLON;
  36680. (function (BABYLON) {
  36681. /**
  36682. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36683. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36684. */
  36685. var PostProcessManager = /** @class */ (function () {
  36686. /**
  36687. * Creates a new instance of @see PostProcess
  36688. * @param scene The scene that the post process is associated with.
  36689. */
  36690. function PostProcessManager(scene) {
  36691. this._vertexBuffers = {};
  36692. this._scene = scene;
  36693. }
  36694. PostProcessManager.prototype._prepareBuffers = function () {
  36695. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36696. return;
  36697. }
  36698. // VBO
  36699. var vertices = [];
  36700. vertices.push(1, 1);
  36701. vertices.push(-1, 1);
  36702. vertices.push(-1, -1);
  36703. vertices.push(1, -1);
  36704. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36705. this._buildIndexBuffer();
  36706. };
  36707. PostProcessManager.prototype._buildIndexBuffer = function () {
  36708. // Indices
  36709. var indices = [];
  36710. indices.push(0);
  36711. indices.push(1);
  36712. indices.push(2);
  36713. indices.push(0);
  36714. indices.push(2);
  36715. indices.push(3);
  36716. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36717. };
  36718. /**
  36719. * Rebuilds the vertex buffers of the manager.
  36720. */
  36721. PostProcessManager.prototype._rebuild = function () {
  36722. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36723. if (!vb) {
  36724. return;
  36725. }
  36726. vb._rebuild();
  36727. this._buildIndexBuffer();
  36728. };
  36729. // Methods
  36730. /**
  36731. * Prepares a frame to be run through a post process.
  36732. * @param sourceTexture The input texture to the post procesess. (default: null)
  36733. * @param postProcesses An array of post processes to be run. (default: null)
  36734. * @returns True if the post processes were able to be run.
  36735. */
  36736. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36737. if (sourceTexture === void 0) { sourceTexture = null; }
  36738. if (postProcesses === void 0) { postProcesses = null; }
  36739. var camera = this._scene.activeCamera;
  36740. if (!camera) {
  36741. return false;
  36742. }
  36743. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36744. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36745. return false;
  36746. }
  36747. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36748. return true;
  36749. };
  36750. /**
  36751. * Manually render a set of post processes to a texture.
  36752. * @param postProcesses An array of post processes to be run.
  36753. * @param targetTexture The target texture to render to.
  36754. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36755. */
  36756. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36757. if (targetTexture === void 0) { targetTexture = null; }
  36758. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36759. var engine = this._scene.getEngine();
  36760. for (var index = 0; index < postProcesses.length; index++) {
  36761. if (index < postProcesses.length - 1) {
  36762. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36763. }
  36764. else {
  36765. if (targetTexture) {
  36766. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36767. }
  36768. else {
  36769. engine.restoreDefaultFramebuffer();
  36770. }
  36771. }
  36772. var pp = postProcesses[index];
  36773. var effect = pp.apply();
  36774. if (effect) {
  36775. pp.onBeforeRenderObservable.notifyObservers(effect);
  36776. // VBOs
  36777. this._prepareBuffers();
  36778. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36779. // Draw order
  36780. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36781. pp.onAfterRenderObservable.notifyObservers(effect);
  36782. }
  36783. }
  36784. // Restore depth buffer
  36785. engine.setDepthBuffer(true);
  36786. engine.setDepthWrite(true);
  36787. };
  36788. /**
  36789. * Finalize the result of the output of the postprocesses.
  36790. * @param doNotPresent If true the result will not be displayed to the screen.
  36791. * @param targetTexture The target texture to render to.
  36792. * @param faceIndex The index of the face to bind the target texture to.
  36793. * @param postProcesses The array of post processes to render.
  36794. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36795. */
  36796. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36797. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36798. var camera = this._scene.activeCamera;
  36799. if (!camera) {
  36800. return;
  36801. }
  36802. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36803. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36804. return;
  36805. }
  36806. var engine = this._scene.getEngine();
  36807. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36808. if (index < len - 1) {
  36809. postProcesses[index + 1].activate(camera, targetTexture);
  36810. }
  36811. else {
  36812. if (targetTexture) {
  36813. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36814. }
  36815. else {
  36816. engine.restoreDefaultFramebuffer();
  36817. }
  36818. }
  36819. if (doNotPresent) {
  36820. break;
  36821. }
  36822. var pp = postProcesses[index];
  36823. var effect = pp.apply();
  36824. if (effect) {
  36825. pp.onBeforeRenderObservable.notifyObservers(effect);
  36826. // VBOs
  36827. this._prepareBuffers();
  36828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36829. // Draw order
  36830. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36831. pp.onAfterRenderObservable.notifyObservers(effect);
  36832. }
  36833. }
  36834. // Restore states
  36835. engine.setDepthBuffer(true);
  36836. engine.setDepthWrite(true);
  36837. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36838. };
  36839. /**
  36840. * Disposes of the post process manager.
  36841. */
  36842. PostProcessManager.prototype.dispose = function () {
  36843. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36844. if (buffer) {
  36845. buffer.dispose();
  36846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36847. }
  36848. if (this._indexBuffer) {
  36849. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36850. this._indexBuffer = null;
  36851. }
  36852. };
  36853. return PostProcessManager;
  36854. }());
  36855. BABYLON.PostProcessManager = PostProcessManager;
  36856. })(BABYLON || (BABYLON = {}));
  36857. //# sourceMappingURL=babylon.postProcessManager.js.map
  36858. var BABYLON;
  36859. (function (BABYLON) {
  36860. /**
  36861. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36862. */
  36863. var PerformanceMonitor = /** @class */ (function () {
  36864. /**
  36865. * constructor
  36866. * @param frameSampleSize The number of samples required to saturate the sliding window
  36867. */
  36868. function PerformanceMonitor(frameSampleSize) {
  36869. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36870. this._enabled = true;
  36871. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36872. }
  36873. /**
  36874. * Samples current frame
  36875. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36876. */
  36877. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36878. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36879. if (!this._enabled)
  36880. return;
  36881. if (this._lastFrameTimeMs != null) {
  36882. var dt = timeMs - this._lastFrameTimeMs;
  36883. this._rollingFrameTime.add(dt);
  36884. }
  36885. this._lastFrameTimeMs = timeMs;
  36886. };
  36887. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36888. /**
  36889. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36890. * @return Average frame time in milliseconds
  36891. */
  36892. get: function () {
  36893. return this._rollingFrameTime.average;
  36894. },
  36895. enumerable: true,
  36896. configurable: true
  36897. });
  36898. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36899. /**
  36900. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36901. * @return Frame time variance in milliseconds squared
  36902. */
  36903. get: function () {
  36904. return this._rollingFrameTime.variance;
  36905. },
  36906. enumerable: true,
  36907. configurable: true
  36908. });
  36909. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36910. /**
  36911. * Returns the frame time of the most recent frame
  36912. * @return Frame time in milliseconds
  36913. */
  36914. get: function () {
  36915. return this._rollingFrameTime.history(0);
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36921. /**
  36922. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36923. * @return Framerate in frames per second
  36924. */
  36925. get: function () {
  36926. return 1000.0 / this._rollingFrameTime.average;
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36932. /**
  36933. * Returns the average framerate in frames per second using the most recent frame time
  36934. * @return Framerate in frames per second
  36935. */
  36936. get: function () {
  36937. var history = this._rollingFrameTime.history(0);
  36938. if (history === 0) {
  36939. return 0;
  36940. }
  36941. return 1000.0 / history;
  36942. },
  36943. enumerable: true,
  36944. configurable: true
  36945. });
  36946. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36947. /**
  36948. * Returns true if enough samples have been taken to completely fill the sliding window
  36949. * @return true if saturated
  36950. */
  36951. get: function () {
  36952. return this._rollingFrameTime.isSaturated();
  36953. },
  36954. enumerable: true,
  36955. configurable: true
  36956. });
  36957. /**
  36958. * Enables contributions to the sliding window sample set
  36959. */
  36960. PerformanceMonitor.prototype.enable = function () {
  36961. this._enabled = true;
  36962. };
  36963. /**
  36964. * Disables contributions to the sliding window sample set
  36965. * Samples will not be interpolated over the disabled period
  36966. */
  36967. PerformanceMonitor.prototype.disable = function () {
  36968. this._enabled = false;
  36969. //clear last sample to avoid interpolating over the disabled period when next enabled
  36970. this._lastFrameTimeMs = null;
  36971. };
  36972. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36973. /**
  36974. * Returns true if sampling is enabled
  36975. * @return true if enabled
  36976. */
  36977. get: function () {
  36978. return this._enabled;
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. /**
  36984. * Resets performance monitor
  36985. */
  36986. PerformanceMonitor.prototype.reset = function () {
  36987. //clear last sample to avoid interpolating over the disabled period when next enabled
  36988. this._lastFrameTimeMs = null;
  36989. //wipe record
  36990. this._rollingFrameTime.reset();
  36991. };
  36992. return PerformanceMonitor;
  36993. }());
  36994. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36995. /**
  36996. * RollingAverage
  36997. *
  36998. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36999. */
  37000. var RollingAverage = /** @class */ (function () {
  37001. /**
  37002. * constructor
  37003. * @param length The number of samples required to saturate the sliding window
  37004. */
  37005. function RollingAverage(length) {
  37006. this._samples = new Array(length);
  37007. this.reset();
  37008. }
  37009. /**
  37010. * Adds a sample to the sample set
  37011. * @param v The sample value
  37012. */
  37013. RollingAverage.prototype.add = function (v) {
  37014. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37015. var delta;
  37016. //we need to check if we've already wrapped round
  37017. if (this.isSaturated()) {
  37018. //remove bottom of stack from mean
  37019. var bottomValue = this._samples[this._pos];
  37020. delta = bottomValue - this.average;
  37021. this.average -= delta / (this._sampleCount - 1);
  37022. this._m2 -= delta * (bottomValue - this.average);
  37023. }
  37024. else {
  37025. this._sampleCount++;
  37026. }
  37027. //add new value to mean
  37028. delta = v - this.average;
  37029. this.average += delta / (this._sampleCount);
  37030. this._m2 += delta * (v - this.average);
  37031. //set the new variance
  37032. this.variance = this._m2 / (this._sampleCount - 1);
  37033. this._samples[this._pos] = v;
  37034. this._pos++;
  37035. this._pos %= this._samples.length; //positive wrap around
  37036. };
  37037. /**
  37038. * Returns previously added values or null if outside of history or outside the sliding window domain
  37039. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37040. * @return Value previously recorded with add() or null if outside of range
  37041. */
  37042. RollingAverage.prototype.history = function (i) {
  37043. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37044. return 0;
  37045. }
  37046. var i0 = this._wrapPosition(this._pos - 1.0);
  37047. return this._samples[this._wrapPosition(i0 - i)];
  37048. };
  37049. /**
  37050. * Returns true if enough samples have been taken to completely fill the sliding window
  37051. * @return true if sample-set saturated
  37052. */
  37053. RollingAverage.prototype.isSaturated = function () {
  37054. return this._sampleCount >= this._samples.length;
  37055. };
  37056. /**
  37057. * Resets the rolling average (equivalent to 0 samples taken so far)
  37058. */
  37059. RollingAverage.prototype.reset = function () {
  37060. this.average = 0;
  37061. this.variance = 0;
  37062. this._sampleCount = 0;
  37063. this._pos = 0;
  37064. this._m2 = 0;
  37065. };
  37066. /**
  37067. * Wraps a value around the sample range boundaries
  37068. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37069. * @return Wrapped position in sample range
  37070. */
  37071. RollingAverage.prototype._wrapPosition = function (i) {
  37072. var max = this._samples.length;
  37073. return ((i % max) + max) % max;
  37074. };
  37075. return RollingAverage;
  37076. }());
  37077. BABYLON.RollingAverage = RollingAverage;
  37078. })(BABYLON || (BABYLON = {}));
  37079. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37080. var BABYLON;
  37081. (function (BABYLON) {
  37082. /**
  37083. * This groups together the common properties used for image processing either in direct forward pass
  37084. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37085. * or not.
  37086. */
  37087. var ImageProcessingConfiguration = /** @class */ (function () {
  37088. function ImageProcessingConfiguration() {
  37089. /**
  37090. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37091. */
  37092. this.colorCurves = new BABYLON.ColorCurves();
  37093. this._colorCurvesEnabled = false;
  37094. this._colorGradingEnabled = false;
  37095. this._colorGradingWithGreenDepth = true;
  37096. this._colorGradingBGR = true;
  37097. this._exposure = 1.0;
  37098. this._toneMappingEnabled = false;
  37099. this._contrast = 1.0;
  37100. /**
  37101. * Vignette stretch size.
  37102. */
  37103. this.vignetteStretch = 0;
  37104. /**
  37105. * Vignette centre X Offset.
  37106. */
  37107. this.vignetteCentreX = 0;
  37108. /**
  37109. * Vignette centre Y Offset.
  37110. */
  37111. this.vignetteCentreY = 0;
  37112. /**
  37113. * Vignette weight or intensity of the vignette effect.
  37114. */
  37115. this.vignetteWeight = 1.5;
  37116. /**
  37117. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37118. * if vignetteEnabled is set to true.
  37119. */
  37120. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37121. /**
  37122. * Camera field of view used by the Vignette effect.
  37123. */
  37124. this.vignetteCameraFov = 0.5;
  37125. this._grainEnabled = false;
  37126. this._grainIntensity = 30;
  37127. this._grainAnimated = false;
  37128. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37129. this._vignetteEnabled = false;
  37130. this._applyByPostProcess = false;
  37131. this._isEnabled = true;
  37132. /**
  37133. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37134. * @type {BABYLON.Observable}
  37135. */
  37136. this.onUpdateParameters = new BABYLON.Observable();
  37137. }
  37138. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37139. /**
  37140. * Gets wether the color curves effect is enabled.
  37141. */
  37142. get: function () {
  37143. return this._colorCurvesEnabled;
  37144. },
  37145. /**
  37146. * Sets wether the color curves effect is enabled.
  37147. */
  37148. set: function (value) {
  37149. if (this._colorCurvesEnabled === value) {
  37150. return;
  37151. }
  37152. this._colorCurvesEnabled = value;
  37153. this._updateParameters();
  37154. },
  37155. enumerable: true,
  37156. configurable: true
  37157. });
  37158. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37159. /**
  37160. * Gets wether the color grading effect is enabled.
  37161. */
  37162. get: function () {
  37163. return this._colorGradingEnabled;
  37164. },
  37165. /**
  37166. * Sets wether the color grading effect is enabled.
  37167. */
  37168. set: function (value) {
  37169. if (this._colorGradingEnabled === value) {
  37170. return;
  37171. }
  37172. this._colorGradingEnabled = value;
  37173. this._updateParameters();
  37174. },
  37175. enumerable: true,
  37176. configurable: true
  37177. });
  37178. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37179. /**
  37180. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37181. */
  37182. get: function () {
  37183. return this._colorGradingWithGreenDepth;
  37184. },
  37185. /**
  37186. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37187. */
  37188. set: function (value) {
  37189. if (this._colorGradingWithGreenDepth === value) {
  37190. return;
  37191. }
  37192. this._colorGradingWithGreenDepth = value;
  37193. this._updateParameters();
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37199. /**
  37200. * Gets wether the color grading texture contains BGR values.
  37201. */
  37202. get: function () {
  37203. return this._colorGradingBGR;
  37204. },
  37205. /**
  37206. * Sets wether the color grading texture contains BGR values.
  37207. */
  37208. set: function (value) {
  37209. if (this._colorGradingBGR === value) {
  37210. return;
  37211. }
  37212. this._colorGradingBGR = value;
  37213. this._updateParameters();
  37214. },
  37215. enumerable: true,
  37216. configurable: true
  37217. });
  37218. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37219. /**
  37220. * Gets the Exposure used in the effect.
  37221. */
  37222. get: function () {
  37223. return this._exposure;
  37224. },
  37225. /**
  37226. * Sets the Exposure used in the effect.
  37227. */
  37228. set: function (value) {
  37229. if (this._exposure === value) {
  37230. return;
  37231. }
  37232. this._exposure = value;
  37233. this._updateParameters();
  37234. },
  37235. enumerable: true,
  37236. configurable: true
  37237. });
  37238. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37239. /**
  37240. * Gets wether the tone mapping effect is enabled.
  37241. */
  37242. get: function () {
  37243. return this._toneMappingEnabled;
  37244. },
  37245. /**
  37246. * Sets wether the tone mapping effect is enabled.
  37247. */
  37248. set: function (value) {
  37249. if (this._toneMappingEnabled === value) {
  37250. return;
  37251. }
  37252. this._toneMappingEnabled = value;
  37253. this._updateParameters();
  37254. },
  37255. enumerable: true,
  37256. configurable: true
  37257. });
  37258. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37259. /**
  37260. * Gets the contrast used in the effect.
  37261. */
  37262. get: function () {
  37263. return this._contrast;
  37264. },
  37265. /**
  37266. * Sets the contrast used in the effect.
  37267. */
  37268. set: function (value) {
  37269. if (this._contrast === value) {
  37270. return;
  37271. }
  37272. this._contrast = value;
  37273. this._updateParameters();
  37274. },
  37275. enumerable: true,
  37276. configurable: true
  37277. });
  37278. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37279. /**
  37280. * If the grain effect should be enabled.
  37281. */
  37282. get: function () {
  37283. return this._grainEnabled;
  37284. },
  37285. set: function (value) {
  37286. if (this._grainEnabled === value) {
  37287. return;
  37288. }
  37289. this._grainEnabled = value;
  37290. this._updateParameters();
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37296. /**
  37297. * Amount of grain to be applied by the grain effect.
  37298. */
  37299. get: function () {
  37300. return this._grainIntensity;
  37301. },
  37302. set: function (value) {
  37303. if (this._grainIntensity === value) {
  37304. return;
  37305. }
  37306. this._grainIntensity = value;
  37307. },
  37308. enumerable: true,
  37309. configurable: true
  37310. });
  37311. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37312. /**
  37313. * If the grain effect should be animated.
  37314. */
  37315. get: function () {
  37316. return this._grainAnimated;
  37317. },
  37318. set: function (value) {
  37319. if (this._grainAnimated === value) {
  37320. return;
  37321. }
  37322. this._grainAnimated = value;
  37323. this._updateParameters();
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37329. /**
  37330. * Gets the vignette blend mode allowing different kind of effect.
  37331. */
  37332. get: function () {
  37333. return this._vignetteBlendMode;
  37334. },
  37335. /**
  37336. * Sets the vignette blend mode allowing different kind of effect.
  37337. */
  37338. set: function (value) {
  37339. if (this._vignetteBlendMode === value) {
  37340. return;
  37341. }
  37342. this._vignetteBlendMode = value;
  37343. this._updateParameters();
  37344. },
  37345. enumerable: true,
  37346. configurable: true
  37347. });
  37348. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37349. /**
  37350. * Gets wether the vignette effect is enabled.
  37351. */
  37352. get: function () {
  37353. return this._vignetteEnabled;
  37354. },
  37355. /**
  37356. * Sets wether the vignette effect is enabled.
  37357. */
  37358. set: function (value) {
  37359. if (this._vignetteEnabled === value) {
  37360. return;
  37361. }
  37362. this._vignetteEnabled = value;
  37363. this._updateParameters();
  37364. },
  37365. enumerable: true,
  37366. configurable: true
  37367. });
  37368. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37369. /**
  37370. * Gets wether the image processing is applied through a post process or not.
  37371. */
  37372. get: function () {
  37373. return this._applyByPostProcess;
  37374. },
  37375. /**
  37376. * Sets wether the image processing is applied through a post process or not.
  37377. */
  37378. set: function (value) {
  37379. if (this._applyByPostProcess === value) {
  37380. return;
  37381. }
  37382. this._applyByPostProcess = value;
  37383. this._updateParameters();
  37384. },
  37385. enumerable: true,
  37386. configurable: true
  37387. });
  37388. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37389. /**
  37390. * Gets wether the image processing is enabled or not.
  37391. */
  37392. get: function () {
  37393. return this._isEnabled;
  37394. },
  37395. /**
  37396. * Sets wether the image processing is enabled or not.
  37397. */
  37398. set: function (value) {
  37399. if (this._isEnabled === value) {
  37400. return;
  37401. }
  37402. this._isEnabled = value;
  37403. this._updateParameters();
  37404. },
  37405. enumerable: true,
  37406. configurable: true
  37407. });
  37408. /**
  37409. * Method called each time the image processing information changes requires to recompile the effect.
  37410. */
  37411. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37412. this.onUpdateParameters.notifyObservers(this);
  37413. };
  37414. ImageProcessingConfiguration.prototype.getClassName = function () {
  37415. return "ImageProcessingConfiguration";
  37416. };
  37417. /**
  37418. * Prepare the list of uniforms associated with the Image Processing effects.
  37419. * @param uniformsList The list of uniforms used in the effect
  37420. * @param defines the list of defines currently in use
  37421. */
  37422. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37423. if (defines.EXPOSURE) {
  37424. uniforms.push("exposureLinear");
  37425. }
  37426. if (defines.CONTRAST) {
  37427. uniforms.push("contrast");
  37428. }
  37429. if (defines.COLORGRADING) {
  37430. uniforms.push("colorTransformSettings");
  37431. }
  37432. if (defines.VIGNETTE) {
  37433. uniforms.push("vInverseScreenSize");
  37434. uniforms.push("vignetteSettings1");
  37435. uniforms.push("vignetteSettings2");
  37436. }
  37437. if (defines.COLORCURVES) {
  37438. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37439. }
  37440. if (defines.GRAIN) {
  37441. uniforms.push("grainVarianceAmount");
  37442. uniforms.push("grainAnimatedSeed");
  37443. }
  37444. };
  37445. /**
  37446. * Prepare the list of samplers associated with the Image Processing effects.
  37447. * @param uniformsList The list of uniforms used in the effect
  37448. * @param defines the list of defines currently in use
  37449. */
  37450. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37451. if (defines.COLORGRADING) {
  37452. samplersList.push("txColorTransform");
  37453. }
  37454. };
  37455. /**
  37456. * Prepare the list of defines associated to the shader.
  37457. * @param defines the list of defines to complete
  37458. */
  37459. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37460. if (forPostProcess === void 0) { forPostProcess = false; }
  37461. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37462. defines.VIGNETTE = false;
  37463. defines.TONEMAPPING = false;
  37464. defines.CONTRAST = false;
  37465. defines.EXPOSURE = false;
  37466. defines.COLORCURVES = false;
  37467. defines.COLORGRADING = false;
  37468. defines.COLORGRADING3D = false;
  37469. defines.IMAGEPROCESSING = false;
  37470. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37471. return;
  37472. }
  37473. defines.VIGNETTE = this.vignetteEnabled;
  37474. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37475. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37476. defines.TONEMAPPING = this.toneMappingEnabled;
  37477. defines.CONTRAST = (this.contrast !== 1.0);
  37478. defines.EXPOSURE = (this.exposure !== 1.0);
  37479. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37480. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37481. if (defines.COLORGRADING) {
  37482. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37483. }
  37484. else {
  37485. defines.COLORGRADING3D = false;
  37486. }
  37487. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37488. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37489. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37490. defines.GRAIN = this.grainEnabled;
  37491. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37492. };
  37493. /**
  37494. * Returns true if all the image processing information are ready.
  37495. */
  37496. ImageProcessingConfiguration.prototype.isReady = function () {
  37497. // Color Grading texure can not be none blocking.
  37498. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37499. };
  37500. /**
  37501. * Binds the image processing to the shader.
  37502. * @param effect The effect to bind to
  37503. */
  37504. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37505. if (aspectRatio === void 0) { aspectRatio = 1; }
  37506. // Color Curves
  37507. if (this._colorCurvesEnabled && this.colorCurves) {
  37508. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37509. }
  37510. // Vignette
  37511. if (this._vignetteEnabled) {
  37512. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37513. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37514. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37515. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37516. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37517. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37518. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37519. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37520. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37521. var vignettePower = -2.0 * this.vignetteWeight;
  37522. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37523. }
  37524. // Exposure
  37525. effect.setFloat("exposureLinear", this.exposure);
  37526. // Contrast
  37527. effect.setFloat("contrast", this.contrast);
  37528. // Color transform settings
  37529. if (this.colorGradingTexture) {
  37530. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37531. var textureSize = this.colorGradingTexture.getSize().height;
  37532. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37533. 0.5 / textureSize, // textureOffset
  37534. textureSize, // textureSize
  37535. this.colorGradingTexture.level // weight
  37536. );
  37537. }
  37538. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37539. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37540. };
  37541. /**
  37542. * Clones the current image processing instance.
  37543. * @return The cloned image processing
  37544. */
  37545. ImageProcessingConfiguration.prototype.clone = function () {
  37546. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37547. };
  37548. /**
  37549. * Serializes the current image processing instance to a json representation.
  37550. * @return a JSON representation
  37551. */
  37552. ImageProcessingConfiguration.prototype.serialize = function () {
  37553. return BABYLON.SerializationHelper.Serialize(this);
  37554. };
  37555. /**
  37556. * Parses the image processing from a json representation.
  37557. * @param source the JSON source to parse
  37558. * @return The parsed image processing
  37559. */
  37560. ImageProcessingConfiguration.Parse = function (source) {
  37561. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37562. };
  37563. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37564. /**
  37565. * Used to apply the vignette as a mix with the pixel color.
  37566. */
  37567. get: function () {
  37568. return this._VIGNETTEMODE_MULTIPLY;
  37569. },
  37570. enumerable: true,
  37571. configurable: true
  37572. });
  37573. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37574. /**
  37575. * Used to apply the vignette as a replacement of the pixel color.
  37576. */
  37577. get: function () {
  37578. return this._VIGNETTEMODE_OPAQUE;
  37579. },
  37580. enumerable: true,
  37581. configurable: true
  37582. });
  37583. // Static constants associated to the image processing.
  37584. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37585. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37586. __decorate([
  37587. BABYLON.serializeAsColorCurves()
  37588. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37589. __decorate([
  37590. BABYLON.serialize()
  37591. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37592. __decorate([
  37593. BABYLON.serializeAsTexture()
  37594. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37595. __decorate([
  37596. BABYLON.serialize()
  37597. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37598. __decorate([
  37599. BABYLON.serialize()
  37600. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37601. __decorate([
  37602. BABYLON.serialize()
  37603. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37604. __decorate([
  37605. BABYLON.serialize()
  37606. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37607. __decorate([
  37608. BABYLON.serialize()
  37609. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37610. __decorate([
  37611. BABYLON.serialize()
  37612. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37613. __decorate([
  37614. BABYLON.serialize()
  37615. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37616. __decorate([
  37617. BABYLON.serialize()
  37618. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37619. __decorate([
  37620. BABYLON.serialize()
  37621. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37622. __decorate([
  37623. BABYLON.serialize()
  37624. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37625. __decorate([
  37626. BABYLON.serializeAsColor4()
  37627. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37628. __decorate([
  37629. BABYLON.serialize()
  37630. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37631. __decorate([
  37632. BABYLON.serialize()
  37633. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37634. __decorate([
  37635. BABYLON.serialize()
  37636. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37637. __decorate([
  37638. BABYLON.serialize()
  37639. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37640. __decorate([
  37641. BABYLON.serialize()
  37642. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37643. __decorate([
  37644. BABYLON.serialize()
  37645. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37646. __decorate([
  37647. BABYLON.serialize()
  37648. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37649. __decorate([
  37650. BABYLON.serialize()
  37651. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37652. return ImageProcessingConfiguration;
  37653. }());
  37654. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37655. })(BABYLON || (BABYLON = {}));
  37656. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37657. var BABYLON;
  37658. (function (BABYLON) {
  37659. /**
  37660. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37661. * It can help converting any input color in a desired output one. This can then be used to create effects
  37662. * from sepia, black and white to sixties or futuristic rendering...
  37663. *
  37664. * The only supported format is currently 3dl.
  37665. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37666. */
  37667. var ColorGradingTexture = /** @class */ (function (_super) {
  37668. __extends(ColorGradingTexture, _super);
  37669. /**
  37670. * Instantiates a ColorGradingTexture from the following parameters.
  37671. *
  37672. * @param url The location of the color gradind data (currently only supporting 3dl)
  37673. * @param scene The scene the texture will be used in
  37674. */
  37675. function ColorGradingTexture(url, scene) {
  37676. var _this = _super.call(this, scene) || this;
  37677. if (!url) {
  37678. return _this;
  37679. }
  37680. _this._engine = scene.getEngine();
  37681. _this._textureMatrix = BABYLON.Matrix.Identity();
  37682. _this.name = url;
  37683. _this.url = url;
  37684. _this.hasAlpha = false;
  37685. _this.isCube = false;
  37686. _this.is3D = _this._engine.webGLVersion > 1;
  37687. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37688. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37689. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37690. _this.anisotropicFilteringLevel = 1;
  37691. _this._texture = _this._getFromCache(url, true);
  37692. if (!_this._texture) {
  37693. if (!scene.useDelayedTextureLoading) {
  37694. _this.loadTexture();
  37695. }
  37696. else {
  37697. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37698. }
  37699. }
  37700. return _this;
  37701. }
  37702. /**
  37703. * Returns the texture matrix used in most of the material.
  37704. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37705. */
  37706. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37707. return this._textureMatrix;
  37708. };
  37709. /**
  37710. * Occurs when the file being loaded is a .3dl LUT file.
  37711. */
  37712. ColorGradingTexture.prototype.load3dlTexture = function () {
  37713. var engine = this._engine;
  37714. var texture;
  37715. if (engine.webGLVersion === 1) {
  37716. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37717. }
  37718. else {
  37719. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37720. }
  37721. this._texture = texture;
  37722. var callback = function (text) {
  37723. if (typeof text !== "string") {
  37724. return;
  37725. }
  37726. var data = null;
  37727. var tempData = null;
  37728. var line;
  37729. var lines = text.split('\n');
  37730. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37731. var maxColor = 0;
  37732. for (var i = 0; i < lines.length; i++) {
  37733. line = lines[i];
  37734. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37735. continue;
  37736. if (line.indexOf('#') === 0)
  37737. continue;
  37738. var words = line.split(" ");
  37739. if (size === 0) {
  37740. // Number of space + one
  37741. size = words.length;
  37742. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37743. tempData = new Float32Array(size * size * size * 4);
  37744. continue;
  37745. }
  37746. if (size != 0) {
  37747. var r = Math.max(parseInt(words[0]), 0);
  37748. var g = Math.max(parseInt(words[1]), 0);
  37749. var b = Math.max(parseInt(words[2]), 0);
  37750. maxColor = Math.max(r, maxColor);
  37751. maxColor = Math.max(g, maxColor);
  37752. maxColor = Math.max(b, maxColor);
  37753. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37754. if (tempData) {
  37755. tempData[pixelStorageIndex + 0] = r;
  37756. tempData[pixelStorageIndex + 1] = g;
  37757. tempData[pixelStorageIndex + 2] = b;
  37758. }
  37759. pixelIndexSlice++;
  37760. if (pixelIndexSlice % size == 0) {
  37761. pixelIndexH++;
  37762. pixelIndexSlice = 0;
  37763. if (pixelIndexH % size == 0) {
  37764. pixelIndexW++;
  37765. pixelIndexH = 0;
  37766. }
  37767. }
  37768. }
  37769. }
  37770. if (tempData && data) {
  37771. for (var i = 0; i < tempData.length; i++) {
  37772. if (i > 0 && (i + 1) % 4 === 0) {
  37773. data[i] = 255;
  37774. }
  37775. else {
  37776. var value = tempData[i];
  37777. data[i] = (value / maxColor * 255);
  37778. }
  37779. }
  37780. }
  37781. if (texture.is3D) {
  37782. texture.updateSize(size, size, size);
  37783. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37784. }
  37785. else {
  37786. texture.updateSize(size * size, size);
  37787. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37788. }
  37789. };
  37790. var scene = this.getScene();
  37791. if (scene) {
  37792. scene._loadFile(this.url, callback);
  37793. }
  37794. else {
  37795. this._engine._loadFile(this.url, callback);
  37796. }
  37797. return this._texture;
  37798. };
  37799. /**
  37800. * Starts the loading process of the texture.
  37801. */
  37802. ColorGradingTexture.prototype.loadTexture = function () {
  37803. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37804. this.load3dlTexture();
  37805. }
  37806. };
  37807. /**
  37808. * Clones the color gradind texture.
  37809. */
  37810. ColorGradingTexture.prototype.clone = function () {
  37811. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37812. // Base texture
  37813. newTexture.level = this.level;
  37814. return newTexture;
  37815. };
  37816. /**
  37817. * Called during delayed load for textures.
  37818. */
  37819. ColorGradingTexture.prototype.delayLoad = function () {
  37820. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37821. return;
  37822. }
  37823. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37824. this._texture = this._getFromCache(this.url, true);
  37825. if (!this._texture) {
  37826. this.loadTexture();
  37827. }
  37828. };
  37829. /**
  37830. * Parses a color grading texture serialized by Babylon.
  37831. * @param parsedTexture The texture information being parsedTexture
  37832. * @param scene The scene to load the texture in
  37833. * @param rootUrl The root url of the data assets to load
  37834. * @return A color gradind texture
  37835. */
  37836. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37837. var texture = null;
  37838. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37839. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37840. texture.name = parsedTexture.name;
  37841. texture.level = parsedTexture.level;
  37842. }
  37843. return texture;
  37844. };
  37845. /**
  37846. * Serializes the LUT texture to json format.
  37847. */
  37848. ColorGradingTexture.prototype.serialize = function () {
  37849. if (!this.name) {
  37850. return null;
  37851. }
  37852. var serializationObject = {};
  37853. serializationObject.name = this.name;
  37854. serializationObject.level = this.level;
  37855. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37856. return serializationObject;
  37857. };
  37858. /**
  37859. * Empty line regex stored for GC.
  37860. */
  37861. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37862. return ColorGradingTexture;
  37863. }(BABYLON.BaseTexture));
  37864. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37865. })(BABYLON || (BABYLON = {}));
  37866. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37867. var BABYLON;
  37868. (function (BABYLON) {
  37869. /**
  37870. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37871. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37872. * 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;
  37873. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37874. */
  37875. var ColorCurves = /** @class */ (function () {
  37876. function ColorCurves() {
  37877. this._dirty = true;
  37878. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37879. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37880. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37881. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37882. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37883. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37884. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37885. this._globalHue = 30;
  37886. this._globalDensity = 0;
  37887. this._globalSaturation = 0;
  37888. this._globalExposure = 0;
  37889. this._highlightsHue = 30;
  37890. this._highlightsDensity = 0;
  37891. this._highlightsSaturation = 0;
  37892. this._highlightsExposure = 0;
  37893. this._midtonesHue = 30;
  37894. this._midtonesDensity = 0;
  37895. this._midtonesSaturation = 0;
  37896. this._midtonesExposure = 0;
  37897. this._shadowsHue = 30;
  37898. this._shadowsDensity = 0;
  37899. this._shadowsSaturation = 0;
  37900. this._shadowsExposure = 0;
  37901. }
  37902. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37903. /**
  37904. * Gets the global Hue value.
  37905. * 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).
  37906. */
  37907. get: function () {
  37908. return this._globalHue;
  37909. },
  37910. /**
  37911. * Sets the global Hue value.
  37912. * 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).
  37913. */
  37914. set: function (value) {
  37915. this._globalHue = value;
  37916. this._dirty = true;
  37917. },
  37918. enumerable: true,
  37919. configurable: true
  37920. });
  37921. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37922. /**
  37923. * Gets the global Density value.
  37924. * 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.
  37925. * Values less than zero provide a filter of opposite hue.
  37926. */
  37927. get: function () {
  37928. return this._globalDensity;
  37929. },
  37930. /**
  37931. * Sets the global Density value.
  37932. * 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.
  37933. * Values less than zero provide a filter of opposite hue.
  37934. */
  37935. set: function (value) {
  37936. this._globalDensity = value;
  37937. this._dirty = true;
  37938. },
  37939. enumerable: true,
  37940. configurable: true
  37941. });
  37942. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37943. /**
  37944. * Gets the global Saturation value.
  37945. * 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.
  37946. */
  37947. get: function () {
  37948. return this._globalSaturation;
  37949. },
  37950. /**
  37951. * Sets the global Saturation value.
  37952. * 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.
  37953. */
  37954. set: function (value) {
  37955. this._globalSaturation = value;
  37956. this._dirty = true;
  37957. },
  37958. enumerable: true,
  37959. configurable: true
  37960. });
  37961. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37962. /**
  37963. * Gets the highlights Hue value.
  37964. * 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).
  37965. */
  37966. get: function () {
  37967. return this._highlightsHue;
  37968. },
  37969. /**
  37970. * Sets the highlights Hue value.
  37971. * 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).
  37972. */
  37973. set: function (value) {
  37974. this._highlightsHue = value;
  37975. this._dirty = true;
  37976. },
  37977. enumerable: true,
  37978. configurable: true
  37979. });
  37980. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37981. /**
  37982. * Gets the highlights Density value.
  37983. * 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.
  37984. * Values less than zero provide a filter of opposite hue.
  37985. */
  37986. get: function () {
  37987. return this._highlightsDensity;
  37988. },
  37989. /**
  37990. * Sets the highlights Density value.
  37991. * 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.
  37992. * Values less than zero provide a filter of opposite hue.
  37993. */
  37994. set: function (value) {
  37995. this._highlightsDensity = value;
  37996. this._dirty = true;
  37997. },
  37998. enumerable: true,
  37999. configurable: true
  38000. });
  38001. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38002. /**
  38003. * Gets the highlights Saturation value.
  38004. * 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.
  38005. */
  38006. get: function () {
  38007. return this._highlightsSaturation;
  38008. },
  38009. /**
  38010. * Sets the highlights Saturation value.
  38011. * 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.
  38012. */
  38013. set: function (value) {
  38014. this._highlightsSaturation = value;
  38015. this._dirty = true;
  38016. },
  38017. enumerable: true,
  38018. configurable: true
  38019. });
  38020. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38021. /**
  38022. * Gets the highlights Exposure value.
  38023. * 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.
  38024. */
  38025. get: function () {
  38026. return this._highlightsExposure;
  38027. },
  38028. /**
  38029. * Sets the highlights Exposure value.
  38030. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38031. */
  38032. set: function (value) {
  38033. this._highlightsExposure = value;
  38034. this._dirty = true;
  38035. },
  38036. enumerable: true,
  38037. configurable: true
  38038. });
  38039. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38040. /**
  38041. * Gets the midtones Hue value.
  38042. * 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).
  38043. */
  38044. get: function () {
  38045. return this._midtonesHue;
  38046. },
  38047. /**
  38048. * Sets the midtones Hue value.
  38049. * 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).
  38050. */
  38051. set: function (value) {
  38052. this._midtonesHue = value;
  38053. this._dirty = true;
  38054. },
  38055. enumerable: true,
  38056. configurable: true
  38057. });
  38058. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38059. /**
  38060. * Gets the midtones Density value.
  38061. * 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.
  38062. * Values less than zero provide a filter of opposite hue.
  38063. */
  38064. get: function () {
  38065. return this._midtonesDensity;
  38066. },
  38067. /**
  38068. * Sets the midtones Density value.
  38069. * 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.
  38070. * Values less than zero provide a filter of opposite hue.
  38071. */
  38072. set: function (value) {
  38073. this._midtonesDensity = value;
  38074. this._dirty = true;
  38075. },
  38076. enumerable: true,
  38077. configurable: true
  38078. });
  38079. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38080. /**
  38081. * Gets the midtones Saturation value.
  38082. * 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.
  38083. */
  38084. get: function () {
  38085. return this._midtonesSaturation;
  38086. },
  38087. /**
  38088. * Sets the midtones Saturation value.
  38089. * 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.
  38090. */
  38091. set: function (value) {
  38092. this._midtonesSaturation = value;
  38093. this._dirty = true;
  38094. },
  38095. enumerable: true,
  38096. configurable: true
  38097. });
  38098. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38099. /**
  38100. * Gets the midtones Exposure value.
  38101. * 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.
  38102. */
  38103. get: function () {
  38104. return this._midtonesExposure;
  38105. },
  38106. /**
  38107. * Sets the midtones Exposure value.
  38108. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38109. */
  38110. set: function (value) {
  38111. this._midtonesExposure = value;
  38112. this._dirty = true;
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38118. /**
  38119. * Gets the shadows Hue value.
  38120. * 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).
  38121. */
  38122. get: function () {
  38123. return this._shadowsHue;
  38124. },
  38125. /**
  38126. * Sets the shadows Hue value.
  38127. * 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).
  38128. */
  38129. set: function (value) {
  38130. this._shadowsHue = value;
  38131. this._dirty = true;
  38132. },
  38133. enumerable: true,
  38134. configurable: true
  38135. });
  38136. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38137. /**
  38138. * Gets the shadows Density value.
  38139. * 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.
  38140. * Values less than zero provide a filter of opposite hue.
  38141. */
  38142. get: function () {
  38143. return this._shadowsDensity;
  38144. },
  38145. /**
  38146. * Sets the shadows Density value.
  38147. * 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.
  38148. * Values less than zero provide a filter of opposite hue.
  38149. */
  38150. set: function (value) {
  38151. this._shadowsDensity = value;
  38152. this._dirty = true;
  38153. },
  38154. enumerable: true,
  38155. configurable: true
  38156. });
  38157. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38158. /**
  38159. * Gets the shadows Saturation value.
  38160. * 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.
  38161. */
  38162. get: function () {
  38163. return this._shadowsSaturation;
  38164. },
  38165. /**
  38166. * Sets the shadows Saturation value.
  38167. * 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.
  38168. */
  38169. set: function (value) {
  38170. this._shadowsSaturation = value;
  38171. this._dirty = true;
  38172. },
  38173. enumerable: true,
  38174. configurable: true
  38175. });
  38176. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38177. /**
  38178. * Gets the shadows Exposure value.
  38179. * 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.
  38180. */
  38181. get: function () {
  38182. return this._shadowsExposure;
  38183. },
  38184. /**
  38185. * Sets the shadows Exposure value.
  38186. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38187. */
  38188. set: function (value) {
  38189. this._shadowsExposure = value;
  38190. this._dirty = true;
  38191. },
  38192. enumerable: true,
  38193. configurable: true
  38194. });
  38195. ColorCurves.prototype.getClassName = function () {
  38196. return "ColorCurves";
  38197. };
  38198. /**
  38199. * Binds the color curves to the shader.
  38200. * @param colorCurves The color curve to bind
  38201. * @param effect The effect to bind to
  38202. */
  38203. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38204. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38205. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38206. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38207. if (colorCurves._dirty) {
  38208. colorCurves._dirty = false;
  38209. // Fill in global info.
  38210. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38211. // Compute highlights info.
  38212. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38213. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38214. // Compute midtones info.
  38215. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38216. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38217. // Compute shadows info.
  38218. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38219. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38220. // Compute deltas (neutral is midtones).
  38221. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38222. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38223. }
  38224. if (effect) {
  38225. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38226. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38227. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38228. }
  38229. };
  38230. /**
  38231. * Prepare the list of uniforms associated with the ColorCurves effects.
  38232. * @param uniformsList The list of uniforms used in the effect
  38233. */
  38234. ColorCurves.PrepareUniforms = function (uniformsList) {
  38235. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38236. };
  38237. /**
  38238. * Returns color grading data based on a hue, density, saturation and exposure value.
  38239. * @param filterHue The hue of the color filter.
  38240. * @param filterDensity The density of the color filter.
  38241. * @param saturation The saturation.
  38242. * @param exposure The exposure.
  38243. * @param result The result data container.
  38244. */
  38245. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38246. if (hue == null) {
  38247. return;
  38248. }
  38249. hue = ColorCurves.clamp(hue, 0, 360);
  38250. density = ColorCurves.clamp(density, -100, 100);
  38251. saturation = ColorCurves.clamp(saturation, -100, 100);
  38252. exposure = ColorCurves.clamp(exposure, -100, 100);
  38253. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38254. // so that the maximum filter density is only 50% control. This provides fine control
  38255. // for small values and reasonable range.
  38256. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38257. density *= 0.5;
  38258. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38259. if (density < 0) {
  38260. density *= -1;
  38261. hue = (hue + 180) % 360;
  38262. }
  38263. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38264. result.scaleToRef(2, result);
  38265. result.a = 1 + 0.01 * saturation;
  38266. };
  38267. /**
  38268. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38269. * @param value The input slider value in range [-100,100].
  38270. * @returns Adjusted value.
  38271. */
  38272. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38273. value /= 100;
  38274. var x = Math.abs(value);
  38275. x = Math.pow(x, 2);
  38276. if (value < 0) {
  38277. x *= -1;
  38278. }
  38279. x *= 100;
  38280. return x;
  38281. };
  38282. /**
  38283. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38284. * @param hue The hue (H) input.
  38285. * @param saturation The saturation (S) input.
  38286. * @param brightness The brightness (B) input.
  38287. * @result An RGBA color represented as Vector4.
  38288. */
  38289. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38290. var h = ColorCurves.clamp(hue, 0, 360);
  38291. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38292. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38293. if (s === 0) {
  38294. result.r = v;
  38295. result.g = v;
  38296. result.b = v;
  38297. }
  38298. else {
  38299. // sector 0 to 5
  38300. h /= 60;
  38301. var i = Math.floor(h);
  38302. // fractional part of h
  38303. var f = h - i;
  38304. var p = v * (1 - s);
  38305. var q = v * (1 - s * f);
  38306. var t = v * (1 - s * (1 - f));
  38307. switch (i) {
  38308. case 0:
  38309. result.r = v;
  38310. result.g = t;
  38311. result.b = p;
  38312. break;
  38313. case 1:
  38314. result.r = q;
  38315. result.g = v;
  38316. result.b = p;
  38317. break;
  38318. case 2:
  38319. result.r = p;
  38320. result.g = v;
  38321. result.b = t;
  38322. break;
  38323. case 3:
  38324. result.r = p;
  38325. result.g = q;
  38326. result.b = v;
  38327. break;
  38328. case 4:
  38329. result.r = t;
  38330. result.g = p;
  38331. result.b = v;
  38332. break;
  38333. default:// case 5:
  38334. result.r = v;
  38335. result.g = p;
  38336. result.b = q;
  38337. break;
  38338. }
  38339. }
  38340. result.a = 1;
  38341. };
  38342. /**
  38343. * Returns a value clamped between min and max
  38344. * @param value The value to clamp
  38345. * @param min The minimum of value
  38346. * @param max The maximum of value
  38347. * @returns The clamped value.
  38348. */
  38349. ColorCurves.clamp = function (value, min, max) {
  38350. return Math.min(Math.max(value, min), max);
  38351. };
  38352. /**
  38353. * Clones the current color curve instance.
  38354. * @return The cloned curves
  38355. */
  38356. ColorCurves.prototype.clone = function () {
  38357. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38358. };
  38359. /**
  38360. * Serializes the current color curve instance to a json representation.
  38361. * @return a JSON representation
  38362. */
  38363. ColorCurves.prototype.serialize = function () {
  38364. return BABYLON.SerializationHelper.Serialize(this);
  38365. };
  38366. /**
  38367. * Parses the color curve from a json representation.
  38368. * @param source the JSON source to parse
  38369. * @return The parsed curves
  38370. */
  38371. ColorCurves.Parse = function (source) {
  38372. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38373. };
  38374. __decorate([
  38375. BABYLON.serialize()
  38376. ], ColorCurves.prototype, "_globalHue", void 0);
  38377. __decorate([
  38378. BABYLON.serialize()
  38379. ], ColorCurves.prototype, "_globalDensity", void 0);
  38380. __decorate([
  38381. BABYLON.serialize()
  38382. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38383. __decorate([
  38384. BABYLON.serialize()
  38385. ], ColorCurves.prototype, "_globalExposure", void 0);
  38386. __decorate([
  38387. BABYLON.serialize()
  38388. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38389. __decorate([
  38390. BABYLON.serialize()
  38391. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38392. __decorate([
  38393. BABYLON.serialize()
  38394. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38395. __decorate([
  38396. BABYLON.serialize()
  38397. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38398. __decorate([
  38399. BABYLON.serialize()
  38400. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38401. __decorate([
  38402. BABYLON.serialize()
  38403. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38404. __decorate([
  38405. BABYLON.serialize()
  38406. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38407. __decorate([
  38408. BABYLON.serialize()
  38409. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38410. return ColorCurves;
  38411. }());
  38412. BABYLON.ColorCurves = ColorCurves;
  38413. })(BABYLON || (BABYLON = {}));
  38414. //# sourceMappingURL=babylon.colorCurves.js.map
  38415. //# sourceMappingURL=babylon.behavior.js.map
  38416. var BABYLON;
  38417. (function (BABYLON) {
  38418. /**
  38419. * "Static Class" containing the most commonly used helper while dealing with material for
  38420. * rendering purpose.
  38421. *
  38422. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38423. *
  38424. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38425. */
  38426. var MaterialHelper = /** @class */ (function () {
  38427. function MaterialHelper() {
  38428. }
  38429. /**
  38430. * Bind the current view position to an effect.
  38431. * @param effect The effect to be bound
  38432. * @param scene The scene the eyes position is used from
  38433. */
  38434. MaterialHelper.BindEyePosition = function (effect, scene) {
  38435. if (scene._forcedViewPosition) {
  38436. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38437. return;
  38438. }
  38439. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38440. };
  38441. /**
  38442. * Helps preparing the defines values about the UVs in used in the effect.
  38443. * UVs are shared as much as we can accross chanels in the shaders.
  38444. * @param texture The texture we are preparing the UVs for
  38445. * @param defines The defines to update
  38446. * @param key The chanel key "diffuse", "specular"... used in the shader
  38447. */
  38448. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38449. defines._needUVs = true;
  38450. defines[key] = true;
  38451. if (texture.getTextureMatrix().isIdentity(true)) {
  38452. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38453. if (texture.coordinatesIndex === 0) {
  38454. defines["MAINUV1"] = true;
  38455. }
  38456. else {
  38457. defines["MAINUV2"] = true;
  38458. }
  38459. }
  38460. else {
  38461. defines[key + "DIRECTUV"] = 0;
  38462. }
  38463. };
  38464. /**
  38465. * Binds a texture matrix value to its corrsponding uniform
  38466. * @param texture The texture to bind the matrix for
  38467. * @param uniformBuffer The uniform buffer receivin the data
  38468. * @param key The chanel key "diffuse", "specular"... used in the shader
  38469. */
  38470. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38471. var matrix = texture.getTextureMatrix();
  38472. if (!matrix.isIdentity(true)) {
  38473. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38474. }
  38475. };
  38476. /**
  38477. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38478. * @param mesh defines the current mesh
  38479. * @param scene defines the current scene
  38480. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38481. * @param pointsCloud defines if point cloud rendering has to be turned on
  38482. * @param fogEnabled defines if fog has to be turned on
  38483. * @param alphaTest defines if alpha testing has to be turned on
  38484. * @param defines defines the current list of defines
  38485. */
  38486. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38487. if (defines._areMiscDirty) {
  38488. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38489. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38490. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38491. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38492. defines["ALPHATEST"] = alphaTest;
  38493. }
  38494. };
  38495. /**
  38496. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38497. * @param scene defines the current scene
  38498. * @param engine defines the current engine
  38499. * @param defines specifies the list of active defines
  38500. * @param useInstances defines if instances have to be turned on
  38501. * @param useClipPlane defines if clip plane have to be turned on
  38502. */
  38503. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38504. if (useClipPlane === void 0) { useClipPlane = null; }
  38505. var changed = false;
  38506. if (useClipPlane == null) {
  38507. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38508. }
  38509. if (defines["CLIPPLANE"] !== useClipPlane) {
  38510. defines["CLIPPLANE"] = useClipPlane;
  38511. changed = true;
  38512. }
  38513. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38514. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38515. changed = true;
  38516. }
  38517. if (defines["INSTANCES"] !== useInstances) {
  38518. defines["INSTANCES"] = useInstances;
  38519. changed = true;
  38520. }
  38521. if (changed) {
  38522. defines.markAsUnprocessed();
  38523. }
  38524. };
  38525. /**
  38526. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38527. * @param mesh The mesh containing the geometry data we will draw
  38528. * @param defines The defines to update
  38529. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38530. * @param useBones Precise whether bones should be used or not (override mesh info)
  38531. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38532. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38533. * @returns false if defines are considered not dirty and have not been checked
  38534. */
  38535. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38536. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38537. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38538. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38539. return false;
  38540. }
  38541. defines._normals = defines._needNormals;
  38542. defines._uvs = defines._needUVs;
  38543. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38544. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38545. defines["TANGENT"] = true;
  38546. }
  38547. if (defines._needUVs) {
  38548. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38549. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38550. }
  38551. else {
  38552. defines["UV1"] = false;
  38553. defines["UV2"] = false;
  38554. }
  38555. if (useVertexColor) {
  38556. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38557. defines["VERTEXCOLOR"] = hasVertexColors;
  38558. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38559. }
  38560. if (useBones) {
  38561. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38562. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38563. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38564. }
  38565. else {
  38566. defines["NUM_BONE_INFLUENCERS"] = 0;
  38567. defines["BonesPerMesh"] = 0;
  38568. }
  38569. }
  38570. if (useMorphTargets) {
  38571. var manager = mesh.morphTargetManager;
  38572. if (manager) {
  38573. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38574. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38575. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38576. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38577. }
  38578. else {
  38579. defines["MORPHTARGETS_TANGENT"] = false;
  38580. defines["MORPHTARGETS_NORMAL"] = false;
  38581. defines["MORPHTARGETS"] = false;
  38582. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38583. }
  38584. }
  38585. return true;
  38586. };
  38587. /**
  38588. * Prepares the defines related to the light information passed in parameter
  38589. * @param scene The scene we are intending to draw
  38590. * @param mesh The mesh the effect is compiling for
  38591. * @param defines The defines to update
  38592. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38593. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38594. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38595. * @returns true if normals will be required for the rest of the effect
  38596. */
  38597. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38598. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38599. if (disableLighting === void 0) { disableLighting = false; }
  38600. if (!defines._areLightsDirty) {
  38601. return defines._needNormals;
  38602. }
  38603. var lightIndex = 0;
  38604. var needNormals = false;
  38605. var needRebuild = false;
  38606. var lightmapMode = false;
  38607. var shadowEnabled = false;
  38608. var specularEnabled = false;
  38609. if (scene.lightsEnabled && !disableLighting) {
  38610. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38611. var light = _a[_i];
  38612. needNormals = true;
  38613. if (defines["LIGHT" + lightIndex] === undefined) {
  38614. needRebuild = true;
  38615. }
  38616. defines["LIGHT" + lightIndex] = true;
  38617. defines["SPOTLIGHT" + lightIndex] = false;
  38618. defines["HEMILIGHT" + lightIndex] = false;
  38619. defines["POINTLIGHT" + lightIndex] = false;
  38620. defines["DIRLIGHT" + lightIndex] = false;
  38621. var type;
  38622. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38623. type = "SPOTLIGHT" + lightIndex;
  38624. var spotLight = light;
  38625. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38626. }
  38627. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38628. type = "HEMILIGHT" + lightIndex;
  38629. }
  38630. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38631. type = "POINTLIGHT" + lightIndex;
  38632. }
  38633. else {
  38634. type = "DIRLIGHT" + lightIndex;
  38635. }
  38636. defines[type] = true;
  38637. // Specular
  38638. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38639. specularEnabled = true;
  38640. }
  38641. // Shadows
  38642. defines["SHADOW" + lightIndex] = false;
  38643. defines["SHADOWPCF" + lightIndex] = false;
  38644. defines["SHADOWESM" + lightIndex] = false;
  38645. defines["SHADOWCUBE" + lightIndex] = false;
  38646. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38647. var shadowGenerator = light.getShadowGenerator();
  38648. if (shadowGenerator) {
  38649. shadowEnabled = true;
  38650. shadowGenerator.prepareDefines(defines, lightIndex);
  38651. }
  38652. }
  38653. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38654. lightmapMode = true;
  38655. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38656. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38657. }
  38658. else {
  38659. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38660. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38661. }
  38662. lightIndex++;
  38663. if (lightIndex === maxSimultaneousLights)
  38664. break;
  38665. }
  38666. }
  38667. defines["SPECULARTERM"] = specularEnabled;
  38668. defines["SHADOWS"] = shadowEnabled;
  38669. // Resetting all other lights if any
  38670. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38671. if (defines["LIGHT" + index] !== undefined) {
  38672. defines["LIGHT" + index] = false;
  38673. defines["HEMILIGHT" + lightIndex] = false;
  38674. defines["POINTLIGHT" + lightIndex] = false;
  38675. defines["DIRLIGHT" + lightIndex] = false;
  38676. defines["SPOTLIGHT" + lightIndex] = false;
  38677. defines["SHADOW" + lightIndex] = false;
  38678. }
  38679. }
  38680. var caps = scene.getEngine().getCaps();
  38681. if (defines["SHADOWFLOAT"] === undefined) {
  38682. needRebuild = true;
  38683. }
  38684. defines["SHADOWFLOAT"] = shadowEnabled &&
  38685. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38686. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38687. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38688. if (needRebuild) {
  38689. defines.rebuild();
  38690. }
  38691. return needNormals;
  38692. };
  38693. /**
  38694. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38695. * that won t be acctive due to defines being turned off.
  38696. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38697. * @param samplersList The samplers list
  38698. * @param defines The defines helping in the list generation
  38699. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38700. */
  38701. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38702. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38703. var uniformsList;
  38704. var uniformBuffersList = null;
  38705. if (uniformsListOrOptions.uniformsNames) {
  38706. var options = uniformsListOrOptions;
  38707. uniformsList = options.uniformsNames;
  38708. uniformBuffersList = options.uniformBuffersNames;
  38709. samplersList = options.samplers;
  38710. defines = options.defines;
  38711. maxSimultaneousLights = options.maxSimultaneousLights;
  38712. }
  38713. else {
  38714. uniformsList = uniformsListOrOptions;
  38715. if (!samplersList) {
  38716. samplersList = [];
  38717. }
  38718. }
  38719. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38720. if (!defines["LIGHT" + lightIndex]) {
  38721. break;
  38722. }
  38723. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38724. if (uniformBuffersList) {
  38725. uniformBuffersList.push("Light" + lightIndex);
  38726. }
  38727. samplersList.push("shadowSampler" + lightIndex);
  38728. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38729. samplersList.push("projectionLightSampler" + lightIndex);
  38730. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38731. }
  38732. }
  38733. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38734. uniformsList.push("morphTargetInfluences");
  38735. }
  38736. };
  38737. /**
  38738. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38739. * @param defines The defines to update while falling back
  38740. * @param fallbacks The authorized effect fallbacks
  38741. * @param maxSimultaneousLights The maximum number of lights allowed
  38742. * @param rank the current rank of the Effect
  38743. * @returns The newly affected rank
  38744. */
  38745. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38746. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38747. if (rank === void 0) { rank = 0; }
  38748. var lightFallbackRank = 0;
  38749. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38750. if (!defines["LIGHT" + lightIndex]) {
  38751. break;
  38752. }
  38753. if (lightIndex > 0) {
  38754. lightFallbackRank = rank + lightIndex;
  38755. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38756. }
  38757. if (!defines["SHADOWS"]) {
  38758. if (defines["SHADOW" + lightIndex]) {
  38759. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38760. }
  38761. if (defines["SHADOWPCF" + lightIndex]) {
  38762. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38763. }
  38764. if (defines["SHADOWESM" + lightIndex]) {
  38765. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38766. }
  38767. }
  38768. }
  38769. return lightFallbackRank++;
  38770. };
  38771. /**
  38772. * Prepares the list of attributes required for morph targets according to the effect defines.
  38773. * @param attribs The current list of supported attribs
  38774. * @param mesh The mesh to prepare the morph targets attributes for
  38775. * @param defines The current Defines of the effect
  38776. */
  38777. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38778. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38779. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38780. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38781. var manager = mesh.morphTargetManager;
  38782. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38783. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38784. for (var index = 0; index < influencers; index++) {
  38785. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38786. if (normal) {
  38787. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38788. }
  38789. if (tangent) {
  38790. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38791. }
  38792. if (attribs.length > maxAttributesCount) {
  38793. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38794. }
  38795. }
  38796. }
  38797. };
  38798. /**
  38799. * Prepares the list of attributes required for bones according to the effect defines.
  38800. * @param attribs The current list of supported attribs
  38801. * @param mesh The mesh to prepare the bones attributes for
  38802. * @param defines The current Defines of the effect
  38803. * @param fallbacks The current efffect fallback strategy
  38804. */
  38805. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38806. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38807. fallbacks.addCPUSkinningFallback(0, mesh);
  38808. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38809. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38810. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38811. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38812. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38813. }
  38814. }
  38815. };
  38816. /**
  38817. * Prepares the list of attributes required for instances according to the effect defines.
  38818. * @param attribs The current list of supported attribs
  38819. * @param defines The current Defines of the effect
  38820. */
  38821. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38822. if (defines["INSTANCES"]) {
  38823. attribs.push("world0");
  38824. attribs.push("world1");
  38825. attribs.push("world2");
  38826. attribs.push("world3");
  38827. }
  38828. };
  38829. /**
  38830. * Binds the light shadow information to the effect for the given mesh.
  38831. * @param light The light containing the generator
  38832. * @param scene The scene the lights belongs to
  38833. * @param mesh The mesh we are binding the information to render
  38834. * @param lightIndex The light index in the effect used to render the mesh
  38835. * @param effect The effect we are binding the data to
  38836. */
  38837. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38838. if (light.shadowEnabled && mesh.receiveShadows) {
  38839. var shadowGenerator = light.getShadowGenerator();
  38840. if (shadowGenerator) {
  38841. shadowGenerator.bindShadowLight(lightIndex, effect);
  38842. }
  38843. }
  38844. };
  38845. /**
  38846. * Binds the light information to the effect.
  38847. * @param light The light containing the generator
  38848. * @param effect The effect we are binding the data to
  38849. * @param lightIndex The light index in the effect used to render
  38850. */
  38851. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38852. light.transferToEffect(effect, lightIndex + "");
  38853. };
  38854. /**
  38855. * Binds the lights information from the scene to the effect for the given mesh.
  38856. * @param scene The scene the lights belongs to
  38857. * @param mesh The mesh we are binding the information to render
  38858. * @param effect The effect we are binding the data to
  38859. * @param defines The generated defines for the effect
  38860. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38861. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38862. */
  38863. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38864. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38865. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38866. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38867. for (var i = 0; i < len; i++) {
  38868. var light = mesh._lightSources[i];
  38869. var iAsString = i.toString();
  38870. var scaledIntensity = light.getScaledIntensity();
  38871. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38872. MaterialHelper.BindLightProperties(light, effect, i);
  38873. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38874. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38875. if (defines["SPECULARTERM"]) {
  38876. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38877. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38878. }
  38879. // Shadows
  38880. if (scene.shadowsEnabled) {
  38881. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38882. }
  38883. light._uniformBuffer.update();
  38884. }
  38885. };
  38886. /**
  38887. * Binds the fog information from the scene to the effect for the given mesh.
  38888. * @param scene The scene the lights belongs to
  38889. * @param mesh The mesh we are binding the information to render
  38890. * @param effect The effect we are binding the data to
  38891. */
  38892. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38893. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38894. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38895. effect.setColor3("vFogColor", scene.fogColor);
  38896. }
  38897. };
  38898. /**
  38899. * Binds the bones information from the mesh to the effect.
  38900. * @param mesh The mesh we are binding the information to render
  38901. * @param effect The effect we are binding the data to
  38902. */
  38903. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38904. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38905. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38906. if (matrices && effect) {
  38907. effect.setMatrices("mBones", matrices);
  38908. }
  38909. }
  38910. };
  38911. /**
  38912. * Binds the morph targets information from the mesh to the effect.
  38913. * @param abstractMesh The mesh we are binding the information to render
  38914. * @param effect The effect we are binding the data to
  38915. */
  38916. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38917. var manager = abstractMesh.morphTargetManager;
  38918. if (!abstractMesh || !manager) {
  38919. return;
  38920. }
  38921. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38922. };
  38923. /**
  38924. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38925. * @param defines The generated defines used in the effect
  38926. * @param effect The effect we are binding the data to
  38927. * @param scene The scene we are willing to render with logarithmic scale for
  38928. */
  38929. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38930. if (defines["LOGARITHMICDEPTH"]) {
  38931. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38932. }
  38933. };
  38934. /**
  38935. * Binds the clip plane information from the scene to the effect.
  38936. * @param scene The scene the clip plane information are extracted from
  38937. * @param effect The effect we are binding the data to
  38938. */
  38939. MaterialHelper.BindClipPlane = function (effect, scene) {
  38940. if (scene.clipPlane) {
  38941. var clipPlane = scene.clipPlane;
  38942. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38943. }
  38944. };
  38945. return MaterialHelper;
  38946. }());
  38947. BABYLON.MaterialHelper = MaterialHelper;
  38948. })(BABYLON || (BABYLON = {}));
  38949. //# sourceMappingURL=babylon.materialHelper.js.map
  38950. var BABYLON;
  38951. (function (BABYLON) {
  38952. var PushMaterial = /** @class */ (function (_super) {
  38953. __extends(PushMaterial, _super);
  38954. function PushMaterial(name, scene) {
  38955. var _this = _super.call(this, name, scene) || this;
  38956. _this._normalMatrix = new BABYLON.Matrix();
  38957. _this.storeEffectOnSubMeshes = true;
  38958. return _this;
  38959. }
  38960. PushMaterial.prototype.getEffect = function () {
  38961. return this._activeEffect;
  38962. };
  38963. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38964. if (!mesh) {
  38965. return false;
  38966. }
  38967. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38968. return true;
  38969. }
  38970. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38971. };
  38972. /**
  38973. * Binds the given world matrix to the active effect
  38974. *
  38975. * @param world the matrix to bind
  38976. */
  38977. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38978. this._activeEffect.setMatrix("world", world);
  38979. };
  38980. /**
  38981. * Binds the given normal matrix to the active effect
  38982. *
  38983. * @param normalMatrix the matrix to bind
  38984. */
  38985. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38986. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38987. };
  38988. PushMaterial.prototype.bind = function (world, mesh) {
  38989. if (!mesh) {
  38990. return;
  38991. }
  38992. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38993. };
  38994. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38995. if (effect === void 0) { effect = null; }
  38996. _super.prototype._afterBind.call(this, mesh);
  38997. this.getScene()._cachedEffect = effect;
  38998. };
  38999. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39000. if (visibility === void 0) { visibility = 1; }
  39001. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39002. };
  39003. return PushMaterial;
  39004. }(BABYLON.Material));
  39005. BABYLON.PushMaterial = PushMaterial;
  39006. })(BABYLON || (BABYLON = {}));
  39007. //# sourceMappingURL=babylon.pushMaterial.js.map
  39008. var BABYLON;
  39009. (function (BABYLON) {
  39010. /** @ignore */
  39011. var StandardMaterialDefines = /** @class */ (function (_super) {
  39012. __extends(StandardMaterialDefines, _super);
  39013. function StandardMaterialDefines() {
  39014. var _this = _super.call(this) || this;
  39015. _this.MAINUV1 = false;
  39016. _this.MAINUV2 = false;
  39017. _this.DIFFUSE = false;
  39018. _this.DIFFUSEDIRECTUV = 0;
  39019. _this.AMBIENT = false;
  39020. _this.AMBIENTDIRECTUV = 0;
  39021. _this.OPACITY = false;
  39022. _this.OPACITYDIRECTUV = 0;
  39023. _this.OPACITYRGB = false;
  39024. _this.REFLECTION = false;
  39025. _this.EMISSIVE = false;
  39026. _this.EMISSIVEDIRECTUV = 0;
  39027. _this.SPECULAR = false;
  39028. _this.SPECULARDIRECTUV = 0;
  39029. _this.BUMP = false;
  39030. _this.BUMPDIRECTUV = 0;
  39031. _this.PARALLAX = false;
  39032. _this.PARALLAXOCCLUSION = false;
  39033. _this.SPECULAROVERALPHA = false;
  39034. _this.CLIPPLANE = false;
  39035. _this.ALPHATEST = false;
  39036. _this.DEPTHPREPASS = false;
  39037. _this.ALPHAFROMDIFFUSE = false;
  39038. _this.POINTSIZE = false;
  39039. _this.FOG = false;
  39040. _this.SPECULARTERM = false;
  39041. _this.DIFFUSEFRESNEL = false;
  39042. _this.OPACITYFRESNEL = false;
  39043. _this.REFLECTIONFRESNEL = false;
  39044. _this.REFRACTIONFRESNEL = false;
  39045. _this.EMISSIVEFRESNEL = false;
  39046. _this.FRESNEL = false;
  39047. _this.NORMAL = false;
  39048. _this.UV1 = false;
  39049. _this.UV2 = false;
  39050. _this.VERTEXCOLOR = false;
  39051. _this.VERTEXALPHA = false;
  39052. _this.NUM_BONE_INFLUENCERS = 0;
  39053. _this.BonesPerMesh = 0;
  39054. _this.INSTANCES = false;
  39055. _this.GLOSSINESS = false;
  39056. _this.ROUGHNESS = false;
  39057. _this.EMISSIVEASILLUMINATION = false;
  39058. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39059. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39060. _this.LIGHTMAP = false;
  39061. _this.LIGHTMAPDIRECTUV = 0;
  39062. _this.OBJECTSPACE_NORMALMAP = false;
  39063. _this.USELIGHTMAPASSHADOWMAP = false;
  39064. _this.REFLECTIONMAP_3D = false;
  39065. _this.REFLECTIONMAP_SPHERICAL = false;
  39066. _this.REFLECTIONMAP_PLANAR = false;
  39067. _this.REFLECTIONMAP_CUBIC = false;
  39068. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39069. _this.REFLECTIONMAP_PROJECTION = false;
  39070. _this.REFLECTIONMAP_SKYBOX = false;
  39071. _this.REFLECTIONMAP_EXPLICIT = false;
  39072. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39073. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39074. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39075. _this.INVERTCUBICMAP = false;
  39076. _this.LOGARITHMICDEPTH = false;
  39077. _this.REFRACTION = false;
  39078. _this.REFRACTIONMAP_3D = false;
  39079. _this.REFLECTIONOVERALPHA = false;
  39080. _this.TWOSIDEDLIGHTING = false;
  39081. _this.SHADOWFLOAT = false;
  39082. _this.MORPHTARGETS = false;
  39083. _this.MORPHTARGETS_NORMAL = false;
  39084. _this.MORPHTARGETS_TANGENT = false;
  39085. _this.NUM_MORPH_INFLUENCERS = 0;
  39086. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39087. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39088. _this.IMAGEPROCESSING = false;
  39089. _this.VIGNETTE = false;
  39090. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39091. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39092. _this.TONEMAPPING = false;
  39093. _this.CONTRAST = false;
  39094. _this.COLORCURVES = false;
  39095. _this.COLORGRADING = false;
  39096. _this.COLORGRADING3D = false;
  39097. _this.SAMPLER3DGREENDEPTH = false;
  39098. _this.SAMPLER3DBGRMAP = false;
  39099. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39100. _this.EXPOSURE = false;
  39101. _this.GRAIN = false;
  39102. _this.rebuild();
  39103. return _this;
  39104. }
  39105. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39106. var modes = [
  39107. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39108. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39109. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39110. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39111. ];
  39112. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39113. var mode = modes_1[_i];
  39114. this[mode] = (mode === modeToEnable);
  39115. }
  39116. };
  39117. return StandardMaterialDefines;
  39118. }(BABYLON.MaterialDefines));
  39119. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39120. var StandardMaterial = /** @class */ (function (_super) {
  39121. __extends(StandardMaterial, _super);
  39122. function StandardMaterial(name, scene) {
  39123. var _this = _super.call(this, name, scene) || this;
  39124. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39125. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39126. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39127. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39128. _this.specularPower = 64;
  39129. _this._useAlphaFromDiffuseTexture = false;
  39130. _this._useEmissiveAsIllumination = false;
  39131. _this._linkEmissiveWithDiffuse = false;
  39132. _this._useSpecularOverAlpha = false;
  39133. _this._useReflectionOverAlpha = false;
  39134. _this._disableLighting = false;
  39135. _this._useObjectSpaceNormalMap = false;
  39136. _this._useParallax = false;
  39137. _this._useParallaxOcclusion = false;
  39138. _this.parallaxScaleBias = 0.05;
  39139. _this._roughness = 0;
  39140. _this.indexOfRefraction = 0.98;
  39141. _this.invertRefractionY = true;
  39142. _this._useLightmapAsShadowmap = false;
  39143. _this._useReflectionFresnelFromSpecular = false;
  39144. _this._useGlossinessFromSpecularMapAlpha = false;
  39145. _this._maxSimultaneousLights = 4;
  39146. /**
  39147. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39148. */
  39149. _this._invertNormalMapX = false;
  39150. /**
  39151. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39152. */
  39153. _this._invertNormalMapY = false;
  39154. /**
  39155. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39156. */
  39157. _this._twoSidedLighting = false;
  39158. _this._renderTargets = new BABYLON.SmartArray(16);
  39159. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39160. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39161. // Setup the default processing configuration to the scene.
  39162. _this._attachImageProcessingConfiguration(null);
  39163. _this.getRenderTargetTextures = function () {
  39164. _this._renderTargets.reset();
  39165. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39166. _this._renderTargets.push(_this._reflectionTexture);
  39167. }
  39168. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39169. _this._renderTargets.push(_this._refractionTexture);
  39170. }
  39171. return _this._renderTargets;
  39172. };
  39173. return _this;
  39174. }
  39175. ;
  39176. ;
  39177. ;
  39178. ;
  39179. ;
  39180. ;
  39181. ;
  39182. ;
  39183. ;
  39184. ;
  39185. ;
  39186. ;
  39187. ;
  39188. ;
  39189. ;
  39190. ;
  39191. ;
  39192. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39193. /**
  39194. * Gets the image processing configuration used either in this material.
  39195. */
  39196. get: function () {
  39197. return this._imageProcessingConfiguration;
  39198. },
  39199. /**
  39200. * Sets the Default image processing configuration used either in the this material.
  39201. *
  39202. * If sets to null, the scene one is in use.
  39203. */
  39204. set: function (value) {
  39205. this._attachImageProcessingConfiguration(value);
  39206. // Ensure the effect will be rebuilt.
  39207. this._markAllSubMeshesAsTexturesDirty();
  39208. },
  39209. enumerable: true,
  39210. configurable: true
  39211. });
  39212. /**
  39213. * Attaches a new image processing configuration to the Standard Material.
  39214. * @param configuration
  39215. */
  39216. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39217. var _this = this;
  39218. if (configuration === this._imageProcessingConfiguration) {
  39219. return;
  39220. }
  39221. // Detaches observer.
  39222. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39223. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39224. }
  39225. // Pick the scene configuration if needed.
  39226. if (!configuration) {
  39227. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39228. }
  39229. else {
  39230. this._imageProcessingConfiguration = configuration;
  39231. }
  39232. // Attaches observer.
  39233. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39234. _this._markAllSubMeshesAsImageProcessingDirty();
  39235. });
  39236. };
  39237. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39238. /**
  39239. * Gets wether the color curves effect is enabled.
  39240. */
  39241. get: function () {
  39242. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39243. },
  39244. /**
  39245. * Sets wether the color curves effect is enabled.
  39246. */
  39247. set: function (value) {
  39248. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39249. },
  39250. enumerable: true,
  39251. configurable: true
  39252. });
  39253. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39254. /**
  39255. * Gets wether the color grading effect is enabled.
  39256. */
  39257. get: function () {
  39258. return this.imageProcessingConfiguration.colorGradingEnabled;
  39259. },
  39260. /**
  39261. * Gets wether the color grading effect is enabled.
  39262. */
  39263. set: function (value) {
  39264. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39265. },
  39266. enumerable: true,
  39267. configurable: true
  39268. });
  39269. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39270. /**
  39271. * Gets wether tonemapping is enabled or not.
  39272. */
  39273. get: function () {
  39274. return this._imageProcessingConfiguration.toneMappingEnabled;
  39275. },
  39276. /**
  39277. * Sets wether tonemapping is enabled or not
  39278. */
  39279. set: function (value) {
  39280. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. ;
  39286. ;
  39287. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39288. /**
  39289. * The camera exposure used on this material.
  39290. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39291. * This corresponds to a photographic exposure.
  39292. */
  39293. get: function () {
  39294. return this._imageProcessingConfiguration.exposure;
  39295. },
  39296. /**
  39297. * The camera exposure used on this material.
  39298. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39299. * This corresponds to a photographic exposure.
  39300. */
  39301. set: function (value) {
  39302. this._imageProcessingConfiguration.exposure = value;
  39303. },
  39304. enumerable: true,
  39305. configurable: true
  39306. });
  39307. ;
  39308. ;
  39309. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39310. /**
  39311. * Gets The camera contrast used on this material.
  39312. */
  39313. get: function () {
  39314. return this._imageProcessingConfiguration.contrast;
  39315. },
  39316. /**
  39317. * Sets The camera contrast used on this material.
  39318. */
  39319. set: function (value) {
  39320. this._imageProcessingConfiguration.contrast = value;
  39321. },
  39322. enumerable: true,
  39323. configurable: true
  39324. });
  39325. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39326. /**
  39327. * Gets the Color Grading 2D Lookup Texture.
  39328. */
  39329. get: function () {
  39330. return this._imageProcessingConfiguration.colorGradingTexture;
  39331. },
  39332. /**
  39333. * Sets the Color Grading 2D Lookup Texture.
  39334. */
  39335. set: function (value) {
  39336. this._imageProcessingConfiguration.colorGradingTexture = value;
  39337. },
  39338. enumerable: true,
  39339. configurable: true
  39340. });
  39341. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39342. /**
  39343. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39344. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39345. * 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;
  39346. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39347. */
  39348. get: function () {
  39349. return this._imageProcessingConfiguration.colorCurves;
  39350. },
  39351. /**
  39352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39354. * 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;
  39355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39356. */
  39357. set: function (value) {
  39358. this._imageProcessingConfiguration.colorCurves = value;
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. StandardMaterial.prototype.getClassName = function () {
  39364. return "StandardMaterial";
  39365. };
  39366. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39367. get: function () {
  39368. return this._useLogarithmicDepth;
  39369. },
  39370. set: function (value) {
  39371. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39372. this._markAllSubMeshesAsMiscDirty();
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. StandardMaterial.prototype.needAlphaBlending = function () {
  39378. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39379. };
  39380. StandardMaterial.prototype.needAlphaTesting = function () {
  39381. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39382. };
  39383. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39384. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39385. };
  39386. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39387. return this._diffuseTexture;
  39388. };
  39389. /**
  39390. * Child classes can use it to update shaders
  39391. */
  39392. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39393. if (useInstances === void 0) { useInstances = false; }
  39394. if (subMesh.effect && this.isFrozen) {
  39395. if (this._wasPreviouslyReady && subMesh.effect) {
  39396. return true;
  39397. }
  39398. }
  39399. if (!subMesh._materialDefines) {
  39400. subMesh._materialDefines = new StandardMaterialDefines();
  39401. }
  39402. var scene = this.getScene();
  39403. var defines = subMesh._materialDefines;
  39404. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39405. if (defines._renderId === scene.getRenderId()) {
  39406. return true;
  39407. }
  39408. }
  39409. var engine = scene.getEngine();
  39410. // Lights
  39411. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39412. // Textures
  39413. if (defines._areTexturesDirty) {
  39414. defines._needUVs = false;
  39415. defines.MAINUV1 = false;
  39416. defines.MAINUV2 = false;
  39417. if (scene.texturesEnabled) {
  39418. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39419. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39420. return false;
  39421. }
  39422. else {
  39423. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39424. }
  39425. }
  39426. else {
  39427. defines.DIFFUSE = false;
  39428. }
  39429. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39430. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39431. return false;
  39432. }
  39433. else {
  39434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39435. }
  39436. }
  39437. else {
  39438. defines.AMBIENT = false;
  39439. }
  39440. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39441. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39442. return false;
  39443. }
  39444. else {
  39445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39446. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39447. }
  39448. }
  39449. else {
  39450. defines.OPACITY = false;
  39451. }
  39452. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39453. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39454. return false;
  39455. }
  39456. else {
  39457. defines._needNormals = true;
  39458. defines.REFLECTION = true;
  39459. defines.ROUGHNESS = (this._roughness > 0);
  39460. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39461. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39462. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39463. switch (this._reflectionTexture.coordinatesMode) {
  39464. case BABYLON.Texture.CUBIC_MODE:
  39465. case BABYLON.Texture.INVCUBIC_MODE:
  39466. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39467. break;
  39468. case BABYLON.Texture.EXPLICIT_MODE:
  39469. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39470. break;
  39471. case BABYLON.Texture.PLANAR_MODE:
  39472. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39473. break;
  39474. case BABYLON.Texture.PROJECTION_MODE:
  39475. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39476. break;
  39477. case BABYLON.Texture.SKYBOX_MODE:
  39478. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39479. break;
  39480. case BABYLON.Texture.SPHERICAL_MODE:
  39481. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39482. break;
  39483. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39484. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39485. break;
  39486. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39487. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39488. break;
  39489. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39490. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39491. break;
  39492. }
  39493. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39494. }
  39495. }
  39496. else {
  39497. defines.REFLECTION = false;
  39498. }
  39499. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39500. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39501. return false;
  39502. }
  39503. else {
  39504. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39505. }
  39506. }
  39507. else {
  39508. defines.EMISSIVE = false;
  39509. }
  39510. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39511. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39512. return false;
  39513. }
  39514. else {
  39515. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39516. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39517. }
  39518. }
  39519. else {
  39520. defines.LIGHTMAP = false;
  39521. }
  39522. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39523. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39524. return false;
  39525. }
  39526. else {
  39527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39528. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39529. }
  39530. }
  39531. else {
  39532. defines.SPECULAR = false;
  39533. }
  39534. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39535. // Bump texure can not be not blocking.
  39536. if (!this._bumpTexture.isReady()) {
  39537. return false;
  39538. }
  39539. else {
  39540. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39541. defines.PARALLAX = this._useParallax;
  39542. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39543. }
  39544. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39545. }
  39546. else {
  39547. defines.BUMP = false;
  39548. }
  39549. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39550. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39551. return false;
  39552. }
  39553. else {
  39554. defines._needUVs = true;
  39555. defines.REFRACTION = true;
  39556. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39557. }
  39558. }
  39559. else {
  39560. defines.REFRACTION = false;
  39561. }
  39562. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39563. }
  39564. else {
  39565. defines.DIFFUSE = false;
  39566. defines.AMBIENT = false;
  39567. defines.OPACITY = false;
  39568. defines.REFLECTION = false;
  39569. defines.EMISSIVE = false;
  39570. defines.LIGHTMAP = false;
  39571. defines.BUMP = false;
  39572. defines.REFRACTION = false;
  39573. }
  39574. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39575. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39576. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39577. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39578. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39579. }
  39580. if (defines._areImageProcessingDirty) {
  39581. if (!this._imageProcessingConfiguration.isReady()) {
  39582. return false;
  39583. }
  39584. this._imageProcessingConfiguration.prepareDefines(defines);
  39585. }
  39586. if (defines._areFresnelDirty) {
  39587. if (StandardMaterial.FresnelEnabled) {
  39588. // Fresnel
  39589. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39590. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39591. this._reflectionFresnelParameters) {
  39592. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39593. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39594. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39595. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39596. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39597. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39598. defines._needNormals = true;
  39599. defines.FRESNEL = true;
  39600. }
  39601. }
  39602. else {
  39603. defines.FRESNEL = false;
  39604. }
  39605. }
  39606. // Misc.
  39607. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39608. // Attribs
  39609. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39610. // Values that need to be evaluated on every frame
  39611. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39612. // Get correct effect
  39613. if (defines.isDirty) {
  39614. defines.markAsProcessed();
  39615. scene.resetCachedMaterial();
  39616. // Fallbacks
  39617. var fallbacks = new BABYLON.EffectFallbacks();
  39618. if (defines.REFLECTION) {
  39619. fallbacks.addFallback(0, "REFLECTION");
  39620. }
  39621. if (defines.SPECULAR) {
  39622. fallbacks.addFallback(0, "SPECULAR");
  39623. }
  39624. if (defines.BUMP) {
  39625. fallbacks.addFallback(0, "BUMP");
  39626. }
  39627. if (defines.PARALLAX) {
  39628. fallbacks.addFallback(1, "PARALLAX");
  39629. }
  39630. if (defines.PARALLAXOCCLUSION) {
  39631. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39632. }
  39633. if (defines.SPECULAROVERALPHA) {
  39634. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39635. }
  39636. if (defines.FOG) {
  39637. fallbacks.addFallback(1, "FOG");
  39638. }
  39639. if (defines.POINTSIZE) {
  39640. fallbacks.addFallback(0, "POINTSIZE");
  39641. }
  39642. if (defines.LOGARITHMICDEPTH) {
  39643. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39644. }
  39645. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39646. if (defines.SPECULARTERM) {
  39647. fallbacks.addFallback(0, "SPECULARTERM");
  39648. }
  39649. if (defines.DIFFUSEFRESNEL) {
  39650. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39651. }
  39652. if (defines.OPACITYFRESNEL) {
  39653. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39654. }
  39655. if (defines.REFLECTIONFRESNEL) {
  39656. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39657. }
  39658. if (defines.EMISSIVEFRESNEL) {
  39659. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39660. }
  39661. if (defines.FRESNEL) {
  39662. fallbacks.addFallback(4, "FRESNEL");
  39663. }
  39664. //Attributes
  39665. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39666. if (defines.NORMAL) {
  39667. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39668. }
  39669. if (defines.UV1) {
  39670. attribs.push(BABYLON.VertexBuffer.UVKind);
  39671. }
  39672. if (defines.UV2) {
  39673. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39674. }
  39675. if (defines.VERTEXCOLOR) {
  39676. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39677. }
  39678. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39679. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39680. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39681. var shaderName = "default";
  39682. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39683. "vFogInfos", "vFogColor", "pointSize",
  39684. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39685. "mBones",
  39686. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39687. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39688. "vReflectionPosition", "vReflectionSize",
  39689. "logarithmicDepthConstant", "vTangentSpaceParams"
  39690. ];
  39691. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39692. var uniformBuffers = ["Material", "Scene"];
  39693. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39694. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39695. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39696. uniformsNames: uniforms,
  39697. uniformBuffersNames: uniformBuffers,
  39698. samplers: samplers,
  39699. defines: defines,
  39700. maxSimultaneousLights: this._maxSimultaneousLights
  39701. });
  39702. if (this.customShaderNameResolve) {
  39703. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39704. }
  39705. var join = defines.toString();
  39706. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39707. attributes: attribs,
  39708. uniformsNames: uniforms,
  39709. uniformBuffersNames: uniformBuffers,
  39710. samplers: samplers,
  39711. defines: join,
  39712. fallbacks: fallbacks,
  39713. onCompiled: this.onCompiled,
  39714. onError: this.onError,
  39715. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39716. }, engine), defines);
  39717. this.buildUniformLayout();
  39718. }
  39719. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39720. return false;
  39721. }
  39722. defines._renderId = scene.getRenderId();
  39723. this._wasPreviouslyReady = true;
  39724. return true;
  39725. };
  39726. StandardMaterial.prototype.buildUniformLayout = function () {
  39727. // Order is important !
  39728. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39729. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39730. this._uniformBuffer.addUniform("opacityParts", 4);
  39731. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39732. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39733. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39734. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39735. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39736. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39737. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39738. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39739. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39740. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39741. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39742. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39743. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39744. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39745. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39746. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39747. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39748. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39749. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39750. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39751. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39752. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39753. this._uniformBuffer.addUniform("specularMatrix", 16);
  39754. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39755. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39756. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39757. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39758. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39759. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39760. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39761. this._uniformBuffer.addUniform("pointSize", 1);
  39762. this._uniformBuffer.create();
  39763. };
  39764. StandardMaterial.prototype.unbind = function () {
  39765. if (this._activeEffect) {
  39766. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39767. this._activeEffect.setTexture("reflection2DSampler", null);
  39768. }
  39769. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39770. this._activeEffect.setTexture("refraction2DSampler", null);
  39771. }
  39772. }
  39773. _super.prototype.unbind.call(this);
  39774. };
  39775. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39776. var scene = this.getScene();
  39777. var defines = subMesh._materialDefines;
  39778. if (!defines) {
  39779. return;
  39780. }
  39781. var effect = subMesh.effect;
  39782. if (!effect) {
  39783. return;
  39784. }
  39785. this._activeEffect = effect;
  39786. // Matrices
  39787. this.bindOnlyWorldMatrix(world);
  39788. // Normal Matrix
  39789. if (defines.OBJECTSPACE_NORMALMAP) {
  39790. world.toNormalMatrix(this._normalMatrix);
  39791. this.bindOnlyNormalMatrix(this._normalMatrix);
  39792. }
  39793. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39794. // Bones
  39795. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39796. if (mustRebind) {
  39797. this._uniformBuffer.bindToEffect(effect, "Material");
  39798. this.bindViewProjection(effect);
  39799. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39800. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39801. // Fresnel
  39802. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39803. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39804. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39805. }
  39806. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39807. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39808. }
  39809. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39810. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39811. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39812. }
  39813. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39814. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39815. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39816. }
  39817. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39818. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39819. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39820. }
  39821. }
  39822. // Textures
  39823. if (scene.texturesEnabled) {
  39824. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39825. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39826. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39827. }
  39828. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39829. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39830. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39831. }
  39832. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39833. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39834. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39835. }
  39836. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39837. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39838. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39839. if (this._reflectionTexture.boundingBoxSize) {
  39840. var cubeTexture = this._reflectionTexture;
  39841. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39842. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39843. }
  39844. }
  39845. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39846. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39847. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39848. }
  39849. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39850. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39851. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39852. }
  39853. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39854. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39855. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39856. }
  39857. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39858. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39859. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39860. if (scene._mirroredCameraPosition) {
  39861. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39862. }
  39863. else {
  39864. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39865. }
  39866. }
  39867. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39868. var depth = 1.0;
  39869. if (!this._refractionTexture.isCube) {
  39870. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39871. if (this._refractionTexture.depth) {
  39872. depth = this._refractionTexture.depth;
  39873. }
  39874. }
  39875. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39876. }
  39877. }
  39878. // Point size
  39879. if (this.pointsCloud) {
  39880. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39881. }
  39882. if (defines.SPECULARTERM) {
  39883. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39884. }
  39885. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39886. // Diffuse
  39887. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39888. }
  39889. // Textures
  39890. if (scene.texturesEnabled) {
  39891. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39892. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39893. }
  39894. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39895. effect.setTexture("ambientSampler", this._ambientTexture);
  39896. }
  39897. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39898. effect.setTexture("opacitySampler", this._opacityTexture);
  39899. }
  39900. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39901. if (this._reflectionTexture.isCube) {
  39902. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39903. }
  39904. else {
  39905. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39906. }
  39907. }
  39908. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39909. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39910. }
  39911. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39912. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39913. }
  39914. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39915. effect.setTexture("specularSampler", this._specularTexture);
  39916. }
  39917. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39918. effect.setTexture("bumpSampler", this._bumpTexture);
  39919. }
  39920. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39921. var depth = 1.0;
  39922. if (this._refractionTexture.isCube) {
  39923. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39924. }
  39925. else {
  39926. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39927. }
  39928. }
  39929. }
  39930. // Clip plane
  39931. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39932. // Colors
  39933. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39934. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39935. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39936. }
  39937. if (mustRebind || !this.isFrozen) {
  39938. // Lights
  39939. if (scene.lightsEnabled && !this._disableLighting) {
  39940. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39941. }
  39942. // View
  39943. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39944. this.bindView(effect);
  39945. }
  39946. // Fog
  39947. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39948. // Morph targets
  39949. if (defines.NUM_MORPH_INFLUENCERS) {
  39950. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39951. }
  39952. // Log. depth
  39953. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39954. // image processing
  39955. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39956. this._imageProcessingConfiguration.bind(this._activeEffect);
  39957. }
  39958. }
  39959. this._uniformBuffer.update();
  39960. this._afterBind(mesh, this._activeEffect);
  39961. };
  39962. StandardMaterial.prototype.getAnimatables = function () {
  39963. var results = [];
  39964. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39965. results.push(this._diffuseTexture);
  39966. }
  39967. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39968. results.push(this._ambientTexture);
  39969. }
  39970. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39971. results.push(this._opacityTexture);
  39972. }
  39973. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39974. results.push(this._reflectionTexture);
  39975. }
  39976. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39977. results.push(this._emissiveTexture);
  39978. }
  39979. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39980. results.push(this._specularTexture);
  39981. }
  39982. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39983. results.push(this._bumpTexture);
  39984. }
  39985. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39986. results.push(this._lightmapTexture);
  39987. }
  39988. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39989. results.push(this._refractionTexture);
  39990. }
  39991. return results;
  39992. };
  39993. StandardMaterial.prototype.getActiveTextures = function () {
  39994. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39995. if (this._diffuseTexture) {
  39996. activeTextures.push(this._diffuseTexture);
  39997. }
  39998. if (this._ambientTexture) {
  39999. activeTextures.push(this._ambientTexture);
  40000. }
  40001. if (this._opacityTexture) {
  40002. activeTextures.push(this._opacityTexture);
  40003. }
  40004. if (this._reflectionTexture) {
  40005. activeTextures.push(this._reflectionTexture);
  40006. }
  40007. if (this._emissiveTexture) {
  40008. activeTextures.push(this._emissiveTexture);
  40009. }
  40010. if (this._specularTexture) {
  40011. activeTextures.push(this._specularTexture);
  40012. }
  40013. if (this._bumpTexture) {
  40014. activeTextures.push(this._bumpTexture);
  40015. }
  40016. if (this._lightmapTexture) {
  40017. activeTextures.push(this._lightmapTexture);
  40018. }
  40019. if (this._refractionTexture) {
  40020. activeTextures.push(this._refractionTexture);
  40021. }
  40022. return activeTextures;
  40023. };
  40024. StandardMaterial.prototype.hasTexture = function (texture) {
  40025. if (_super.prototype.hasTexture.call(this, texture)) {
  40026. return true;
  40027. }
  40028. if (this._diffuseTexture === texture) {
  40029. return true;
  40030. }
  40031. if (this._ambientTexture === texture) {
  40032. return true;
  40033. }
  40034. if (this._opacityTexture === texture) {
  40035. return true;
  40036. }
  40037. if (this._reflectionTexture === texture) {
  40038. return true;
  40039. }
  40040. if (this._emissiveTexture === texture) {
  40041. return true;
  40042. }
  40043. if (this._specularTexture === texture) {
  40044. return true;
  40045. }
  40046. if (this._bumpTexture === texture) {
  40047. return true;
  40048. }
  40049. if (this._lightmapTexture === texture) {
  40050. return true;
  40051. }
  40052. if (this._refractionTexture === texture) {
  40053. return true;
  40054. }
  40055. return false;
  40056. };
  40057. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40058. if (forceDisposeTextures) {
  40059. if (this._diffuseTexture) {
  40060. this._diffuseTexture.dispose();
  40061. }
  40062. if (this._ambientTexture) {
  40063. this._ambientTexture.dispose();
  40064. }
  40065. if (this._opacityTexture) {
  40066. this._opacityTexture.dispose();
  40067. }
  40068. if (this._reflectionTexture) {
  40069. this._reflectionTexture.dispose();
  40070. }
  40071. if (this._emissiveTexture) {
  40072. this._emissiveTexture.dispose();
  40073. }
  40074. if (this._specularTexture) {
  40075. this._specularTexture.dispose();
  40076. }
  40077. if (this._bumpTexture) {
  40078. this._bumpTexture.dispose();
  40079. }
  40080. if (this._lightmapTexture) {
  40081. this._lightmapTexture.dispose();
  40082. }
  40083. if (this._refractionTexture) {
  40084. this._refractionTexture.dispose();
  40085. }
  40086. }
  40087. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40088. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40089. }
  40090. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40091. };
  40092. StandardMaterial.prototype.clone = function (name) {
  40093. var _this = this;
  40094. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40095. result.name = name;
  40096. result.id = name;
  40097. return result;
  40098. };
  40099. StandardMaterial.prototype.serialize = function () {
  40100. return BABYLON.SerializationHelper.Serialize(this);
  40101. };
  40102. // Statics
  40103. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40104. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40105. };
  40106. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40107. get: function () {
  40108. return StandardMaterial._DiffuseTextureEnabled;
  40109. },
  40110. set: function (value) {
  40111. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40112. return;
  40113. }
  40114. StandardMaterial._DiffuseTextureEnabled = value;
  40115. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40116. },
  40117. enumerable: true,
  40118. configurable: true
  40119. });
  40120. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40121. get: function () {
  40122. return StandardMaterial._AmbientTextureEnabled;
  40123. },
  40124. set: function (value) {
  40125. if (StandardMaterial._AmbientTextureEnabled === value) {
  40126. return;
  40127. }
  40128. StandardMaterial._AmbientTextureEnabled = value;
  40129. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40130. },
  40131. enumerable: true,
  40132. configurable: true
  40133. });
  40134. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40135. get: function () {
  40136. return StandardMaterial._OpacityTextureEnabled;
  40137. },
  40138. set: function (value) {
  40139. if (StandardMaterial._OpacityTextureEnabled === value) {
  40140. return;
  40141. }
  40142. StandardMaterial._OpacityTextureEnabled = value;
  40143. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40144. },
  40145. enumerable: true,
  40146. configurable: true
  40147. });
  40148. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40149. get: function () {
  40150. return StandardMaterial._ReflectionTextureEnabled;
  40151. },
  40152. set: function (value) {
  40153. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40154. return;
  40155. }
  40156. StandardMaterial._ReflectionTextureEnabled = value;
  40157. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40158. },
  40159. enumerable: true,
  40160. configurable: true
  40161. });
  40162. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40163. get: function () {
  40164. return StandardMaterial._EmissiveTextureEnabled;
  40165. },
  40166. set: function (value) {
  40167. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40168. return;
  40169. }
  40170. StandardMaterial._EmissiveTextureEnabled = value;
  40171. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40172. },
  40173. enumerable: true,
  40174. configurable: true
  40175. });
  40176. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40177. get: function () {
  40178. return StandardMaterial._SpecularTextureEnabled;
  40179. },
  40180. set: function (value) {
  40181. if (StandardMaterial._SpecularTextureEnabled === value) {
  40182. return;
  40183. }
  40184. StandardMaterial._SpecularTextureEnabled = value;
  40185. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40186. },
  40187. enumerable: true,
  40188. configurable: true
  40189. });
  40190. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40191. get: function () {
  40192. return StandardMaterial._BumpTextureEnabled;
  40193. },
  40194. set: function (value) {
  40195. if (StandardMaterial._BumpTextureEnabled === value) {
  40196. return;
  40197. }
  40198. StandardMaterial._BumpTextureEnabled = value;
  40199. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40200. },
  40201. enumerable: true,
  40202. configurable: true
  40203. });
  40204. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40205. get: function () {
  40206. return StandardMaterial._LightmapTextureEnabled;
  40207. },
  40208. set: function (value) {
  40209. if (StandardMaterial._LightmapTextureEnabled === value) {
  40210. return;
  40211. }
  40212. StandardMaterial._LightmapTextureEnabled = value;
  40213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40214. },
  40215. enumerable: true,
  40216. configurable: true
  40217. });
  40218. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40219. get: function () {
  40220. return StandardMaterial._RefractionTextureEnabled;
  40221. },
  40222. set: function (value) {
  40223. if (StandardMaterial._RefractionTextureEnabled === value) {
  40224. return;
  40225. }
  40226. StandardMaterial._RefractionTextureEnabled = value;
  40227. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40228. },
  40229. enumerable: true,
  40230. configurable: true
  40231. });
  40232. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40233. get: function () {
  40234. return StandardMaterial._ColorGradingTextureEnabled;
  40235. },
  40236. set: function (value) {
  40237. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40238. return;
  40239. }
  40240. StandardMaterial._ColorGradingTextureEnabled = value;
  40241. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40242. },
  40243. enumerable: true,
  40244. configurable: true
  40245. });
  40246. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40247. get: function () {
  40248. return StandardMaterial._FresnelEnabled;
  40249. },
  40250. set: function (value) {
  40251. if (StandardMaterial._FresnelEnabled === value) {
  40252. return;
  40253. }
  40254. StandardMaterial._FresnelEnabled = value;
  40255. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40256. },
  40257. enumerable: true,
  40258. configurable: true
  40259. });
  40260. // Flags used to enable or disable a type of texture for all Standard Materials
  40261. StandardMaterial._DiffuseTextureEnabled = true;
  40262. StandardMaterial._AmbientTextureEnabled = true;
  40263. StandardMaterial._OpacityTextureEnabled = true;
  40264. StandardMaterial._ReflectionTextureEnabled = true;
  40265. StandardMaterial._EmissiveTextureEnabled = true;
  40266. StandardMaterial._SpecularTextureEnabled = true;
  40267. StandardMaterial._BumpTextureEnabled = true;
  40268. StandardMaterial._LightmapTextureEnabled = true;
  40269. StandardMaterial._RefractionTextureEnabled = true;
  40270. StandardMaterial._ColorGradingTextureEnabled = true;
  40271. StandardMaterial._FresnelEnabled = true;
  40272. __decorate([
  40273. BABYLON.serializeAsTexture("diffuseTexture")
  40274. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40277. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40278. __decorate([
  40279. BABYLON.serializeAsTexture("ambientTexture")
  40280. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40284. __decorate([
  40285. BABYLON.serializeAsTexture("opacityTexture")
  40286. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40289. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40290. __decorate([
  40291. BABYLON.serializeAsTexture("reflectionTexture")
  40292. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40293. __decorate([
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40295. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40296. __decorate([
  40297. BABYLON.serializeAsTexture("emissiveTexture")
  40298. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40299. __decorate([
  40300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40301. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40302. __decorate([
  40303. BABYLON.serializeAsTexture("specularTexture")
  40304. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40307. ], StandardMaterial.prototype, "specularTexture", void 0);
  40308. __decorate([
  40309. BABYLON.serializeAsTexture("bumpTexture")
  40310. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40311. __decorate([
  40312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40313. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40314. __decorate([
  40315. BABYLON.serializeAsTexture("lightmapTexture")
  40316. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40317. __decorate([
  40318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40319. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40320. __decorate([
  40321. BABYLON.serializeAsTexture("refractionTexture")
  40322. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40323. __decorate([
  40324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40325. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40326. __decorate([
  40327. BABYLON.serializeAsColor3("ambient")
  40328. ], StandardMaterial.prototype, "ambientColor", void 0);
  40329. __decorate([
  40330. BABYLON.serializeAsColor3("diffuse")
  40331. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40332. __decorate([
  40333. BABYLON.serializeAsColor3("specular")
  40334. ], StandardMaterial.prototype, "specularColor", void 0);
  40335. __decorate([
  40336. BABYLON.serializeAsColor3("emissive")
  40337. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40338. __decorate([
  40339. BABYLON.serialize()
  40340. ], StandardMaterial.prototype, "specularPower", void 0);
  40341. __decorate([
  40342. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40343. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40344. __decorate([
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40346. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40347. __decorate([
  40348. BABYLON.serialize("useEmissiveAsIllumination")
  40349. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40350. __decorate([
  40351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40352. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40353. __decorate([
  40354. BABYLON.serialize("linkEmissiveWithDiffuse")
  40355. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40356. __decorate([
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40358. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40359. __decorate([
  40360. BABYLON.serialize("useSpecularOverAlpha")
  40361. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40362. __decorate([
  40363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40364. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40365. __decorate([
  40366. BABYLON.serialize("useReflectionOverAlpha")
  40367. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40368. __decorate([
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40370. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40371. __decorate([
  40372. BABYLON.serialize("disableLighting")
  40373. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40374. __decorate([
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40376. ], StandardMaterial.prototype, "disableLighting", void 0);
  40377. __decorate([
  40378. BABYLON.serialize("useObjectSpaceNormalMap")
  40379. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40380. __decorate([
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40382. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40383. __decorate([
  40384. BABYLON.serialize("useParallax")
  40385. ], StandardMaterial.prototype, "_useParallax", void 0);
  40386. __decorate([
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], StandardMaterial.prototype, "useParallax", void 0);
  40389. __decorate([
  40390. BABYLON.serialize("useParallaxOcclusion")
  40391. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40392. __decorate([
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40395. __decorate([
  40396. BABYLON.serialize()
  40397. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40398. __decorate([
  40399. BABYLON.serialize("roughness")
  40400. ], StandardMaterial.prototype, "_roughness", void 0);
  40401. __decorate([
  40402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40403. ], StandardMaterial.prototype, "roughness", void 0);
  40404. __decorate([
  40405. BABYLON.serialize()
  40406. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40407. __decorate([
  40408. BABYLON.serialize()
  40409. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40410. __decorate([
  40411. BABYLON.serialize("useLightmapAsShadowmap")
  40412. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40413. __decorate([
  40414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40415. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40416. __decorate([
  40417. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40418. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40419. __decorate([
  40420. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40421. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40422. __decorate([
  40423. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40424. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40425. __decorate([
  40426. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40427. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40428. __decorate([
  40429. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40430. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40431. __decorate([
  40432. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40433. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40434. __decorate([
  40435. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40436. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40437. __decorate([
  40438. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40439. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40440. __decorate([
  40441. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40442. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40443. __decorate([
  40444. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40445. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40446. __decorate([
  40447. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40448. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40449. __decorate([
  40450. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40451. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40452. __decorate([
  40453. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40454. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40455. __decorate([
  40456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40457. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40458. __decorate([
  40459. BABYLON.serialize("maxSimultaneousLights")
  40460. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40461. __decorate([
  40462. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40463. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40464. __decorate([
  40465. BABYLON.serialize("invertNormalMapX")
  40466. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40467. __decorate([
  40468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40469. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40470. __decorate([
  40471. BABYLON.serialize("invertNormalMapY")
  40472. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40473. __decorate([
  40474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40475. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40476. __decorate([
  40477. BABYLON.serialize("twoSidedLighting")
  40478. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40479. __decorate([
  40480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40481. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40482. __decorate([
  40483. BABYLON.serialize()
  40484. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40485. return StandardMaterial;
  40486. }(BABYLON.PushMaterial));
  40487. BABYLON.StandardMaterial = StandardMaterial;
  40488. })(BABYLON || (BABYLON = {}));
  40489. //# sourceMappingURL=babylon.standardMaterial.js.map
  40490. var BABYLON;
  40491. (function (BABYLON) {
  40492. /**
  40493. * Manages the defines for the PBR Material.
  40494. */
  40495. var PBRMaterialDefines = /** @class */ (function (_super) {
  40496. __extends(PBRMaterialDefines, _super);
  40497. /**
  40498. * Initializes the PBR Material defines.
  40499. */
  40500. function PBRMaterialDefines() {
  40501. var _this = _super.call(this) || this;
  40502. _this.PBR = true;
  40503. _this.MAINUV1 = false;
  40504. _this.MAINUV2 = false;
  40505. _this.UV1 = false;
  40506. _this.UV2 = false;
  40507. _this.ALBEDO = false;
  40508. _this.ALBEDODIRECTUV = 0;
  40509. _this.VERTEXCOLOR = false;
  40510. _this.AMBIENT = false;
  40511. _this.AMBIENTDIRECTUV = 0;
  40512. _this.AMBIENTINGRAYSCALE = false;
  40513. _this.OPACITY = false;
  40514. _this.VERTEXALPHA = false;
  40515. _this.OPACITYDIRECTUV = 0;
  40516. _this.OPACITYRGB = false;
  40517. _this.ALPHATEST = false;
  40518. _this.DEPTHPREPASS = false;
  40519. _this.ALPHABLEND = false;
  40520. _this.ALPHAFROMALBEDO = false;
  40521. _this.ALPHATESTVALUE = 0.5;
  40522. _this.SPECULAROVERALPHA = false;
  40523. _this.RADIANCEOVERALPHA = false;
  40524. _this.ALPHAFRESNEL = false;
  40525. _this.LINEARALPHAFRESNEL = false;
  40526. _this.PREMULTIPLYALPHA = false;
  40527. _this.EMISSIVE = false;
  40528. _this.EMISSIVEDIRECTUV = 0;
  40529. _this.REFLECTIVITY = false;
  40530. _this.REFLECTIVITYDIRECTUV = 0;
  40531. _this.SPECULARTERM = false;
  40532. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40533. _this.MICROSURFACEAUTOMATIC = false;
  40534. _this.LODBASEDMICROSFURACE = false;
  40535. _this.MICROSURFACEMAP = false;
  40536. _this.MICROSURFACEMAPDIRECTUV = 0;
  40537. _this.METALLICWORKFLOW = false;
  40538. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40539. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40540. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40541. _this.AOSTOREINMETALMAPRED = false;
  40542. _this.ENVIRONMENTBRDF = false;
  40543. _this.NORMAL = false;
  40544. _this.TANGENT = false;
  40545. _this.BUMP = false;
  40546. _this.BUMPDIRECTUV = 0;
  40547. _this.OBJECTSPACE_NORMALMAP = false;
  40548. _this.PARALLAX = false;
  40549. _this.PARALLAXOCCLUSION = false;
  40550. _this.NORMALXYSCALE = true;
  40551. _this.LIGHTMAP = false;
  40552. _this.LIGHTMAPDIRECTUV = 0;
  40553. _this.USELIGHTMAPASSHADOWMAP = false;
  40554. _this.REFLECTION = false;
  40555. _this.REFLECTIONMAP_3D = false;
  40556. _this.REFLECTIONMAP_SPHERICAL = false;
  40557. _this.REFLECTIONMAP_PLANAR = false;
  40558. _this.REFLECTIONMAP_CUBIC = false;
  40559. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40560. _this.REFLECTIONMAP_PROJECTION = false;
  40561. _this.REFLECTIONMAP_SKYBOX = false;
  40562. _this.REFLECTIONMAP_EXPLICIT = false;
  40563. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40564. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40565. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40566. _this.INVERTCUBICMAP = false;
  40567. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40568. _this.USESPHERICALINVERTEX = false;
  40569. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40570. _this.LODINREFLECTIONALPHA = false;
  40571. _this.GAMMAREFLECTION = false;
  40572. _this.RADIANCEOCCLUSION = false;
  40573. _this.HORIZONOCCLUSION = false;
  40574. _this.REFRACTION = false;
  40575. _this.REFRACTIONMAP_3D = false;
  40576. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40577. _this.LODINREFRACTIONALPHA = false;
  40578. _this.GAMMAREFRACTION = false;
  40579. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40580. _this.INSTANCES = false;
  40581. _this.NUM_BONE_INFLUENCERS = 0;
  40582. _this.BonesPerMesh = 0;
  40583. _this.NONUNIFORMSCALING = false;
  40584. _this.MORPHTARGETS = false;
  40585. _this.MORPHTARGETS_NORMAL = false;
  40586. _this.MORPHTARGETS_TANGENT = false;
  40587. _this.NUM_MORPH_INFLUENCERS = 0;
  40588. _this.IMAGEPROCESSING = false;
  40589. _this.VIGNETTE = false;
  40590. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40591. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40592. _this.TONEMAPPING = false;
  40593. _this.CONTRAST = false;
  40594. _this.COLORCURVES = false;
  40595. _this.COLORGRADING = false;
  40596. _this.COLORGRADING3D = false;
  40597. _this.SAMPLER3DGREENDEPTH = false;
  40598. _this.SAMPLER3DBGRMAP = false;
  40599. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40600. _this.EXPOSURE = false;
  40601. _this.GRAIN = false;
  40602. _this.USEPHYSICALLIGHTFALLOFF = false;
  40603. _this.TWOSIDEDLIGHTING = false;
  40604. _this.SHADOWFLOAT = false;
  40605. _this.CLIPPLANE = false;
  40606. _this.POINTSIZE = false;
  40607. _this.FOG = false;
  40608. _this.LOGARITHMICDEPTH = false;
  40609. _this.FORCENORMALFORWARD = false;
  40610. _this.rebuild();
  40611. return _this;
  40612. }
  40613. /**
  40614. * Resets the PBR Material defines.
  40615. */
  40616. PBRMaterialDefines.prototype.reset = function () {
  40617. _super.prototype.reset.call(this);
  40618. this.ALPHATESTVALUE = 0.5;
  40619. this.PBR = true;
  40620. };
  40621. return PBRMaterialDefines;
  40622. }(BABYLON.MaterialDefines));
  40623. /**
  40624. * The Physically based material base class of BJS.
  40625. *
  40626. * This offers the main features of a standard PBR material.
  40627. * For more information, please refer to the documentation :
  40628. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40629. */
  40630. var PBRBaseMaterial = /** @class */ (function (_super) {
  40631. __extends(PBRBaseMaterial, _super);
  40632. /**
  40633. * Instantiates a new PBRMaterial instance.
  40634. *
  40635. * @param name The material name
  40636. * @param scene The scene the material will be use in.
  40637. */
  40638. function PBRBaseMaterial(name, scene) {
  40639. var _this = _super.call(this, name, scene) || this;
  40640. /**
  40641. * Intensity of the direct lights e.g. the four lights available in your scene.
  40642. * This impacts both the direct diffuse and specular highlights.
  40643. */
  40644. _this._directIntensity = 1.0;
  40645. /**
  40646. * Intensity of the emissive part of the material.
  40647. * This helps controlling the emissive effect without modifying the emissive color.
  40648. */
  40649. _this._emissiveIntensity = 1.0;
  40650. /**
  40651. * Intensity of the environment e.g. how much the environment will light the object
  40652. * either through harmonics for rough material or through the refelction for shiny ones.
  40653. */
  40654. _this._environmentIntensity = 1.0;
  40655. /**
  40656. * This is a special control allowing the reduction of the specular highlights coming from the
  40657. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40658. */
  40659. _this._specularIntensity = 1.0;
  40660. /**
  40661. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40662. */
  40663. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40664. /**
  40665. * Debug Control allowing disabling the bump map on this material.
  40666. */
  40667. _this._disableBumpMap = false;
  40668. /**
  40669. * AKA Occlusion Texture Intensity in other nomenclature.
  40670. */
  40671. _this._ambientTextureStrength = 1.0;
  40672. /**
  40673. * The color of a material in ambient lighting.
  40674. */
  40675. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40676. /**
  40677. * AKA Diffuse Color in other nomenclature.
  40678. */
  40679. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40680. /**
  40681. * AKA Specular Color in other nomenclature.
  40682. */
  40683. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40684. /**
  40685. * The color applied when light is reflected from a material.
  40686. */
  40687. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40688. /**
  40689. * The color applied when light is emitted from a material.
  40690. */
  40691. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40692. /**
  40693. * AKA Glossiness in other nomenclature.
  40694. */
  40695. _this._microSurface = 0.9;
  40696. /**
  40697. * source material index of refraction (IOR)' / 'destination material IOR.
  40698. */
  40699. _this._indexOfRefraction = 0.66;
  40700. /**
  40701. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40702. */
  40703. _this._invertRefractionY = false;
  40704. /**
  40705. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40706. * Materials half opaque for instance using refraction could benefit from this control.
  40707. */
  40708. _this._linkRefractionWithTransparency = false;
  40709. /**
  40710. * Specifies that the material will use the light map as a show map.
  40711. */
  40712. _this._useLightmapAsShadowmap = false;
  40713. /**
  40714. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40715. * makes the reflect vector face the model (under horizon).
  40716. */
  40717. _this._useHorizonOcclusion = true;
  40718. /**
  40719. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40720. * too much the area relying on ambient texture to define their ambient occlusion.
  40721. */
  40722. _this._useRadianceOcclusion = true;
  40723. /**
  40724. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40725. */
  40726. _this._useAlphaFromAlbedoTexture = false;
  40727. /**
  40728. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40729. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40730. */
  40731. _this._useSpecularOverAlpha = true;
  40732. /**
  40733. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40734. */
  40735. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40736. /**
  40737. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40738. */
  40739. _this._useRoughnessFromMetallicTextureAlpha = true;
  40740. /**
  40741. * Specifies if the metallic texture contains the roughness information in its green channel.
  40742. */
  40743. _this._useRoughnessFromMetallicTextureGreen = false;
  40744. /**
  40745. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40746. */
  40747. _this._useMetallnessFromMetallicTextureBlue = false;
  40748. /**
  40749. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40750. */
  40751. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40752. /**
  40753. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40754. */
  40755. _this._useAmbientInGrayScale = false;
  40756. /**
  40757. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40758. * The material will try to infer what glossiness each pixel should be.
  40759. */
  40760. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40761. /**
  40762. * BJS is using an harcoded light falloff based on a manually sets up range.
  40763. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40764. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40765. */
  40766. _this._usePhysicalLightFalloff = true;
  40767. /**
  40768. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40769. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40770. */
  40771. _this._useRadianceOverAlpha = true;
  40772. /**
  40773. * Allows using an object space normal map (instead of tangent space).
  40774. */
  40775. _this._useObjectSpaceNormalMap = false;
  40776. /**
  40777. * Allows using the bump map in parallax mode.
  40778. */
  40779. _this._useParallax = false;
  40780. /**
  40781. * Allows using the bump map in parallax occlusion mode.
  40782. */
  40783. _this._useParallaxOcclusion = false;
  40784. /**
  40785. * Controls the scale bias of the parallax mode.
  40786. */
  40787. _this._parallaxScaleBias = 0.05;
  40788. /**
  40789. * If sets to true, disables all the lights affecting the material.
  40790. */
  40791. _this._disableLighting = false;
  40792. /**
  40793. * Number of Simultaneous lights allowed on the material.
  40794. */
  40795. _this._maxSimultaneousLights = 4;
  40796. /**
  40797. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40798. */
  40799. _this._invertNormalMapX = false;
  40800. /**
  40801. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40802. */
  40803. _this._invertNormalMapY = false;
  40804. /**
  40805. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40806. */
  40807. _this._twoSidedLighting = false;
  40808. /**
  40809. * Defines the alpha limits in alpha test mode.
  40810. */
  40811. _this._alphaCutOff = 0.4;
  40812. /**
  40813. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40814. */
  40815. _this._forceAlphaTest = false;
  40816. /**
  40817. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40818. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40819. */
  40820. _this._useAlphaFresnel = false;
  40821. /**
  40822. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40823. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40824. */
  40825. _this._useLinearAlphaFresnel = false;
  40826. /**
  40827. * The transparency mode of the material.
  40828. */
  40829. _this._transparencyMode = null;
  40830. /**
  40831. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40832. * from cos thetav and roughness:
  40833. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40834. */
  40835. _this._environmentBRDFTexture = null;
  40836. /**
  40837. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40838. */
  40839. _this._forceIrradianceInFragment = false;
  40840. /**
  40841. * Force normal to face away from face.
  40842. */
  40843. _this._forceNormalForward = false;
  40844. /**
  40845. * Stores the available render targets.
  40846. */
  40847. _this._renderTargets = new BABYLON.SmartArray(16);
  40848. /**
  40849. * Sets the global ambient color for the material used in lighting calculations.
  40850. */
  40851. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40852. // Setup the default processing configuration to the scene.
  40853. _this._attachImageProcessingConfiguration(null);
  40854. _this.getRenderTargetTextures = function () {
  40855. _this._renderTargets.reset();
  40856. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40857. _this._renderTargets.push(_this._reflectionTexture);
  40858. }
  40859. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40860. _this._renderTargets.push(_this._refractionTexture);
  40861. }
  40862. return _this._renderTargets;
  40863. };
  40864. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40865. return _this;
  40866. }
  40867. /**
  40868. * Attaches a new image processing configuration to the PBR Material.
  40869. * @param configuration
  40870. */
  40871. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40872. var _this = this;
  40873. if (configuration === this._imageProcessingConfiguration) {
  40874. return;
  40875. }
  40876. // Detaches observer.
  40877. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40878. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40879. }
  40880. // Pick the scene configuration if needed.
  40881. if (!configuration) {
  40882. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40883. }
  40884. else {
  40885. this._imageProcessingConfiguration = configuration;
  40886. }
  40887. // Attaches observer.
  40888. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40889. _this._markAllSubMeshesAsImageProcessingDirty();
  40890. });
  40891. };
  40892. /**
  40893. * Gets the name of the material class.
  40894. */
  40895. PBRBaseMaterial.prototype.getClassName = function () {
  40896. return "PBRBaseMaterial";
  40897. };
  40898. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40899. /**
  40900. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40901. */
  40902. get: function () {
  40903. return this._useLogarithmicDepth;
  40904. },
  40905. /**
  40906. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40907. */
  40908. set: function (value) {
  40909. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40910. },
  40911. enumerable: true,
  40912. configurable: true
  40913. });
  40914. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40915. /**
  40916. * Gets the current transparency mode.
  40917. */
  40918. get: function () {
  40919. return this._transparencyMode;
  40920. },
  40921. /**
  40922. * Sets the transparency mode of the material.
  40923. */
  40924. set: function (value) {
  40925. if (this._transparencyMode === value) {
  40926. return;
  40927. }
  40928. this._transparencyMode = value;
  40929. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40930. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40936. /**
  40937. * Returns true if alpha blending should be disabled.
  40938. */
  40939. get: function () {
  40940. return (this._linkRefractionWithTransparency ||
  40941. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40942. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40943. },
  40944. enumerable: true,
  40945. configurable: true
  40946. });
  40947. /**
  40948. * Specifies whether or not this material should be rendered in alpha blend mode.
  40949. */
  40950. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40951. if (this._disableAlphaBlending) {
  40952. return false;
  40953. }
  40954. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40955. };
  40956. /**
  40957. * Specifies if the mesh will require alpha blending.
  40958. * @param mesh - BJS mesh.
  40959. */
  40960. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40961. if (this._disableAlphaBlending) {
  40962. return false;
  40963. }
  40964. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40965. };
  40966. /**
  40967. * Specifies whether or not this material should be rendered in alpha test mode.
  40968. */
  40969. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40970. if (this._forceAlphaTest) {
  40971. return true;
  40972. }
  40973. if (this._linkRefractionWithTransparency) {
  40974. return false;
  40975. }
  40976. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40977. };
  40978. /**
  40979. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40980. */
  40981. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40982. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40983. };
  40984. /**
  40985. * Gets the texture used for the alpha test.
  40986. */
  40987. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40988. return this._albedoTexture;
  40989. };
  40990. /**
  40991. * Specifies that the submesh is ready to be used.
  40992. * @param mesh - BJS mesh.
  40993. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40994. * @param useInstances - Specifies that instances should be used.
  40995. * @returns - boolean indicating that the submesh is ready or not.
  40996. */
  40997. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40998. if (subMesh.effect && this.isFrozen) {
  40999. if (this._wasPreviouslyReady) {
  41000. return true;
  41001. }
  41002. }
  41003. if (!subMesh._materialDefines) {
  41004. subMesh._materialDefines = new PBRMaterialDefines();
  41005. }
  41006. var defines = subMesh._materialDefines;
  41007. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41008. if (defines._renderId === this.getScene().getRenderId()) {
  41009. return true;
  41010. }
  41011. }
  41012. var scene = this.getScene();
  41013. var engine = scene.getEngine();
  41014. if (defines._areTexturesDirty) {
  41015. if (scene.texturesEnabled) {
  41016. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41017. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41018. return false;
  41019. }
  41020. }
  41021. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41022. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41023. return false;
  41024. }
  41025. }
  41026. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41027. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41028. return false;
  41029. }
  41030. }
  41031. var reflectionTexture = this._getReflectionTexture();
  41032. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41033. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41034. return false;
  41035. }
  41036. }
  41037. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41038. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41039. return false;
  41040. }
  41041. }
  41042. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41043. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41044. return false;
  41045. }
  41046. }
  41047. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41048. if (this._metallicTexture) {
  41049. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41050. return false;
  41051. }
  41052. }
  41053. else if (this._reflectivityTexture) {
  41054. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41055. return false;
  41056. }
  41057. }
  41058. if (this._microSurfaceTexture) {
  41059. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41060. return false;
  41061. }
  41062. }
  41063. }
  41064. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41065. // Bump texture cannot be not blocking.
  41066. if (!this._bumpTexture.isReady()) {
  41067. return false;
  41068. }
  41069. }
  41070. var refractionTexture = this._getRefractionTexture();
  41071. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41072. if (!refractionTexture.isReadyOrNotBlocking()) {
  41073. return false;
  41074. }
  41075. }
  41076. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41077. // This is blocking.
  41078. if (!this._environmentBRDFTexture.isReady()) {
  41079. return false;
  41080. }
  41081. }
  41082. }
  41083. }
  41084. if (defines._areImageProcessingDirty) {
  41085. if (!this._imageProcessingConfiguration.isReady()) {
  41086. return false;
  41087. }
  41088. }
  41089. if (!engine.getCaps().standardDerivatives) {
  41090. var bufferMesh = null;
  41091. if (mesh.getClassName() === "InstancedMesh") {
  41092. bufferMesh = mesh.sourceMesh;
  41093. }
  41094. else if (mesh.getClassName() === "Mesh") {
  41095. bufferMesh = mesh;
  41096. }
  41097. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41098. bufferMesh.createNormals(true);
  41099. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41100. }
  41101. }
  41102. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41103. if (effect) {
  41104. scene.resetCachedMaterial();
  41105. subMesh.setEffect(effect, defines);
  41106. this.buildUniformLayout();
  41107. }
  41108. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41109. return false;
  41110. }
  41111. defines._renderId = scene.getRenderId();
  41112. this._wasPreviouslyReady = true;
  41113. return true;
  41114. };
  41115. /**
  41116. * Specifies if the material uses metallic roughness workflow.
  41117. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41118. */
  41119. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41120. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41121. return true;
  41122. }
  41123. return false;
  41124. };
  41125. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41126. if (onCompiled === void 0) { onCompiled = null; }
  41127. if (onError === void 0) { onError = null; }
  41128. if (useInstances === void 0) { useInstances = null; }
  41129. if (useClipPlane === void 0) { useClipPlane = null; }
  41130. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41131. if (!defines.isDirty) {
  41132. return null;
  41133. }
  41134. defines.markAsProcessed();
  41135. var scene = this.getScene();
  41136. var engine = scene.getEngine();
  41137. // Fallbacks
  41138. var fallbacks = new BABYLON.EffectFallbacks();
  41139. var fallbackRank = 0;
  41140. if (defines.USESPHERICALINVERTEX) {
  41141. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41142. }
  41143. if (defines.FOG) {
  41144. fallbacks.addFallback(fallbackRank, "FOG");
  41145. }
  41146. if (defines.POINTSIZE) {
  41147. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41148. }
  41149. if (defines.LOGARITHMICDEPTH) {
  41150. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41151. }
  41152. if (defines.PARALLAX) {
  41153. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41154. }
  41155. if (defines.PARALLAXOCCLUSION) {
  41156. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41157. }
  41158. if (defines.ENVIRONMENTBRDF) {
  41159. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41160. }
  41161. if (defines.TANGENT) {
  41162. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41163. }
  41164. if (defines.BUMP) {
  41165. fallbacks.addFallback(fallbackRank++, "BUMP");
  41166. }
  41167. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41168. if (defines.SPECULARTERM) {
  41169. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41170. }
  41171. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41172. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41173. }
  41174. if (defines.LIGHTMAP) {
  41175. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41176. }
  41177. if (defines.NORMAL) {
  41178. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41179. }
  41180. if (defines.AMBIENT) {
  41181. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41182. }
  41183. if (defines.EMISSIVE) {
  41184. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41185. }
  41186. if (defines.VERTEXCOLOR) {
  41187. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41188. }
  41189. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41190. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41191. }
  41192. if (defines.MORPHTARGETS) {
  41193. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41194. }
  41195. //Attributes
  41196. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41197. if (defines.NORMAL) {
  41198. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41199. }
  41200. if (defines.TANGENT) {
  41201. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41202. }
  41203. if (defines.UV1) {
  41204. attribs.push(BABYLON.VertexBuffer.UVKind);
  41205. }
  41206. if (defines.UV2) {
  41207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41208. }
  41209. if (defines.VERTEXCOLOR) {
  41210. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41211. }
  41212. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41213. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41214. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41215. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41216. "vFogInfos", "vFogColor", "pointSize",
  41217. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41218. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41219. "mBones",
  41220. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41221. "vLightingIntensity",
  41222. "logarithmicDepthConstant",
  41223. "vSphericalX", "vSphericalY", "vSphericalZ",
  41224. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41225. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41226. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41227. "vTangentSpaceParams"
  41228. ];
  41229. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41230. "bumpSampler", "lightmapSampler", "opacitySampler",
  41231. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41232. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41233. "microSurfaceSampler", "environmentBrdfSampler"];
  41234. var uniformBuffers = ["Material", "Scene"];
  41235. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41236. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41237. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41238. uniformsNames: uniforms,
  41239. uniformBuffersNames: uniformBuffers,
  41240. samplers: samplers,
  41241. defines: defines,
  41242. maxSimultaneousLights: this._maxSimultaneousLights
  41243. });
  41244. var join = defines.toString();
  41245. return engine.createEffect("pbr", {
  41246. attributes: attribs,
  41247. uniformsNames: uniforms,
  41248. uniformBuffersNames: uniformBuffers,
  41249. samplers: samplers,
  41250. defines: join,
  41251. fallbacks: fallbacks,
  41252. onCompiled: onCompiled,
  41253. onError: onError,
  41254. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41255. }, engine);
  41256. };
  41257. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41258. if (useInstances === void 0) { useInstances = null; }
  41259. if (useClipPlane === void 0) { useClipPlane = null; }
  41260. var scene = this.getScene();
  41261. var engine = scene.getEngine();
  41262. // Lights
  41263. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41264. defines._needNormals = true;
  41265. // Textures
  41266. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41267. if (defines._areTexturesDirty) {
  41268. defines._needUVs = false;
  41269. if (scene.texturesEnabled) {
  41270. if (scene.getEngine().getCaps().textureLOD) {
  41271. defines.LODBASEDMICROSFURACE = true;
  41272. }
  41273. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41275. }
  41276. else {
  41277. defines.ALBEDO = false;
  41278. }
  41279. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41280. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41281. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41282. }
  41283. else {
  41284. defines.AMBIENT = false;
  41285. }
  41286. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41288. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41289. }
  41290. else {
  41291. defines.OPACITY = false;
  41292. }
  41293. var reflectionTexture = this._getReflectionTexture();
  41294. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41295. defines.REFLECTION = true;
  41296. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41297. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41298. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41299. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41300. defines.INVERTCUBICMAP = true;
  41301. }
  41302. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41303. switch (reflectionTexture.coordinatesMode) {
  41304. case BABYLON.Texture.CUBIC_MODE:
  41305. case BABYLON.Texture.INVCUBIC_MODE:
  41306. defines.REFLECTIONMAP_CUBIC = true;
  41307. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41308. break;
  41309. case BABYLON.Texture.EXPLICIT_MODE:
  41310. defines.REFLECTIONMAP_EXPLICIT = true;
  41311. break;
  41312. case BABYLON.Texture.PLANAR_MODE:
  41313. defines.REFLECTIONMAP_PLANAR = true;
  41314. break;
  41315. case BABYLON.Texture.PROJECTION_MODE:
  41316. defines.REFLECTIONMAP_PROJECTION = true;
  41317. break;
  41318. case BABYLON.Texture.SKYBOX_MODE:
  41319. defines.REFLECTIONMAP_SKYBOX = true;
  41320. break;
  41321. case BABYLON.Texture.SPHERICAL_MODE:
  41322. defines.REFLECTIONMAP_SPHERICAL = true;
  41323. break;
  41324. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41325. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41326. break;
  41327. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41328. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41329. break;
  41330. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41331. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41332. break;
  41333. }
  41334. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41335. if (reflectionTexture.sphericalPolynomial) {
  41336. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41337. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41338. defines.USESPHERICALINVERTEX = false;
  41339. }
  41340. else {
  41341. defines.USESPHERICALINVERTEX = true;
  41342. }
  41343. }
  41344. }
  41345. }
  41346. else {
  41347. defines.REFLECTION = false;
  41348. defines.REFLECTIONMAP_3D = false;
  41349. defines.REFLECTIONMAP_SPHERICAL = false;
  41350. defines.REFLECTIONMAP_PLANAR = false;
  41351. defines.REFLECTIONMAP_CUBIC = false;
  41352. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41353. defines.REFLECTIONMAP_PROJECTION = false;
  41354. defines.REFLECTIONMAP_SKYBOX = false;
  41355. defines.REFLECTIONMAP_EXPLICIT = false;
  41356. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41357. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41358. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41359. defines.INVERTCUBICMAP = false;
  41360. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41361. defines.USESPHERICALINVERTEX = false;
  41362. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41363. defines.LODINREFLECTIONALPHA = false;
  41364. defines.GAMMAREFLECTION = false;
  41365. }
  41366. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41367. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41368. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41369. }
  41370. else {
  41371. defines.LIGHTMAP = false;
  41372. }
  41373. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41375. }
  41376. else {
  41377. defines.EMISSIVE = false;
  41378. }
  41379. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41380. if (this._metallicTexture) {
  41381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41382. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41383. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41384. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41385. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41386. }
  41387. else if (this._reflectivityTexture) {
  41388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41389. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41390. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41391. }
  41392. else {
  41393. defines.REFLECTIVITY = false;
  41394. }
  41395. if (this._microSurfaceTexture) {
  41396. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41397. }
  41398. else {
  41399. defines.MICROSURFACEMAP = false;
  41400. }
  41401. }
  41402. else {
  41403. defines.REFLECTIVITY = false;
  41404. defines.MICROSURFACEMAP = false;
  41405. }
  41406. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41408. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41409. defines.PARALLAX = true;
  41410. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41411. }
  41412. else {
  41413. defines.PARALLAX = false;
  41414. }
  41415. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41416. }
  41417. else {
  41418. defines.BUMP = false;
  41419. }
  41420. var refractionTexture = this._getRefractionTexture();
  41421. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41422. defines.REFRACTION = true;
  41423. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41424. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41425. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41426. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41427. if (this._linkRefractionWithTransparency) {
  41428. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41429. }
  41430. }
  41431. else {
  41432. defines.REFRACTION = false;
  41433. }
  41434. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41435. defines.ENVIRONMENTBRDF = true;
  41436. }
  41437. else {
  41438. defines.ENVIRONMENTBRDF = false;
  41439. }
  41440. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41441. defines.ALPHAFROMALBEDO = true;
  41442. }
  41443. else {
  41444. defines.ALPHAFROMALBEDO = false;
  41445. }
  41446. }
  41447. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41448. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41449. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41450. if (!this.backFaceCulling && this._twoSidedLighting) {
  41451. defines.TWOSIDEDLIGHTING = true;
  41452. }
  41453. else {
  41454. defines.TWOSIDEDLIGHTING = false;
  41455. }
  41456. defines.ALPHATESTVALUE = this._alphaCutOff;
  41457. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41458. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41459. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41460. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41461. }
  41462. if (defines._areImageProcessingDirty) {
  41463. this._imageProcessingConfiguration.prepareDefines(defines);
  41464. }
  41465. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41466. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41467. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41468. // Misc.
  41469. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41470. // Values that need to be evaluated on every frame
  41471. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41472. // Attribs
  41473. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41474. };
  41475. /**
  41476. * Force shader compilation
  41477. */
  41478. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41479. var _this = this;
  41480. var localOptions = __assign({ clipPlane: false }, options);
  41481. var defines = new PBRMaterialDefines();
  41482. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41483. if (effect.isReady()) {
  41484. if (onCompiled) {
  41485. onCompiled(this);
  41486. }
  41487. }
  41488. else {
  41489. effect.onCompileObservable.add(function () {
  41490. if (onCompiled) {
  41491. onCompiled(_this);
  41492. }
  41493. });
  41494. }
  41495. };
  41496. /**
  41497. * Initializes the uniform buffer layout for the shader.
  41498. */
  41499. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41500. // Order is important !
  41501. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41502. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41503. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41504. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41505. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41506. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41507. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41508. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41509. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41510. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41511. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41512. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41513. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41514. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41515. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41516. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41517. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41518. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41519. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41520. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41521. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41522. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41523. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41524. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41525. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41526. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41527. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41528. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41529. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41530. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41531. this._uniformBuffer.addUniform("pointSize", 1);
  41532. this._uniformBuffer.create();
  41533. };
  41534. /**
  41535. * Unbinds the textures.
  41536. */
  41537. PBRBaseMaterial.prototype.unbind = function () {
  41538. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41539. this._uniformBuffer.setTexture("reflectionSampler", null);
  41540. }
  41541. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41542. this._uniformBuffer.setTexture("refractionSampler", null);
  41543. }
  41544. _super.prototype.unbind.call(this);
  41545. };
  41546. /**
  41547. * Binds the submesh data.
  41548. * @param world - The world matrix.
  41549. * @param mesh - The BJS mesh.
  41550. * @param subMesh - A submesh of the BJS mesh.
  41551. */
  41552. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41553. var scene = this.getScene();
  41554. var defines = subMesh._materialDefines;
  41555. if (!defines) {
  41556. return;
  41557. }
  41558. var effect = subMesh.effect;
  41559. if (!effect) {
  41560. return;
  41561. }
  41562. this._activeEffect = effect;
  41563. // Matrices
  41564. this.bindOnlyWorldMatrix(world);
  41565. // Normal Matrix
  41566. if (defines.OBJECTSPACE_NORMALMAP) {
  41567. world.toNormalMatrix(this._normalMatrix);
  41568. this.bindOnlyNormalMatrix(this._normalMatrix);
  41569. }
  41570. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41571. // Bones
  41572. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41573. var reflectionTexture = null;
  41574. if (mustRebind) {
  41575. this._uniformBuffer.bindToEffect(effect, "Material");
  41576. this.bindViewProjection(effect);
  41577. reflectionTexture = this._getReflectionTexture();
  41578. var refractionTexture = this._getRefractionTexture();
  41579. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41580. // Texture uniforms
  41581. if (scene.texturesEnabled) {
  41582. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41583. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41584. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41585. }
  41586. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41587. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41588. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41589. }
  41590. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41591. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41592. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41593. }
  41594. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41595. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41596. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41597. if (reflectionTexture.boundingBoxSize) {
  41598. var cubeTexture = reflectionTexture;
  41599. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41600. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41601. }
  41602. var polynomials = reflectionTexture.sphericalPolynomial;
  41603. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41604. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41605. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41606. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41607. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41608. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41609. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41610. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41611. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41612. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41613. }
  41614. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41615. }
  41616. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41617. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41618. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41619. }
  41620. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41621. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41622. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41623. }
  41624. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41625. if (this._metallicTexture) {
  41626. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41627. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41628. }
  41629. else if (this._reflectivityTexture) {
  41630. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41631. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41632. }
  41633. if (this._microSurfaceTexture) {
  41634. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41635. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41636. }
  41637. }
  41638. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41639. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41640. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41641. if (scene._mirroredCameraPosition) {
  41642. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41643. }
  41644. else {
  41645. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41646. }
  41647. }
  41648. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41649. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41650. var depth = 1.0;
  41651. if (!refractionTexture.isCube) {
  41652. if (refractionTexture.depth) {
  41653. depth = refractionTexture.depth;
  41654. }
  41655. }
  41656. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41657. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41658. }
  41659. }
  41660. // Point size
  41661. if (this.pointsCloud) {
  41662. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41663. }
  41664. // Colors
  41665. if (defines.METALLICWORKFLOW) {
  41666. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41667. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41668. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41669. }
  41670. else {
  41671. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41672. }
  41673. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41674. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41675. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41676. // Misc
  41677. this._lightingInfos.x = this._directIntensity;
  41678. this._lightingInfos.y = this._emissiveIntensity;
  41679. this._lightingInfos.z = this._environmentIntensity;
  41680. this._lightingInfos.w = this._specularIntensity;
  41681. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41682. }
  41683. // Textures
  41684. if (scene.texturesEnabled) {
  41685. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41686. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41687. }
  41688. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41689. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41690. }
  41691. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41692. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41693. }
  41694. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41695. if (defines.LODBASEDMICROSFURACE) {
  41696. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41697. }
  41698. else {
  41699. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41700. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41701. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41702. }
  41703. }
  41704. if (defines.ENVIRONMENTBRDF) {
  41705. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41706. }
  41707. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41708. if (defines.LODBASEDMICROSFURACE) {
  41709. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41710. }
  41711. else {
  41712. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41713. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41714. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41715. }
  41716. }
  41717. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41718. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41719. }
  41720. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41721. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41722. }
  41723. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41724. if (this._metallicTexture) {
  41725. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41726. }
  41727. else if (this._reflectivityTexture) {
  41728. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41729. }
  41730. if (this._microSurfaceTexture) {
  41731. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41732. }
  41733. }
  41734. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41735. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41736. }
  41737. }
  41738. // Clip plane
  41739. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41740. // Colors
  41741. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41742. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41743. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41744. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41745. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41746. }
  41747. if (mustRebind || !this.isFrozen) {
  41748. // Lights
  41749. if (scene.lightsEnabled && !this._disableLighting) {
  41750. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41751. }
  41752. // View
  41753. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41754. this.bindView(effect);
  41755. }
  41756. // Fog
  41757. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41758. // Morph targets
  41759. if (defines.NUM_MORPH_INFLUENCERS) {
  41760. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41761. }
  41762. // image processing
  41763. this._imageProcessingConfiguration.bind(this._activeEffect);
  41764. // Log. depth
  41765. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41766. }
  41767. this._uniformBuffer.update();
  41768. this._afterBind(mesh);
  41769. };
  41770. /**
  41771. * Returns the animatable textures.
  41772. * @returns - Array of animatable textures.
  41773. */
  41774. PBRBaseMaterial.prototype.getAnimatables = function () {
  41775. var results = [];
  41776. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41777. results.push(this._albedoTexture);
  41778. }
  41779. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41780. results.push(this._ambientTexture);
  41781. }
  41782. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41783. results.push(this._opacityTexture);
  41784. }
  41785. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41786. results.push(this._reflectionTexture);
  41787. }
  41788. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41789. results.push(this._emissiveTexture);
  41790. }
  41791. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41792. results.push(this._metallicTexture);
  41793. }
  41794. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41795. results.push(this._reflectivityTexture);
  41796. }
  41797. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41798. results.push(this._bumpTexture);
  41799. }
  41800. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41801. results.push(this._lightmapTexture);
  41802. }
  41803. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41804. results.push(this._refractionTexture);
  41805. }
  41806. return results;
  41807. };
  41808. /**
  41809. * Returns the texture used for reflections.
  41810. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41811. */
  41812. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41813. if (this._reflectionTexture) {
  41814. return this._reflectionTexture;
  41815. }
  41816. return this.getScene().environmentTexture;
  41817. };
  41818. /**
  41819. * Returns the texture used for refraction or null if none is used.
  41820. * @returns - Refection texture if present. If no refraction texture and refraction
  41821. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41822. */
  41823. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41824. if (this._refractionTexture) {
  41825. return this._refractionTexture;
  41826. }
  41827. if (this._linkRefractionWithTransparency) {
  41828. return this.getScene().environmentTexture;
  41829. }
  41830. return null;
  41831. };
  41832. /**
  41833. * Disposes the resources of the material.
  41834. * @param forceDisposeEffect - Forces the disposal of effects.
  41835. * @param forceDisposeTextures - Forces the disposal of all textures.
  41836. */
  41837. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41838. if (forceDisposeTextures) {
  41839. if (this._albedoTexture) {
  41840. this._albedoTexture.dispose();
  41841. }
  41842. if (this._ambientTexture) {
  41843. this._ambientTexture.dispose();
  41844. }
  41845. if (this._opacityTexture) {
  41846. this._opacityTexture.dispose();
  41847. }
  41848. if (this._reflectionTexture) {
  41849. this._reflectionTexture.dispose();
  41850. }
  41851. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41852. this._environmentBRDFTexture.dispose();
  41853. }
  41854. if (this._emissiveTexture) {
  41855. this._emissiveTexture.dispose();
  41856. }
  41857. if (this._metallicTexture) {
  41858. this._metallicTexture.dispose();
  41859. }
  41860. if (this._reflectivityTexture) {
  41861. this._reflectivityTexture.dispose();
  41862. }
  41863. if (this._bumpTexture) {
  41864. this._bumpTexture.dispose();
  41865. }
  41866. if (this._lightmapTexture) {
  41867. this._lightmapTexture.dispose();
  41868. }
  41869. if (this._refractionTexture) {
  41870. this._refractionTexture.dispose();
  41871. }
  41872. }
  41873. this._renderTargets.dispose();
  41874. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41875. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41876. }
  41877. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41878. };
  41879. /**
  41880. * Stores the reflectivity values based on metallic roughness workflow.
  41881. */
  41882. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41883. __decorate([
  41884. BABYLON.serializeAsImageProcessingConfiguration()
  41885. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41886. __decorate([
  41887. BABYLON.serialize()
  41888. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41889. __decorate([
  41890. BABYLON.serialize()
  41891. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41892. return PBRBaseMaterial;
  41893. }(BABYLON.PushMaterial));
  41894. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41895. })(BABYLON || (BABYLON = {}));
  41896. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41897. var BABYLON;
  41898. (function (BABYLON) {
  41899. /**
  41900. * The Physically based simple base material of BJS.
  41901. *
  41902. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41903. * It is used as the base class for both the specGloss and metalRough conventions.
  41904. */
  41905. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41906. __extends(PBRBaseSimpleMaterial, _super);
  41907. /**
  41908. * Instantiates a new PBRMaterial instance.
  41909. *
  41910. * @param name The material name
  41911. * @param scene The scene the material will be use in.
  41912. */
  41913. function PBRBaseSimpleMaterial(name, scene) {
  41914. var _this = _super.call(this, name, scene) || this;
  41915. /**
  41916. * Number of Simultaneous lights allowed on the material.
  41917. */
  41918. _this.maxSimultaneousLights = 4;
  41919. /**
  41920. * If sets to true, disables all the lights affecting the material.
  41921. */
  41922. _this.disableLighting = false;
  41923. /**
  41924. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41925. */
  41926. _this.invertNormalMapX = false;
  41927. /**
  41928. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41929. */
  41930. _this.invertNormalMapY = false;
  41931. /**
  41932. * Emissivie color used to self-illuminate the model.
  41933. */
  41934. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41935. /**
  41936. * Occlusion Channel Strenght.
  41937. */
  41938. _this.occlusionStrength = 1.0;
  41939. _this.useLightmapAsShadowmap = false;
  41940. _this._useAlphaFromAlbedoTexture = true;
  41941. _this._useAmbientInGrayScale = true;
  41942. return _this;
  41943. }
  41944. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41945. /**
  41946. * Gets the current double sided mode.
  41947. */
  41948. get: function () {
  41949. return this._twoSidedLighting;
  41950. },
  41951. /**
  41952. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41953. */
  41954. set: function (value) {
  41955. if (this._twoSidedLighting === value) {
  41956. return;
  41957. }
  41958. this._twoSidedLighting = value;
  41959. this.backFaceCulling = !value;
  41960. this._markAllSubMeshesAsTexturesDirty();
  41961. },
  41962. enumerable: true,
  41963. configurable: true
  41964. });
  41965. /**
  41966. * Return the active textures of the material.
  41967. */
  41968. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41969. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41970. if (this.environmentTexture) {
  41971. activeTextures.push(this.environmentTexture);
  41972. }
  41973. if (this.normalTexture) {
  41974. activeTextures.push(this.normalTexture);
  41975. }
  41976. if (this.emissiveTexture) {
  41977. activeTextures.push(this.emissiveTexture);
  41978. }
  41979. if (this.occlusionTexture) {
  41980. activeTextures.push(this.occlusionTexture);
  41981. }
  41982. if (this.lightmapTexture) {
  41983. activeTextures.push(this.lightmapTexture);
  41984. }
  41985. return activeTextures;
  41986. };
  41987. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41988. if (_super.prototype.hasTexture.call(this, texture)) {
  41989. return true;
  41990. }
  41991. if (this.lightmapTexture === texture) {
  41992. return true;
  41993. }
  41994. return false;
  41995. };
  41996. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41997. return "PBRBaseSimpleMaterial";
  41998. };
  41999. __decorate([
  42000. BABYLON.serialize(),
  42001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42002. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42003. __decorate([
  42004. BABYLON.serialize(),
  42005. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42006. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42007. __decorate([
  42008. BABYLON.serializeAsTexture(),
  42009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42010. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42011. __decorate([
  42012. BABYLON.serialize(),
  42013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42014. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42015. __decorate([
  42016. BABYLON.serialize(),
  42017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42018. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42019. __decorate([
  42020. BABYLON.serializeAsTexture(),
  42021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42022. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42023. __decorate([
  42024. BABYLON.serializeAsColor3("emissive"),
  42025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42026. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42027. __decorate([
  42028. BABYLON.serializeAsTexture(),
  42029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42030. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42031. __decorate([
  42032. BABYLON.serialize(),
  42033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42034. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42035. __decorate([
  42036. BABYLON.serializeAsTexture(),
  42037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42038. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42039. __decorate([
  42040. BABYLON.serialize(),
  42041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42042. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42043. __decorate([
  42044. BABYLON.serialize()
  42045. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42046. __decorate([
  42047. BABYLON.serializeAsTexture(),
  42048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42049. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42050. __decorate([
  42051. BABYLON.serialize(),
  42052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42053. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42054. return PBRBaseSimpleMaterial;
  42055. }(BABYLON.PBRBaseMaterial));
  42056. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42057. })(BABYLON || (BABYLON = {}));
  42058. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42059. var BABYLON;
  42060. (function (BABYLON) {
  42061. /**
  42062. * The Physically based material of BJS.
  42063. *
  42064. * This offers the main features of a standard PBR material.
  42065. * For more information, please refer to the documentation :
  42066. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42067. */
  42068. var PBRMaterial = /** @class */ (function (_super) {
  42069. __extends(PBRMaterial, _super);
  42070. /**
  42071. * Instantiates a new PBRMaterial instance.
  42072. *
  42073. * @param name The material name
  42074. * @param scene The scene the material will be use in.
  42075. */
  42076. function PBRMaterial(name, scene) {
  42077. var _this = _super.call(this, name, scene) || this;
  42078. /**
  42079. * Intensity of the direct lights e.g. the four lights available in your scene.
  42080. * This impacts both the direct diffuse and specular highlights.
  42081. */
  42082. _this.directIntensity = 1.0;
  42083. /**
  42084. * Intensity of the emissive part of the material.
  42085. * This helps controlling the emissive effect without modifying the emissive color.
  42086. */
  42087. _this.emissiveIntensity = 1.0;
  42088. /**
  42089. * Intensity of the environment e.g. how much the environment will light the object
  42090. * either through harmonics for rough material or through the refelction for shiny ones.
  42091. */
  42092. _this.environmentIntensity = 1.0;
  42093. /**
  42094. * This is a special control allowing the reduction of the specular highlights coming from the
  42095. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42096. */
  42097. _this.specularIntensity = 1.0;
  42098. /**
  42099. * Debug Control allowing disabling the bump map on this material.
  42100. */
  42101. _this.disableBumpMap = false;
  42102. /**
  42103. * AKA Occlusion Texture Intensity in other nomenclature.
  42104. */
  42105. _this.ambientTextureStrength = 1.0;
  42106. /**
  42107. * The color of a material in ambient lighting.
  42108. */
  42109. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42110. /**
  42111. * AKA Diffuse Color in other nomenclature.
  42112. */
  42113. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42114. /**
  42115. * AKA Specular Color in other nomenclature.
  42116. */
  42117. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42118. /**
  42119. * The color reflected from the material.
  42120. */
  42121. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42122. /**
  42123. * The color emitted from the material.
  42124. */
  42125. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42126. /**
  42127. * AKA Glossiness in other nomenclature.
  42128. */
  42129. _this.microSurface = 1.0;
  42130. /**
  42131. * source material index of refraction (IOR)' / 'destination material IOR.
  42132. */
  42133. _this.indexOfRefraction = 0.66;
  42134. /**
  42135. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42136. */
  42137. _this.invertRefractionY = false;
  42138. /**
  42139. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42140. * Materials half opaque for instance using refraction could benefit from this control.
  42141. */
  42142. _this.linkRefractionWithTransparency = false;
  42143. _this.useLightmapAsShadowmap = false;
  42144. /**
  42145. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42146. */
  42147. _this.useAlphaFromAlbedoTexture = false;
  42148. /**
  42149. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42150. */
  42151. _this.forceAlphaTest = false;
  42152. /**
  42153. * Defines the alpha limits in alpha test mode.
  42154. */
  42155. _this.alphaCutOff = 0.4;
  42156. /**
  42157. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42158. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42159. */
  42160. _this.useSpecularOverAlpha = true;
  42161. /**
  42162. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42163. */
  42164. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42165. /**
  42166. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42167. */
  42168. _this.useRoughnessFromMetallicTextureAlpha = true;
  42169. /**
  42170. * Specifies if the metallic texture contains the roughness information in its green channel.
  42171. */
  42172. _this.useRoughnessFromMetallicTextureGreen = false;
  42173. /**
  42174. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42175. */
  42176. _this.useMetallnessFromMetallicTextureBlue = false;
  42177. /**
  42178. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42179. */
  42180. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42181. /**
  42182. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42183. */
  42184. _this.useAmbientInGrayScale = false;
  42185. /**
  42186. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42187. * The material will try to infer what glossiness each pixel should be.
  42188. */
  42189. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42190. /**
  42191. * BJS is using an harcoded light falloff based on a manually sets up range.
  42192. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42193. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42194. */
  42195. _this.usePhysicalLightFalloff = true;
  42196. /**
  42197. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42198. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42199. */
  42200. _this.useRadianceOverAlpha = true;
  42201. /**
  42202. * Allows using an object space normal map (instead of tangent space).
  42203. */
  42204. _this.useObjectSpaceNormalMap = false;
  42205. /**
  42206. * Allows using the bump map in parallax mode.
  42207. */
  42208. _this.useParallax = false;
  42209. /**
  42210. * Allows using the bump map in parallax occlusion mode.
  42211. */
  42212. _this.useParallaxOcclusion = false;
  42213. /**
  42214. * Controls the scale bias of the parallax mode.
  42215. */
  42216. _this.parallaxScaleBias = 0.05;
  42217. /**
  42218. * If sets to true, disables all the lights affecting the material.
  42219. */
  42220. _this.disableLighting = false;
  42221. /**
  42222. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42223. */
  42224. _this.forceIrradianceInFragment = false;
  42225. /**
  42226. * Number of Simultaneous lights allowed on the material.
  42227. */
  42228. _this.maxSimultaneousLights = 4;
  42229. /**
  42230. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42231. */
  42232. _this.invertNormalMapX = false;
  42233. /**
  42234. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42235. */
  42236. _this.invertNormalMapY = false;
  42237. /**
  42238. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42239. */
  42240. _this.twoSidedLighting = false;
  42241. /**
  42242. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42243. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42244. */
  42245. _this.useAlphaFresnel = false;
  42246. /**
  42247. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42248. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42249. */
  42250. _this.useLinearAlphaFresnel = false;
  42251. /**
  42252. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42253. * And/Or occlude the blended part.
  42254. */
  42255. _this.environmentBRDFTexture = null;
  42256. /**
  42257. * Force normal to face away from face.
  42258. */
  42259. _this.forceNormalForward = false;
  42260. /**
  42261. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42262. * makes the reflect vector face the model (under horizon).
  42263. */
  42264. _this.useHorizonOcclusion = true;
  42265. /**
  42266. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42267. * too much the area relying on ambient texture to define their ambient occlusion.
  42268. */
  42269. _this.useRadianceOcclusion = true;
  42270. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42271. return _this;
  42272. }
  42273. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42274. /**
  42275. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42276. */
  42277. get: function () {
  42278. return this._PBRMATERIAL_OPAQUE;
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42284. /**
  42285. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42286. */
  42287. get: function () {
  42288. return this._PBRMATERIAL_ALPHATEST;
  42289. },
  42290. enumerable: true,
  42291. configurable: true
  42292. });
  42293. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42294. /**
  42295. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42296. */
  42297. get: function () {
  42298. return this._PBRMATERIAL_ALPHABLEND;
  42299. },
  42300. enumerable: true,
  42301. configurable: true
  42302. });
  42303. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42304. /**
  42305. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42306. * They are also discarded below the alpha cutoff threshold to improve performances.
  42307. */
  42308. get: function () {
  42309. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42310. },
  42311. enumerable: true,
  42312. configurable: true
  42313. });
  42314. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42315. /**
  42316. * Gets the image processing configuration used either in this material.
  42317. */
  42318. get: function () {
  42319. return this._imageProcessingConfiguration;
  42320. },
  42321. /**
  42322. * Sets the Default image processing configuration used either in the this material.
  42323. *
  42324. * If sets to null, the scene one is in use.
  42325. */
  42326. set: function (value) {
  42327. this._attachImageProcessingConfiguration(value);
  42328. // Ensure the effect will be rebuilt.
  42329. this._markAllSubMeshesAsTexturesDirty();
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42335. /**
  42336. * Gets wether the color curves effect is enabled.
  42337. */
  42338. get: function () {
  42339. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42340. },
  42341. /**
  42342. * Sets wether the color curves effect is enabled.
  42343. */
  42344. set: function (value) {
  42345. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42346. },
  42347. enumerable: true,
  42348. configurable: true
  42349. });
  42350. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42351. /**
  42352. * Gets wether the color grading effect is enabled.
  42353. */
  42354. get: function () {
  42355. return this.imageProcessingConfiguration.colorGradingEnabled;
  42356. },
  42357. /**
  42358. * Gets wether the color grading effect is enabled.
  42359. */
  42360. set: function (value) {
  42361. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42362. },
  42363. enumerable: true,
  42364. configurable: true
  42365. });
  42366. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42367. /**
  42368. * Gets wether tonemapping is enabled or not.
  42369. */
  42370. get: function () {
  42371. return this._imageProcessingConfiguration.toneMappingEnabled;
  42372. },
  42373. /**
  42374. * Sets wether tonemapping is enabled or not
  42375. */
  42376. set: function (value) {
  42377. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42378. },
  42379. enumerable: true,
  42380. configurable: true
  42381. });
  42382. ;
  42383. ;
  42384. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42385. /**
  42386. * The camera exposure used on this material.
  42387. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42388. * This corresponds to a photographic exposure.
  42389. */
  42390. get: function () {
  42391. return this._imageProcessingConfiguration.exposure;
  42392. },
  42393. /**
  42394. * The camera exposure used on this material.
  42395. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42396. * This corresponds to a photographic exposure.
  42397. */
  42398. set: function (value) {
  42399. this._imageProcessingConfiguration.exposure = value;
  42400. },
  42401. enumerable: true,
  42402. configurable: true
  42403. });
  42404. ;
  42405. ;
  42406. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42407. /**
  42408. * Gets The camera contrast used on this material.
  42409. */
  42410. get: function () {
  42411. return this._imageProcessingConfiguration.contrast;
  42412. },
  42413. /**
  42414. * Sets The camera contrast used on this material.
  42415. */
  42416. set: function (value) {
  42417. this._imageProcessingConfiguration.contrast = value;
  42418. },
  42419. enumerable: true,
  42420. configurable: true
  42421. });
  42422. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42423. /**
  42424. * Gets the Color Grading 2D Lookup Texture.
  42425. */
  42426. get: function () {
  42427. return this._imageProcessingConfiguration.colorGradingTexture;
  42428. },
  42429. /**
  42430. * Sets the Color Grading 2D Lookup Texture.
  42431. */
  42432. set: function (value) {
  42433. this._imageProcessingConfiguration.colorGradingTexture = value;
  42434. },
  42435. enumerable: true,
  42436. configurable: true
  42437. });
  42438. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42439. /**
  42440. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42441. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42442. * 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;
  42443. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42444. */
  42445. get: function () {
  42446. return this._imageProcessingConfiguration.colorCurves;
  42447. },
  42448. /**
  42449. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42450. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42451. * 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;
  42452. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42453. */
  42454. set: function (value) {
  42455. this._imageProcessingConfiguration.colorCurves = value;
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. /**
  42461. * Returns the name of this material class.
  42462. */
  42463. PBRMaterial.prototype.getClassName = function () {
  42464. return "PBRMaterial";
  42465. };
  42466. /**
  42467. * Returns an array of the actively used textures.
  42468. * @returns - Array of BaseTextures
  42469. */
  42470. PBRMaterial.prototype.getActiveTextures = function () {
  42471. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42472. if (this._albedoTexture) {
  42473. activeTextures.push(this._albedoTexture);
  42474. }
  42475. if (this._ambientTexture) {
  42476. activeTextures.push(this._ambientTexture);
  42477. }
  42478. if (this._opacityTexture) {
  42479. activeTextures.push(this._opacityTexture);
  42480. }
  42481. if (this._reflectionTexture) {
  42482. activeTextures.push(this._reflectionTexture);
  42483. }
  42484. if (this._emissiveTexture) {
  42485. activeTextures.push(this._emissiveTexture);
  42486. }
  42487. if (this._reflectivityTexture) {
  42488. activeTextures.push(this._reflectivityTexture);
  42489. }
  42490. if (this._metallicTexture) {
  42491. activeTextures.push(this._metallicTexture);
  42492. }
  42493. if (this._microSurfaceTexture) {
  42494. activeTextures.push(this._microSurfaceTexture);
  42495. }
  42496. if (this._bumpTexture) {
  42497. activeTextures.push(this._bumpTexture);
  42498. }
  42499. if (this._lightmapTexture) {
  42500. activeTextures.push(this._lightmapTexture);
  42501. }
  42502. if (this._refractionTexture) {
  42503. activeTextures.push(this._refractionTexture);
  42504. }
  42505. return activeTextures;
  42506. };
  42507. /**
  42508. * Checks to see if a texture is used in the material.
  42509. * @param texture - Base texture to use.
  42510. * @returns - Boolean specifying if a texture is used in the material.
  42511. */
  42512. PBRMaterial.prototype.hasTexture = function (texture) {
  42513. if (_super.prototype.hasTexture.call(this, texture)) {
  42514. return true;
  42515. }
  42516. if (this._albedoTexture === texture) {
  42517. return true;
  42518. }
  42519. if (this._ambientTexture === texture) {
  42520. return true;
  42521. }
  42522. if (this._opacityTexture === texture) {
  42523. return true;
  42524. }
  42525. if (this._reflectionTexture === texture) {
  42526. return true;
  42527. }
  42528. if (this._reflectivityTexture === texture) {
  42529. return true;
  42530. }
  42531. if (this._metallicTexture === texture) {
  42532. return true;
  42533. }
  42534. if (this._microSurfaceTexture === texture) {
  42535. return true;
  42536. }
  42537. if (this._bumpTexture === texture) {
  42538. return true;
  42539. }
  42540. if (this._lightmapTexture === texture) {
  42541. return true;
  42542. }
  42543. if (this._refractionTexture === texture) {
  42544. return true;
  42545. }
  42546. return false;
  42547. };
  42548. /**
  42549. * Makes a duplicate of the current material.
  42550. * @param name - name to use for the new material.
  42551. */
  42552. PBRMaterial.prototype.clone = function (name) {
  42553. var _this = this;
  42554. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42555. clone.id = name;
  42556. clone.name = name;
  42557. return clone;
  42558. };
  42559. /**
  42560. * Serializes this PBR Material.
  42561. * @returns - An object with the serialized material.
  42562. */
  42563. PBRMaterial.prototype.serialize = function () {
  42564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42565. serializationObject.customType = "BABYLON.PBRMaterial";
  42566. return serializationObject;
  42567. };
  42568. // Statics
  42569. /**
  42570. * Parses a PBR Material from a serialized object.
  42571. * @param source - Serialized object.
  42572. * @param scene - BJS scene instance.
  42573. * @param rootUrl - url for the scene object
  42574. * @returns - PBRMaterial
  42575. */
  42576. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42577. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42578. };
  42579. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42580. /**
  42581. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42582. */
  42583. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42584. /**
  42585. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42586. */
  42587. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42588. /**
  42589. * 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.
  42590. * They are also discarded below the alpha cutoff threshold to improve performances.
  42591. */
  42592. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42593. __decorate([
  42594. BABYLON.serialize(),
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42596. ], PBRMaterial.prototype, "directIntensity", void 0);
  42597. __decorate([
  42598. BABYLON.serialize(),
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42600. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42601. __decorate([
  42602. BABYLON.serialize(),
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42604. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42605. __decorate([
  42606. BABYLON.serialize(),
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42608. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42609. __decorate([
  42610. BABYLON.serialize(),
  42611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42612. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42613. __decorate([
  42614. BABYLON.serializeAsTexture(),
  42615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42616. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42617. __decorate([
  42618. BABYLON.serializeAsTexture(),
  42619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42620. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42621. __decorate([
  42622. BABYLON.serialize(),
  42623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42624. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42625. __decorate([
  42626. BABYLON.serializeAsTexture(),
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42628. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42629. __decorate([
  42630. BABYLON.serializeAsTexture(),
  42631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42632. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42633. __decorate([
  42634. BABYLON.serializeAsTexture(),
  42635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42636. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42637. __decorate([
  42638. BABYLON.serializeAsTexture(),
  42639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42640. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42641. __decorate([
  42642. BABYLON.serializeAsTexture(),
  42643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42644. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42645. __decorate([
  42646. BABYLON.serialize(),
  42647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42648. ], PBRMaterial.prototype, "metallic", void 0);
  42649. __decorate([
  42650. BABYLON.serialize(),
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42652. ], PBRMaterial.prototype, "roughness", void 0);
  42653. __decorate([
  42654. BABYLON.serializeAsTexture(),
  42655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42656. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42657. __decorate([
  42658. BABYLON.serializeAsTexture(),
  42659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42660. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42661. __decorate([
  42662. BABYLON.serializeAsTexture(),
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42664. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42665. __decorate([
  42666. BABYLON.serializeAsTexture(),
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42668. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42669. __decorate([
  42670. BABYLON.serializeAsColor3("ambient"),
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42672. ], PBRMaterial.prototype, "ambientColor", void 0);
  42673. __decorate([
  42674. BABYLON.serializeAsColor3("albedo"),
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42676. ], PBRMaterial.prototype, "albedoColor", void 0);
  42677. __decorate([
  42678. BABYLON.serializeAsColor3("reflectivity"),
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42681. __decorate([
  42682. BABYLON.serializeAsColor3("reflection"),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42684. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42685. __decorate([
  42686. BABYLON.serializeAsColor3("emissive"),
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42688. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42689. __decorate([
  42690. BABYLON.serialize(),
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42692. ], PBRMaterial.prototype, "microSurface", void 0);
  42693. __decorate([
  42694. BABYLON.serialize(),
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42696. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42697. __decorate([
  42698. BABYLON.serialize(),
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42700. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42701. __decorate([
  42702. BABYLON.serialize(),
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42704. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42705. __decorate([
  42706. BABYLON.serialize(),
  42707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42708. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42709. __decorate([
  42710. BABYLON.serialize(),
  42711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42712. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42713. __decorate([
  42714. BABYLON.serialize(),
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42716. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42717. __decorate([
  42718. BABYLON.serialize(),
  42719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42720. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42721. __decorate([
  42722. BABYLON.serialize(),
  42723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42724. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42725. __decorate([
  42726. BABYLON.serialize(),
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42728. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42729. __decorate([
  42730. BABYLON.serialize(),
  42731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42732. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42733. __decorate([
  42734. BABYLON.serialize(),
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42736. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42737. __decorate([
  42738. BABYLON.serialize(),
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42740. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42741. __decorate([
  42742. BABYLON.serialize(),
  42743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42744. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42745. __decorate([
  42746. BABYLON.serialize(),
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42748. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42749. __decorate([
  42750. BABYLON.serialize(),
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42752. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42753. __decorate([
  42754. BABYLON.serialize(),
  42755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42756. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42757. __decorate([
  42758. BABYLON.serialize(),
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42760. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42761. __decorate([
  42762. BABYLON.serialize(),
  42763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42764. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42765. __decorate([
  42766. BABYLON.serialize(),
  42767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42768. ], PBRMaterial.prototype, "useParallax", void 0);
  42769. __decorate([
  42770. BABYLON.serialize(),
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42772. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42773. __decorate([
  42774. BABYLON.serialize(),
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42776. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42777. __decorate([
  42778. BABYLON.serialize(),
  42779. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42780. ], PBRMaterial.prototype, "disableLighting", void 0);
  42781. __decorate([
  42782. BABYLON.serialize(),
  42783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42784. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42785. __decorate([
  42786. BABYLON.serialize(),
  42787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42788. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42789. __decorate([
  42790. BABYLON.serialize(),
  42791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42792. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42793. __decorate([
  42794. BABYLON.serialize(),
  42795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42796. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42797. __decorate([
  42798. BABYLON.serialize(),
  42799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42800. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42801. __decorate([
  42802. BABYLON.serialize(),
  42803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42804. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42805. __decorate([
  42806. BABYLON.serialize(),
  42807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42808. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42809. __decorate([
  42810. BABYLON.serializeAsTexture(),
  42811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42812. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42813. __decorate([
  42814. BABYLON.serialize(),
  42815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42816. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42817. __decorate([
  42818. BABYLON.serialize(),
  42819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42820. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42821. __decorate([
  42822. BABYLON.serialize(),
  42823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42824. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42825. return PBRMaterial;
  42826. }(BABYLON.PBRBaseMaterial));
  42827. BABYLON.PBRMaterial = PBRMaterial;
  42828. })(BABYLON || (BABYLON = {}));
  42829. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42830. var BABYLON;
  42831. (function (BABYLON) {
  42832. /**
  42833. * The PBR material of BJS following the metal roughness convention.
  42834. *
  42835. * This fits to the PBR convention in the GLTF definition:
  42836. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42837. */
  42838. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42839. __extends(PBRMetallicRoughnessMaterial, _super);
  42840. /**
  42841. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42842. *
  42843. * @param name The material name
  42844. * @param scene The scene the material will be use in.
  42845. */
  42846. function PBRMetallicRoughnessMaterial(name, scene) {
  42847. var _this = _super.call(this, name, scene) || this;
  42848. _this._useRoughnessFromMetallicTextureAlpha = false;
  42849. _this._useRoughnessFromMetallicTextureGreen = true;
  42850. _this._useMetallnessFromMetallicTextureBlue = true;
  42851. _this.metallic = 1.0;
  42852. _this.roughness = 1.0;
  42853. return _this;
  42854. }
  42855. /**
  42856. * Return the currrent class name of the material.
  42857. */
  42858. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42859. return "PBRMetallicRoughnessMaterial";
  42860. };
  42861. /**
  42862. * Return the active textures of the material.
  42863. */
  42864. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42865. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42866. if (this.baseTexture) {
  42867. activeTextures.push(this.baseTexture);
  42868. }
  42869. if (this.metallicRoughnessTexture) {
  42870. activeTextures.push(this.metallicRoughnessTexture);
  42871. }
  42872. return activeTextures;
  42873. };
  42874. /**
  42875. * Checks to see if a texture is used in the material.
  42876. * @param texture - Base texture to use.
  42877. * @returns - Boolean specifying if a texture is used in the material.
  42878. */
  42879. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42880. if (_super.prototype.hasTexture.call(this, texture)) {
  42881. return true;
  42882. }
  42883. if (this.baseTexture === texture) {
  42884. return true;
  42885. }
  42886. if (this.metallicRoughnessTexture === texture) {
  42887. return true;
  42888. }
  42889. return false;
  42890. };
  42891. /**
  42892. * Makes a duplicate of the current material.
  42893. * @param name - name to use for the new material.
  42894. */
  42895. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42896. var _this = this;
  42897. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42898. clone.id = name;
  42899. clone.name = name;
  42900. return clone;
  42901. };
  42902. /**
  42903. * Serialize the material to a parsable JSON object.
  42904. */
  42905. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42906. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42907. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42908. return serializationObject;
  42909. };
  42910. /**
  42911. * Parses a JSON object correponding to the serialize function.
  42912. */
  42913. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42914. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42915. };
  42916. __decorate([
  42917. BABYLON.serializeAsColor3(),
  42918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42919. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42920. __decorate([
  42921. BABYLON.serializeAsTexture(),
  42922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42923. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42924. __decorate([
  42925. BABYLON.serialize(),
  42926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42927. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42928. __decorate([
  42929. BABYLON.serialize(),
  42930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42931. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42932. __decorate([
  42933. BABYLON.serializeAsTexture(),
  42934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42935. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42936. return PBRMetallicRoughnessMaterial;
  42937. }(BABYLON.PBRBaseSimpleMaterial));
  42938. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42939. })(BABYLON || (BABYLON = {}));
  42940. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42941. var BABYLON;
  42942. (function (BABYLON) {
  42943. /**
  42944. * The PBR material of BJS following the specular glossiness convention.
  42945. *
  42946. * This fits to the PBR convention in the GLTF definition:
  42947. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42948. */
  42949. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42950. __extends(PBRSpecularGlossinessMaterial, _super);
  42951. /**
  42952. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42953. *
  42954. * @param name The material name
  42955. * @param scene The scene the material will be use in.
  42956. */
  42957. function PBRSpecularGlossinessMaterial(name, scene) {
  42958. var _this = _super.call(this, name, scene) || this;
  42959. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42960. return _this;
  42961. }
  42962. /**
  42963. * Return the currrent class name of the material.
  42964. */
  42965. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42966. return "PBRSpecularGlossinessMaterial";
  42967. };
  42968. /**
  42969. * Return the active textures of the material.
  42970. */
  42971. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42972. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42973. if (this.diffuseTexture) {
  42974. activeTextures.push(this.diffuseTexture);
  42975. }
  42976. if (this.specularGlossinessTexture) {
  42977. activeTextures.push(this.specularGlossinessTexture);
  42978. }
  42979. return activeTextures;
  42980. };
  42981. /**
  42982. * Checks to see if a texture is used in the material.
  42983. * @param texture - Base texture to use.
  42984. * @returns - Boolean specifying if a texture is used in the material.
  42985. */
  42986. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42987. if (_super.prototype.hasTexture.call(this, texture)) {
  42988. return true;
  42989. }
  42990. if (this.diffuseTexture === texture) {
  42991. return true;
  42992. }
  42993. if (this.specularGlossinessTexture === texture) {
  42994. return true;
  42995. }
  42996. return false;
  42997. };
  42998. /**
  42999. * Makes a duplicate of the current material.
  43000. * @param name - name to use for the new material.
  43001. */
  43002. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43003. var _this = this;
  43004. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43005. clone.id = name;
  43006. clone.name = name;
  43007. return clone;
  43008. };
  43009. /**
  43010. * Serialize the material to a parsable JSON object.
  43011. */
  43012. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43013. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43014. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43015. return serializationObject;
  43016. };
  43017. /**
  43018. * Parses a JSON object correponding to the serialize function.
  43019. */
  43020. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43021. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43022. };
  43023. __decorate([
  43024. BABYLON.serializeAsColor3("diffuse"),
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43026. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43027. __decorate([
  43028. BABYLON.serializeAsTexture(),
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43030. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43031. __decorate([
  43032. BABYLON.serializeAsColor3("specular"),
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43034. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43035. __decorate([
  43036. BABYLON.serialize(),
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43038. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsTexture(),
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43042. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43043. return PBRSpecularGlossinessMaterial;
  43044. }(BABYLON.PBRBaseSimpleMaterial));
  43045. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43046. })(BABYLON || (BABYLON = {}));
  43047. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43048. var BABYLON;
  43049. (function (BABYLON) {
  43050. BABYLON.CameraInputTypes = {};
  43051. var CameraInputsManager = /** @class */ (function () {
  43052. function CameraInputsManager(camera) {
  43053. this.attached = {};
  43054. this.camera = camera;
  43055. this.checkInputs = function () { };
  43056. }
  43057. /**
  43058. * Add an input method to a camera.
  43059. * builtin inputs example: camera.inputs.addGamepad();
  43060. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43061. * @param input camera input method
  43062. */
  43063. CameraInputsManager.prototype.add = function (input) {
  43064. var type = input.getSimpleName();
  43065. if (this.attached[type]) {
  43066. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43067. return;
  43068. }
  43069. this.attached[type] = input;
  43070. input.camera = this.camera;
  43071. //for checkInputs, we are dynamically creating a function
  43072. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43073. if (input.checkInputs) {
  43074. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43075. }
  43076. if (this.attachedElement) {
  43077. input.attachControl(this.attachedElement);
  43078. }
  43079. };
  43080. /**
  43081. * Remove a specific input method from a camera
  43082. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43083. * @param inputToRemove camera input method
  43084. */
  43085. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43086. for (var cam in this.attached) {
  43087. var input = this.attached[cam];
  43088. if (input === inputToRemove) {
  43089. input.detachControl(this.attachedElement);
  43090. input.camera = null;
  43091. delete this.attached[cam];
  43092. this.rebuildInputCheck();
  43093. }
  43094. }
  43095. };
  43096. CameraInputsManager.prototype.removeByType = function (inputType) {
  43097. for (var cam in this.attached) {
  43098. var input = this.attached[cam];
  43099. if (input.getClassName() === inputType) {
  43100. input.detachControl(this.attachedElement);
  43101. input.camera = null;
  43102. delete this.attached[cam];
  43103. this.rebuildInputCheck();
  43104. }
  43105. }
  43106. };
  43107. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43108. var current = this.checkInputs;
  43109. return function () {
  43110. current();
  43111. fn();
  43112. };
  43113. };
  43114. CameraInputsManager.prototype.attachInput = function (input) {
  43115. if (this.attachedElement) {
  43116. input.attachControl(this.attachedElement, this.noPreventDefault);
  43117. }
  43118. };
  43119. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43120. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43121. if (this.attachedElement) {
  43122. return;
  43123. }
  43124. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43125. this.attachedElement = element;
  43126. this.noPreventDefault = noPreventDefault;
  43127. for (var cam in this.attached) {
  43128. this.attached[cam].attachControl(element, noPreventDefault);
  43129. }
  43130. };
  43131. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43132. if (disconnect === void 0) { disconnect = false; }
  43133. if (this.attachedElement !== element) {
  43134. return;
  43135. }
  43136. for (var cam in this.attached) {
  43137. this.attached[cam].detachControl(element);
  43138. if (disconnect) {
  43139. this.attached[cam].camera = null;
  43140. }
  43141. }
  43142. this.attachedElement = null;
  43143. };
  43144. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43145. this.checkInputs = function () { };
  43146. for (var cam in this.attached) {
  43147. var input = this.attached[cam];
  43148. if (input.checkInputs) {
  43149. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43150. }
  43151. }
  43152. };
  43153. /**
  43154. * Remove all attached input methods from a camera
  43155. */
  43156. CameraInputsManager.prototype.clear = function () {
  43157. if (this.attachedElement) {
  43158. this.detachElement(this.attachedElement, true);
  43159. }
  43160. this.attached = {};
  43161. this.attachedElement = null;
  43162. this.checkInputs = function () { };
  43163. };
  43164. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43165. var inputs = {};
  43166. for (var cam in this.attached) {
  43167. var input = this.attached[cam];
  43168. var res = BABYLON.SerializationHelper.Serialize(input);
  43169. inputs[input.getClassName()] = res;
  43170. }
  43171. serializedCamera.inputsmgr = inputs;
  43172. };
  43173. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43174. var parsedInputs = parsedCamera.inputsmgr;
  43175. if (parsedInputs) {
  43176. this.clear();
  43177. for (var n in parsedInputs) {
  43178. var construct = BABYLON.CameraInputTypes[n];
  43179. if (construct) {
  43180. var parsedinput = parsedInputs[n];
  43181. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43182. this.add(input);
  43183. }
  43184. }
  43185. }
  43186. else {
  43187. //2016-03-08 this part is for managing backward compatibility
  43188. for (var n in this.attached) {
  43189. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43190. if (construct) {
  43191. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43192. this.remove(this.attached[n]);
  43193. this.add(input);
  43194. }
  43195. }
  43196. }
  43197. };
  43198. return CameraInputsManager;
  43199. }());
  43200. BABYLON.CameraInputsManager = CameraInputsManager;
  43201. })(BABYLON || (BABYLON = {}));
  43202. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43203. var BABYLON;
  43204. (function (BABYLON) {
  43205. var TargetCamera = /** @class */ (function (_super) {
  43206. __extends(TargetCamera, _super);
  43207. function TargetCamera(name, position, scene) {
  43208. var _this = _super.call(this, name, position, scene) || this;
  43209. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43210. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43211. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43212. _this.speed = 2.0;
  43213. _this.noRotationConstraint = false;
  43214. _this.lockedTarget = null;
  43215. _this._currentTarget = BABYLON.Vector3.Zero();
  43216. _this._viewMatrix = BABYLON.Matrix.Zero();
  43217. _this._camMatrix = BABYLON.Matrix.Zero();
  43218. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43219. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43220. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43221. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43222. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43223. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43224. _this._tempMatrix = BABYLON.Matrix.Zero();
  43225. return _this;
  43226. }
  43227. TargetCamera.prototype.getFrontPosition = function (distance) {
  43228. this.getWorldMatrix();
  43229. var direction = this.getTarget().subtract(this.position);
  43230. direction.normalize();
  43231. direction.scaleInPlace(distance);
  43232. return this.globalPosition.add(direction);
  43233. };
  43234. TargetCamera.prototype._getLockedTargetPosition = function () {
  43235. if (!this.lockedTarget) {
  43236. return null;
  43237. }
  43238. if (this.lockedTarget.absolutePosition) {
  43239. this.lockedTarget.computeWorldMatrix();
  43240. }
  43241. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43242. };
  43243. TargetCamera.prototype.storeState = function () {
  43244. this._storedPosition = this.position.clone();
  43245. this._storedRotation = this.rotation.clone();
  43246. if (this.rotationQuaternion) {
  43247. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43248. }
  43249. return _super.prototype.storeState.call(this);
  43250. };
  43251. /**
  43252. * Restored camera state. You must call storeState() first
  43253. */
  43254. TargetCamera.prototype._restoreStateValues = function () {
  43255. if (!_super.prototype._restoreStateValues.call(this)) {
  43256. return false;
  43257. }
  43258. this.position = this._storedPosition.clone();
  43259. this.rotation = this._storedRotation.clone();
  43260. if (this.rotationQuaternion) {
  43261. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43262. }
  43263. this.cameraDirection.copyFromFloats(0, 0, 0);
  43264. this.cameraRotation.copyFromFloats(0, 0);
  43265. return true;
  43266. };
  43267. // Cache
  43268. TargetCamera.prototype._initCache = function () {
  43269. _super.prototype._initCache.call(this);
  43270. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43271. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43272. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43273. };
  43274. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43275. if (!ignoreParentClass) {
  43276. _super.prototype._updateCache.call(this);
  43277. }
  43278. var lockedTargetPosition = this._getLockedTargetPosition();
  43279. if (!lockedTargetPosition) {
  43280. this._cache.lockedTarget = null;
  43281. }
  43282. else {
  43283. if (!this._cache.lockedTarget) {
  43284. this._cache.lockedTarget = lockedTargetPosition.clone();
  43285. }
  43286. else {
  43287. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43288. }
  43289. }
  43290. this._cache.rotation.copyFrom(this.rotation);
  43291. if (this.rotationQuaternion)
  43292. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43293. };
  43294. // Synchronized
  43295. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43296. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43297. return false;
  43298. }
  43299. var lockedTargetPosition = this._getLockedTargetPosition();
  43300. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43301. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43302. };
  43303. // Methods
  43304. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43305. var engine = this.getEngine();
  43306. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43307. };
  43308. // Target
  43309. TargetCamera.prototype.setTarget = function (target) {
  43310. this.upVector.normalize();
  43311. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43312. this._camMatrix.invert();
  43313. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43314. var vDir = target.subtract(this.position);
  43315. if (vDir.x >= 0.0) {
  43316. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43317. }
  43318. else {
  43319. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43320. }
  43321. this.rotation.z = 0;
  43322. if (isNaN(this.rotation.x)) {
  43323. this.rotation.x = 0;
  43324. }
  43325. if (isNaN(this.rotation.y)) {
  43326. this.rotation.y = 0;
  43327. }
  43328. if (isNaN(this.rotation.z)) {
  43329. this.rotation.z = 0;
  43330. }
  43331. if (this.rotationQuaternion) {
  43332. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43333. }
  43334. };
  43335. /**
  43336. * Return the current target position of the camera. This value is expressed in local space.
  43337. */
  43338. TargetCamera.prototype.getTarget = function () {
  43339. return this._currentTarget;
  43340. };
  43341. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43342. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43343. };
  43344. TargetCamera.prototype._updatePosition = function () {
  43345. if (this.parent) {
  43346. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43347. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43348. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43349. return;
  43350. }
  43351. this.position.addInPlace(this.cameraDirection);
  43352. };
  43353. TargetCamera.prototype._checkInputs = function () {
  43354. var needToMove = this._decideIfNeedsToMove();
  43355. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43356. // Move
  43357. if (needToMove) {
  43358. this._updatePosition();
  43359. }
  43360. // Rotate
  43361. if (needToRotate) {
  43362. this.rotation.x += this.cameraRotation.x;
  43363. this.rotation.y += this.cameraRotation.y;
  43364. //rotate, if quaternion is set and rotation was used
  43365. if (this.rotationQuaternion) {
  43366. var len = this.rotation.lengthSquared();
  43367. if (len) {
  43368. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43369. }
  43370. }
  43371. if (!this.noRotationConstraint) {
  43372. var limit = (Math.PI / 2) * 0.95;
  43373. if (this.rotation.x > limit)
  43374. this.rotation.x = limit;
  43375. if (this.rotation.x < -limit)
  43376. this.rotation.x = -limit;
  43377. }
  43378. }
  43379. // Inertia
  43380. if (needToMove) {
  43381. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43382. this.cameraDirection.x = 0;
  43383. }
  43384. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43385. this.cameraDirection.y = 0;
  43386. }
  43387. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43388. this.cameraDirection.z = 0;
  43389. }
  43390. this.cameraDirection.scaleInPlace(this.inertia);
  43391. }
  43392. if (needToRotate) {
  43393. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43394. this.cameraRotation.x = 0;
  43395. }
  43396. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43397. this.cameraRotation.y = 0;
  43398. }
  43399. this.cameraRotation.scaleInPlace(this.inertia);
  43400. }
  43401. _super.prototype._checkInputs.call(this);
  43402. };
  43403. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43404. if (this.rotationQuaternion) {
  43405. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43406. }
  43407. else {
  43408. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43409. }
  43410. //update the up vector!
  43411. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43412. };
  43413. TargetCamera.prototype._getViewMatrix = function () {
  43414. if (this.lockedTarget) {
  43415. this.setTarget(this._getLockedTargetPosition());
  43416. }
  43417. // Compute
  43418. this._updateCameraRotationMatrix();
  43419. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43420. // Computing target and final matrix
  43421. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43422. if (this.getScene().useRightHandedSystem) {
  43423. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43424. }
  43425. else {
  43426. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43427. }
  43428. return this._viewMatrix;
  43429. };
  43430. /**
  43431. * @override
  43432. * Override Camera.createRigCamera
  43433. */
  43434. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43435. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43436. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43437. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43438. if (!this.rotationQuaternion) {
  43439. this.rotationQuaternion = new BABYLON.Quaternion();
  43440. }
  43441. rigCamera._cameraRigParams = {};
  43442. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43443. }
  43444. return rigCamera;
  43445. }
  43446. return null;
  43447. };
  43448. /**
  43449. * @override
  43450. * Override Camera._updateRigCameras
  43451. */
  43452. TargetCamera.prototype._updateRigCameras = function () {
  43453. var camLeft = this._rigCameras[0];
  43454. var camRight = this._rigCameras[1];
  43455. switch (this.cameraRigMode) {
  43456. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43459. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43460. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43461. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43462. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43463. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43464. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43465. camLeft.setTarget(this.getTarget());
  43466. camRight.setTarget(this.getTarget());
  43467. break;
  43468. case BABYLON.Camera.RIG_MODE_VR:
  43469. if (camLeft.rotationQuaternion) {
  43470. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43471. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43472. }
  43473. else {
  43474. camLeft.rotation.copyFrom(this.rotation);
  43475. camRight.rotation.copyFrom(this.rotation);
  43476. }
  43477. camLeft.position.copyFrom(this.position);
  43478. camRight.position.copyFrom(this.position);
  43479. break;
  43480. }
  43481. _super.prototype._updateRigCameras.call(this);
  43482. };
  43483. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43484. if (!this._rigCamTransformMatrix) {
  43485. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43486. }
  43487. var target = this.getTarget();
  43488. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43489. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43490. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43491. };
  43492. TargetCamera.prototype.getClassName = function () {
  43493. return "TargetCamera";
  43494. };
  43495. __decorate([
  43496. BABYLON.serializeAsVector3()
  43497. ], TargetCamera.prototype, "rotation", void 0);
  43498. __decorate([
  43499. BABYLON.serialize()
  43500. ], TargetCamera.prototype, "speed", void 0);
  43501. __decorate([
  43502. BABYLON.serializeAsMeshReference("lockedTargetId")
  43503. ], TargetCamera.prototype, "lockedTarget", void 0);
  43504. return TargetCamera;
  43505. }(BABYLON.Camera));
  43506. BABYLON.TargetCamera = TargetCamera;
  43507. })(BABYLON || (BABYLON = {}));
  43508. //# sourceMappingURL=babylon.targetCamera.js.map
  43509. var BABYLON;
  43510. (function (BABYLON) {
  43511. var FreeCameraMouseInput = /** @class */ (function () {
  43512. function FreeCameraMouseInput(touchEnabled) {
  43513. if (touchEnabled === void 0) { touchEnabled = true; }
  43514. this.touchEnabled = touchEnabled;
  43515. this.buttons = [0, 1, 2];
  43516. this.angularSensibility = 2000.0;
  43517. this.previousPosition = null;
  43518. }
  43519. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43520. var _this = this;
  43521. var engine = this.camera.getEngine();
  43522. if (!this._pointerInput) {
  43523. this._pointerInput = function (p, s) {
  43524. var evt = p.event;
  43525. if (engine.isInVRExclusivePointerMode) {
  43526. return;
  43527. }
  43528. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43529. return;
  43530. }
  43531. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43532. return;
  43533. }
  43534. var srcElement = (evt.srcElement || evt.target);
  43535. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43536. try {
  43537. srcElement.setPointerCapture(evt.pointerId);
  43538. }
  43539. catch (e) {
  43540. //Nothing to do with the error. Execution will continue.
  43541. }
  43542. _this.previousPosition = {
  43543. x: evt.clientX,
  43544. y: evt.clientY
  43545. };
  43546. if (!noPreventDefault) {
  43547. evt.preventDefault();
  43548. element.focus();
  43549. }
  43550. }
  43551. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43552. try {
  43553. srcElement.releasePointerCapture(evt.pointerId);
  43554. }
  43555. catch (e) {
  43556. //Nothing to do with the error.
  43557. }
  43558. _this.previousPosition = null;
  43559. if (!noPreventDefault) {
  43560. evt.preventDefault();
  43561. }
  43562. }
  43563. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43564. if (!_this.previousPosition || engine.isPointerLock) {
  43565. return;
  43566. }
  43567. var offsetX = evt.clientX - _this.previousPosition.x;
  43568. var offsetY = evt.clientY - _this.previousPosition.y;
  43569. if (_this.camera.getScene().useRightHandedSystem) {
  43570. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43571. }
  43572. else {
  43573. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43574. }
  43575. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43576. _this.previousPosition = {
  43577. x: evt.clientX,
  43578. y: evt.clientY
  43579. };
  43580. if (!noPreventDefault) {
  43581. evt.preventDefault();
  43582. }
  43583. }
  43584. };
  43585. }
  43586. this._onMouseMove = function (evt) {
  43587. if (!engine.isPointerLock) {
  43588. return;
  43589. }
  43590. if (engine.isInVRExclusivePointerMode) {
  43591. return;
  43592. }
  43593. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43594. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43595. if (_this.camera.getScene().useRightHandedSystem) {
  43596. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43597. }
  43598. else {
  43599. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43600. }
  43601. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43602. _this.previousPosition = null;
  43603. if (!noPreventDefault) {
  43604. evt.preventDefault();
  43605. }
  43606. };
  43607. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43608. element.addEventListener("mousemove", this._onMouseMove, false);
  43609. };
  43610. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43611. if (this._observer && element) {
  43612. this.camera.getScene().onPointerObservable.remove(this._observer);
  43613. if (this._onMouseMove) {
  43614. element.removeEventListener("mousemove", this._onMouseMove);
  43615. }
  43616. this._observer = null;
  43617. this._onMouseMove = null;
  43618. this.previousPosition = null;
  43619. }
  43620. };
  43621. FreeCameraMouseInput.prototype.getClassName = function () {
  43622. return "FreeCameraMouseInput";
  43623. };
  43624. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43625. return "mouse";
  43626. };
  43627. __decorate([
  43628. BABYLON.serialize()
  43629. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43630. __decorate([
  43631. BABYLON.serialize()
  43632. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43633. return FreeCameraMouseInput;
  43634. }());
  43635. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43636. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43637. })(BABYLON || (BABYLON = {}));
  43638. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43639. var BABYLON;
  43640. (function (BABYLON) {
  43641. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43642. function FreeCameraKeyboardMoveInput() {
  43643. this._keys = new Array();
  43644. this.keysUp = [38];
  43645. this.keysDown = [40];
  43646. this.keysLeft = [37];
  43647. this.keysRight = [39];
  43648. }
  43649. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43650. var _this = this;
  43651. if (this._onCanvasBlurObserver) {
  43652. return;
  43653. }
  43654. this._scene = this.camera.getScene();
  43655. this._engine = this._scene.getEngine();
  43656. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43657. _this._keys = [];
  43658. });
  43659. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43660. var evt = info.event;
  43661. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43662. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43663. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43664. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43665. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43666. var index = _this._keys.indexOf(evt.keyCode);
  43667. if (index === -1) {
  43668. _this._keys.push(evt.keyCode);
  43669. }
  43670. if (!noPreventDefault) {
  43671. evt.preventDefault();
  43672. }
  43673. }
  43674. }
  43675. else {
  43676. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43677. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43678. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43679. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43680. var index = _this._keys.indexOf(evt.keyCode);
  43681. if (index >= 0) {
  43682. _this._keys.splice(index, 1);
  43683. }
  43684. if (!noPreventDefault) {
  43685. evt.preventDefault();
  43686. }
  43687. }
  43688. }
  43689. });
  43690. };
  43691. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43692. if (this._scene) {
  43693. if (this._onKeyboardObserver) {
  43694. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43695. }
  43696. if (this._onCanvasBlurObserver) {
  43697. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43698. }
  43699. this._onKeyboardObserver = null;
  43700. this._onCanvasBlurObserver = null;
  43701. }
  43702. this._keys = [];
  43703. };
  43704. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43705. if (this._onKeyboardObserver) {
  43706. var camera = this.camera;
  43707. // Keyboard
  43708. for (var index = 0; index < this._keys.length; index++) {
  43709. var keyCode = this._keys[index];
  43710. var speed = camera._computeLocalCameraSpeed();
  43711. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43712. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43713. }
  43714. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43715. camera._localDirection.copyFromFloats(0, 0, speed);
  43716. }
  43717. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43718. camera._localDirection.copyFromFloats(speed, 0, 0);
  43719. }
  43720. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43721. camera._localDirection.copyFromFloats(0, 0, -speed);
  43722. }
  43723. if (camera.getScene().useRightHandedSystem) {
  43724. camera._localDirection.z *= -1;
  43725. }
  43726. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43727. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43728. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43729. }
  43730. }
  43731. };
  43732. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43733. return "FreeCameraKeyboardMoveInput";
  43734. };
  43735. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43736. this._keys = [];
  43737. };
  43738. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43739. return "keyboard";
  43740. };
  43741. __decorate([
  43742. BABYLON.serialize()
  43743. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43744. __decorate([
  43745. BABYLON.serialize()
  43746. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43747. __decorate([
  43748. BABYLON.serialize()
  43749. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43750. __decorate([
  43751. BABYLON.serialize()
  43752. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43753. return FreeCameraKeyboardMoveInput;
  43754. }());
  43755. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43756. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43757. })(BABYLON || (BABYLON = {}));
  43758. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43759. var BABYLON;
  43760. (function (BABYLON) {
  43761. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43762. __extends(FreeCameraInputsManager, _super);
  43763. function FreeCameraInputsManager(camera) {
  43764. return _super.call(this, camera) || this;
  43765. }
  43766. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43767. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43768. return this;
  43769. };
  43770. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43771. if (touchEnabled === void 0) { touchEnabled = true; }
  43772. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43773. return this;
  43774. };
  43775. FreeCameraInputsManager.prototype.addGamepad = function () {
  43776. this.add(new BABYLON.FreeCameraGamepadInput());
  43777. return this;
  43778. };
  43779. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43780. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43781. return this;
  43782. };
  43783. FreeCameraInputsManager.prototype.addTouch = function () {
  43784. this.add(new BABYLON.FreeCameraTouchInput());
  43785. return this;
  43786. };
  43787. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43788. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43789. return this;
  43790. };
  43791. return FreeCameraInputsManager;
  43792. }(BABYLON.CameraInputsManager));
  43793. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43794. })(BABYLON || (BABYLON = {}));
  43795. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43796. var BABYLON;
  43797. (function (BABYLON) {
  43798. var FreeCamera = /** @class */ (function (_super) {
  43799. __extends(FreeCamera, _super);
  43800. function FreeCamera(name, position, scene) {
  43801. var _this = _super.call(this, name, position, scene) || this;
  43802. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43803. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43804. _this.checkCollisions = false;
  43805. _this.applyGravity = false;
  43806. _this._needMoveForGravity = false;
  43807. _this._oldPosition = BABYLON.Vector3.Zero();
  43808. _this._diffPosition = BABYLON.Vector3.Zero();
  43809. _this._newPosition = BABYLON.Vector3.Zero();
  43810. // Collisions
  43811. _this._collisionMask = -1;
  43812. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43813. if (collidedMesh === void 0) { collidedMesh = null; }
  43814. //TODO move this to the collision coordinator!
  43815. if (_this.getScene().workerCollisions)
  43816. newPosition.multiplyInPlace(_this._collider._radius);
  43817. var updatePosition = function (newPos) {
  43818. _this._newPosition.copyFrom(newPos);
  43819. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43820. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43821. _this.position.addInPlace(_this._diffPosition);
  43822. if (_this.onCollide && collidedMesh) {
  43823. _this.onCollide(collidedMesh);
  43824. }
  43825. }
  43826. };
  43827. updatePosition(newPosition);
  43828. };
  43829. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43830. _this.inputs.addKeyboard().addMouse();
  43831. return _this;
  43832. }
  43833. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43834. //-- begin properties for backward compatibility for inputs
  43835. /**
  43836. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43837. * Higher values reduce sensitivity.
  43838. */
  43839. get: function () {
  43840. var mouse = this.inputs.attached["mouse"];
  43841. if (mouse)
  43842. return mouse.angularSensibility;
  43843. return 0;
  43844. },
  43845. /**
  43846. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43847. * Higher values reduce sensitivity.
  43848. */
  43849. set: function (value) {
  43850. var mouse = this.inputs.attached["mouse"];
  43851. if (mouse)
  43852. mouse.angularSensibility = value;
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43858. get: function () {
  43859. var keyboard = this.inputs.attached["keyboard"];
  43860. if (keyboard)
  43861. return keyboard.keysUp;
  43862. return [];
  43863. },
  43864. set: function (value) {
  43865. var keyboard = this.inputs.attached["keyboard"];
  43866. if (keyboard)
  43867. keyboard.keysUp = value;
  43868. },
  43869. enumerable: true,
  43870. configurable: true
  43871. });
  43872. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43873. get: function () {
  43874. var keyboard = this.inputs.attached["keyboard"];
  43875. if (keyboard)
  43876. return keyboard.keysDown;
  43877. return [];
  43878. },
  43879. set: function (value) {
  43880. var keyboard = this.inputs.attached["keyboard"];
  43881. if (keyboard)
  43882. keyboard.keysDown = value;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43888. get: function () {
  43889. var keyboard = this.inputs.attached["keyboard"];
  43890. if (keyboard)
  43891. return keyboard.keysLeft;
  43892. return [];
  43893. },
  43894. set: function (value) {
  43895. var keyboard = this.inputs.attached["keyboard"];
  43896. if (keyboard)
  43897. keyboard.keysLeft = value;
  43898. },
  43899. enumerable: true,
  43900. configurable: true
  43901. });
  43902. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43903. get: function () {
  43904. var keyboard = this.inputs.attached["keyboard"];
  43905. if (keyboard)
  43906. return keyboard.keysRight;
  43907. return [];
  43908. },
  43909. set: function (value) {
  43910. var keyboard = this.inputs.attached["keyboard"];
  43911. if (keyboard)
  43912. keyboard.keysRight = value;
  43913. },
  43914. enumerable: true,
  43915. configurable: true
  43916. });
  43917. // Controls
  43918. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43919. this.inputs.attachElement(element, noPreventDefault);
  43920. };
  43921. FreeCamera.prototype.detachControl = function (element) {
  43922. this.inputs.detachElement(element);
  43923. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43924. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43925. };
  43926. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43927. get: function () {
  43928. return this._collisionMask;
  43929. },
  43930. set: function (mask) {
  43931. this._collisionMask = !isNaN(mask) ? mask : -1;
  43932. },
  43933. enumerable: true,
  43934. configurable: true
  43935. });
  43936. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43937. var globalPosition;
  43938. if (this.parent) {
  43939. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43940. }
  43941. else {
  43942. globalPosition = this.position;
  43943. }
  43944. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43945. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43946. if (!this._collider) {
  43947. this._collider = new BABYLON.Collider();
  43948. }
  43949. this._collider._radius = this.ellipsoid;
  43950. this._collider.collisionMask = this._collisionMask;
  43951. //no need for clone, as long as gravity is not on.
  43952. var actualDisplacement = displacement;
  43953. //add gravity to the direction to prevent the dual-collision checking
  43954. if (this.applyGravity) {
  43955. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43956. actualDisplacement = displacement.add(this.getScene().gravity);
  43957. }
  43958. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43959. };
  43960. FreeCamera.prototype._checkInputs = function () {
  43961. if (!this._localDirection) {
  43962. this._localDirection = BABYLON.Vector3.Zero();
  43963. this._transformedDirection = BABYLON.Vector3.Zero();
  43964. }
  43965. this.inputs.checkInputs();
  43966. _super.prototype._checkInputs.call(this);
  43967. };
  43968. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43969. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43970. };
  43971. FreeCamera.prototype._updatePosition = function () {
  43972. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43973. this._collideWithWorld(this.cameraDirection);
  43974. }
  43975. else {
  43976. _super.prototype._updatePosition.call(this);
  43977. }
  43978. };
  43979. FreeCamera.prototype.dispose = function () {
  43980. this.inputs.clear();
  43981. _super.prototype.dispose.call(this);
  43982. };
  43983. FreeCamera.prototype.getClassName = function () {
  43984. return "FreeCamera";
  43985. };
  43986. __decorate([
  43987. BABYLON.serializeAsVector3()
  43988. ], FreeCamera.prototype, "ellipsoid", void 0);
  43989. __decorate([
  43990. BABYLON.serializeAsVector3()
  43991. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43992. __decorate([
  43993. BABYLON.serialize()
  43994. ], FreeCamera.prototype, "checkCollisions", void 0);
  43995. __decorate([
  43996. BABYLON.serialize()
  43997. ], FreeCamera.prototype, "applyGravity", void 0);
  43998. return FreeCamera;
  43999. }(BABYLON.TargetCamera));
  44000. BABYLON.FreeCamera = FreeCamera;
  44001. })(BABYLON || (BABYLON = {}));
  44002. //# sourceMappingURL=babylon.freeCamera.js.map
  44003. var BABYLON;
  44004. (function (BABYLON) {
  44005. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44006. function ArcRotateCameraKeyboardMoveInput() {
  44007. this._keys = new Array();
  44008. this.keysUp = [38];
  44009. this.keysDown = [40];
  44010. this.keysLeft = [37];
  44011. this.keysRight = [39];
  44012. this.keysReset = [220];
  44013. this.panningSensibility = 50.0;
  44014. this.zoomingSensibility = 25.0;
  44015. this.useAltToZoom = true;
  44016. }
  44017. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44018. var _this = this;
  44019. if (this._onCanvasBlurObserver) {
  44020. return;
  44021. }
  44022. this._scene = this.camera.getScene();
  44023. this._engine = this._scene.getEngine();
  44024. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44025. _this._keys = [];
  44026. });
  44027. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44028. var evt = info.event;
  44029. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44030. _this._ctrlPressed = evt.ctrlKey;
  44031. _this._altPressed = evt.altKey;
  44032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44035. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44036. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44037. var index = _this._keys.indexOf(evt.keyCode);
  44038. if (index === -1) {
  44039. _this._keys.push(evt.keyCode);
  44040. }
  44041. if (evt.preventDefault) {
  44042. if (!noPreventDefault) {
  44043. evt.preventDefault();
  44044. }
  44045. }
  44046. }
  44047. }
  44048. else {
  44049. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44050. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44051. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44052. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44053. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44054. var index = _this._keys.indexOf(evt.keyCode);
  44055. if (index >= 0) {
  44056. _this._keys.splice(index, 1);
  44057. }
  44058. if (evt.preventDefault) {
  44059. if (!noPreventDefault) {
  44060. evt.preventDefault();
  44061. }
  44062. }
  44063. }
  44064. }
  44065. });
  44066. };
  44067. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44068. if (this._scene) {
  44069. if (this._onKeyboardObserver) {
  44070. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44071. }
  44072. if (this._onCanvasBlurObserver) {
  44073. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44074. }
  44075. this._onKeyboardObserver = null;
  44076. this._onCanvasBlurObserver = null;
  44077. }
  44078. this._keys = [];
  44079. };
  44080. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44081. if (this._onKeyboardObserver) {
  44082. var camera = this.camera;
  44083. for (var index = 0; index < this._keys.length; index++) {
  44084. var keyCode = this._keys[index];
  44085. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44086. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44087. camera.inertialPanningX -= 1 / this.panningSensibility;
  44088. }
  44089. else {
  44090. camera.inertialAlphaOffset -= 0.01;
  44091. }
  44092. }
  44093. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44094. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44095. camera.inertialPanningY += 1 / this.panningSensibility;
  44096. }
  44097. else if (this._altPressed && this.useAltToZoom) {
  44098. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44099. }
  44100. else {
  44101. camera.inertialBetaOffset -= 0.01;
  44102. }
  44103. }
  44104. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44105. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44106. camera.inertialPanningX += 1 / this.panningSensibility;
  44107. }
  44108. else {
  44109. camera.inertialAlphaOffset += 0.01;
  44110. }
  44111. }
  44112. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44113. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44114. camera.inertialPanningY -= 1 / this.panningSensibility;
  44115. }
  44116. else if (this._altPressed && this.useAltToZoom) {
  44117. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44118. }
  44119. else {
  44120. camera.inertialBetaOffset += 0.01;
  44121. }
  44122. }
  44123. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44124. camera.restoreState();
  44125. }
  44126. }
  44127. }
  44128. };
  44129. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44130. return "ArcRotateCameraKeyboardMoveInput";
  44131. };
  44132. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44133. return "keyboard";
  44134. };
  44135. __decorate([
  44136. BABYLON.serialize()
  44137. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44138. __decorate([
  44139. BABYLON.serialize()
  44140. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44141. __decorate([
  44142. BABYLON.serialize()
  44143. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44144. __decorate([
  44145. BABYLON.serialize()
  44146. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44147. __decorate([
  44148. BABYLON.serialize()
  44149. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44150. __decorate([
  44151. BABYLON.serialize()
  44152. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44153. __decorate([
  44154. BABYLON.serialize()
  44155. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44156. __decorate([
  44157. BABYLON.serialize()
  44158. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44159. return ArcRotateCameraKeyboardMoveInput;
  44160. }());
  44161. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44162. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44163. })(BABYLON || (BABYLON = {}));
  44164. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44165. var BABYLON;
  44166. (function (BABYLON) {
  44167. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44168. function ArcRotateCameraMouseWheelInput() {
  44169. this.wheelPrecision = 3.0;
  44170. /**
  44171. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44172. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44173. */
  44174. this.wheelDeltaPercentage = 0;
  44175. }
  44176. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44177. var _this = this;
  44178. this._wheel = function (p, s) {
  44179. //sanity check - this should be a PointerWheel event.
  44180. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44181. return;
  44182. var event = p.event;
  44183. var delta = 0;
  44184. if (event.wheelDelta) {
  44185. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44186. }
  44187. else if (event.detail) {
  44188. delta = -event.detail / _this.wheelPrecision;
  44189. }
  44190. if (delta)
  44191. _this.camera.inertialRadiusOffset += delta;
  44192. if (event.preventDefault) {
  44193. if (!noPreventDefault) {
  44194. event.preventDefault();
  44195. }
  44196. }
  44197. };
  44198. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44199. };
  44200. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44201. if (this._observer && element) {
  44202. this.camera.getScene().onPointerObservable.remove(this._observer);
  44203. this._observer = null;
  44204. this._wheel = null;
  44205. }
  44206. };
  44207. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44208. return "ArcRotateCameraMouseWheelInput";
  44209. };
  44210. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44211. return "mousewheel";
  44212. };
  44213. __decorate([
  44214. BABYLON.serialize()
  44215. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44216. __decorate([
  44217. BABYLON.serialize()
  44218. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44219. return ArcRotateCameraMouseWheelInput;
  44220. }());
  44221. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44222. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44223. })(BABYLON || (BABYLON = {}));
  44224. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44225. var BABYLON;
  44226. (function (BABYLON) {
  44227. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44228. function ArcRotateCameraPointersInput() {
  44229. this.buttons = [0, 1, 2];
  44230. this.angularSensibilityX = 1000.0;
  44231. this.angularSensibilityY = 1000.0;
  44232. this.pinchPrecision = 12.0;
  44233. /**
  44234. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44235. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44236. */
  44237. this.pinchDeltaPercentage = 0;
  44238. this.panningSensibility = 1000.0;
  44239. this.multiTouchPanning = true;
  44240. this.multiTouchPanAndZoom = true;
  44241. this._isPanClick = false;
  44242. this.pinchInwards = true;
  44243. }
  44244. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44245. var _this = this;
  44246. var engine = this.camera.getEngine();
  44247. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44248. var pointA = null;
  44249. var pointB = null;
  44250. var previousPinchSquaredDistance = 0;
  44251. var initialDistance = 0;
  44252. var twoFingerActivityCount = 0;
  44253. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44254. this._pointerInput = function (p, s) {
  44255. var evt = p.event;
  44256. var isTouch = p.event.pointerType === "touch";
  44257. if (engine.isInVRExclusivePointerMode) {
  44258. return;
  44259. }
  44260. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44261. return;
  44262. }
  44263. var srcElement = (evt.srcElement || evt.target);
  44264. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44265. try {
  44266. srcElement.setPointerCapture(evt.pointerId);
  44267. }
  44268. catch (e) {
  44269. //Nothing to do with the error. Execution will continue.
  44270. }
  44271. // Manage panning with pan button click
  44272. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44273. // manage pointers
  44274. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44275. if (pointA === null) {
  44276. pointA = cacheSoloPointer;
  44277. }
  44278. else if (pointB === null) {
  44279. pointB = cacheSoloPointer;
  44280. }
  44281. if (!noPreventDefault) {
  44282. evt.preventDefault();
  44283. element.focus();
  44284. }
  44285. }
  44286. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44287. _this.camera.restoreState();
  44288. }
  44289. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44290. try {
  44291. srcElement.releasePointerCapture(evt.pointerId);
  44292. }
  44293. catch (e) {
  44294. //Nothing to do with the error.
  44295. }
  44296. cacheSoloPointer = null;
  44297. previousPinchSquaredDistance = 0;
  44298. previousMultiTouchPanPosition.isPaning = false;
  44299. previousMultiTouchPanPosition.isPinching = false;
  44300. twoFingerActivityCount = 0;
  44301. initialDistance = 0;
  44302. if (!isTouch) {
  44303. pointB = null; // Mouse and pen are mono pointer
  44304. }
  44305. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44306. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44307. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44308. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44309. if (engine.badOS) {
  44310. pointA = pointB = null;
  44311. }
  44312. else {
  44313. //only remove the impacted pointer in case of multitouch allowing on most
  44314. //platforms switching from rotate to zoom and pan seamlessly.
  44315. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44316. pointA = pointB;
  44317. pointB = null;
  44318. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44319. }
  44320. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44321. pointB = null;
  44322. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44323. }
  44324. else {
  44325. pointA = pointB = null;
  44326. }
  44327. }
  44328. if (!noPreventDefault) {
  44329. evt.preventDefault();
  44330. }
  44331. }
  44332. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44333. if (!noPreventDefault) {
  44334. evt.preventDefault();
  44335. }
  44336. // One button down
  44337. if (pointA && pointB === null && cacheSoloPointer) {
  44338. if (_this.panningSensibility !== 0 &&
  44339. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44340. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44341. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44342. }
  44343. else {
  44344. var offsetX = evt.clientX - cacheSoloPointer.x;
  44345. var offsetY = evt.clientY - cacheSoloPointer.y;
  44346. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44347. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44348. }
  44349. cacheSoloPointer.x = evt.clientX;
  44350. cacheSoloPointer.y = evt.clientY;
  44351. }
  44352. else if (pointA && pointB) {
  44353. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44354. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44355. ed.x = evt.clientX;
  44356. ed.y = evt.clientY;
  44357. var direction = _this.pinchInwards ? 1 : -1;
  44358. var distX = pointA.x - pointB.x;
  44359. var distY = pointA.y - pointB.y;
  44360. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44361. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44362. if (previousPinchSquaredDistance === 0) {
  44363. initialDistance = pinchDistance;
  44364. previousPinchSquaredDistance = pinchSquaredDistance;
  44365. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44366. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44367. return;
  44368. }
  44369. if (_this.multiTouchPanAndZoom) {
  44370. if (_this.pinchDeltaPercentage) {
  44371. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44372. }
  44373. else {
  44374. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44375. (_this.pinchPrecision *
  44376. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44377. direction);
  44378. }
  44379. if (_this.panningSensibility !== 0) {
  44380. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44381. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44382. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44383. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44384. previousMultiTouchPanPosition.x = pointersCenterX;
  44385. previousMultiTouchPanPosition.y = pointersCenterY;
  44386. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44387. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44388. }
  44389. }
  44390. else {
  44391. twoFingerActivityCount++;
  44392. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44393. if (_this.pinchDeltaPercentage) {
  44394. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44395. }
  44396. else {
  44397. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44398. (_this.pinchPrecision *
  44399. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44400. direction);
  44401. }
  44402. previousMultiTouchPanPosition.isPaning = false;
  44403. previousMultiTouchPanPosition.isPinching = true;
  44404. }
  44405. else {
  44406. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44407. if (!previousMultiTouchPanPosition.isPaning) {
  44408. previousMultiTouchPanPosition.isPaning = true;
  44409. previousMultiTouchPanPosition.isPinching = false;
  44410. previousMultiTouchPanPosition.x = ed.x;
  44411. previousMultiTouchPanPosition.y = ed.y;
  44412. return;
  44413. }
  44414. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44415. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44416. }
  44417. }
  44418. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44419. previousMultiTouchPanPosition.x = ed.x;
  44420. previousMultiTouchPanPosition.y = ed.y;
  44421. }
  44422. }
  44423. previousPinchSquaredDistance = pinchSquaredDistance;
  44424. }
  44425. }
  44426. };
  44427. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44428. this._onContextMenu = function (evt) {
  44429. evt.preventDefault();
  44430. };
  44431. if (!this.camera._useCtrlForPanning) {
  44432. element.addEventListener("contextmenu", this._onContextMenu, false);
  44433. }
  44434. this._onLostFocus = function () {
  44435. //this._keys = [];
  44436. pointA = pointB = null;
  44437. previousPinchSquaredDistance = 0;
  44438. previousMultiTouchPanPosition.isPaning = false;
  44439. previousMultiTouchPanPosition.isPinching = false;
  44440. twoFingerActivityCount = 0;
  44441. cacheSoloPointer = null;
  44442. initialDistance = 0;
  44443. };
  44444. this._onMouseMove = function (evt) {
  44445. if (!engine.isPointerLock) {
  44446. return;
  44447. }
  44448. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44449. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44450. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44451. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44452. if (!noPreventDefault) {
  44453. evt.preventDefault();
  44454. }
  44455. };
  44456. this._onGestureStart = function (e) {
  44457. if (window.MSGesture === undefined) {
  44458. return;
  44459. }
  44460. if (!_this._MSGestureHandler) {
  44461. _this._MSGestureHandler = new MSGesture();
  44462. _this._MSGestureHandler.target = element;
  44463. }
  44464. _this._MSGestureHandler.addPointer(e.pointerId);
  44465. };
  44466. this._onGesture = function (e) {
  44467. _this.camera.radius *= e.scale;
  44468. if (e.preventDefault) {
  44469. if (!noPreventDefault) {
  44470. e.stopPropagation();
  44471. e.preventDefault();
  44472. }
  44473. }
  44474. };
  44475. element.addEventListener("mousemove", this._onMouseMove, false);
  44476. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44477. element.addEventListener("MSGestureChange", this._onGesture, false);
  44478. BABYLON.Tools.RegisterTopRootEvents([
  44479. { name: "blur", handler: this._onLostFocus }
  44480. ]);
  44481. };
  44482. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44483. if (this._onLostFocus) {
  44484. BABYLON.Tools.UnregisterTopRootEvents([
  44485. { name: "blur", handler: this._onLostFocus }
  44486. ]);
  44487. }
  44488. if (element && this._observer) {
  44489. this.camera.getScene().onPointerObservable.remove(this._observer);
  44490. this._observer = null;
  44491. if (this._onContextMenu) {
  44492. element.removeEventListener("contextmenu", this._onContextMenu);
  44493. }
  44494. if (this._onMouseMove) {
  44495. element.removeEventListener("mousemove", this._onMouseMove);
  44496. }
  44497. if (this._onGestureStart) {
  44498. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44499. }
  44500. if (this._onGesture) {
  44501. element.removeEventListener("MSGestureChange", this._onGesture);
  44502. }
  44503. this._isPanClick = false;
  44504. this.pinchInwards = true;
  44505. this._onMouseMove = null;
  44506. this._onGestureStart = null;
  44507. this._onGesture = null;
  44508. this._MSGestureHandler = null;
  44509. this._onLostFocus = null;
  44510. this._onContextMenu = null;
  44511. }
  44512. };
  44513. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44514. return "ArcRotateCameraPointersInput";
  44515. };
  44516. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44517. return "pointers";
  44518. };
  44519. __decorate([
  44520. BABYLON.serialize()
  44521. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44522. __decorate([
  44523. BABYLON.serialize()
  44524. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44525. __decorate([
  44526. BABYLON.serialize()
  44527. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44528. __decorate([
  44529. BABYLON.serialize()
  44530. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44531. __decorate([
  44532. BABYLON.serialize()
  44533. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44534. __decorate([
  44535. BABYLON.serialize()
  44536. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44537. __decorate([
  44538. BABYLON.serialize()
  44539. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44540. __decorate([
  44541. BABYLON.serialize()
  44542. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44543. return ArcRotateCameraPointersInput;
  44544. }());
  44545. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44546. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44547. })(BABYLON || (BABYLON = {}));
  44548. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44549. var BABYLON;
  44550. (function (BABYLON) {
  44551. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44552. __extends(ArcRotateCameraInputsManager, _super);
  44553. function ArcRotateCameraInputsManager(camera) {
  44554. return _super.call(this, camera) || this;
  44555. }
  44556. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44557. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44558. return this;
  44559. };
  44560. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44561. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44562. return this;
  44563. };
  44564. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44565. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44566. return this;
  44567. };
  44568. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44569. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44570. return this;
  44571. };
  44572. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44573. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44574. return this;
  44575. };
  44576. return ArcRotateCameraInputsManager;
  44577. }(BABYLON.CameraInputsManager));
  44578. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44579. })(BABYLON || (BABYLON = {}));
  44580. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44581. var BABYLON;
  44582. (function (BABYLON) {
  44583. var ArcRotateCamera = /** @class */ (function (_super) {
  44584. __extends(ArcRotateCamera, _super);
  44585. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44586. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44587. _this.inertialAlphaOffset = 0;
  44588. _this.inertialBetaOffset = 0;
  44589. _this.inertialRadiusOffset = 0;
  44590. _this.lowerAlphaLimit = null;
  44591. _this.upperAlphaLimit = null;
  44592. _this.lowerBetaLimit = 0.01;
  44593. _this.upperBetaLimit = Math.PI;
  44594. _this.lowerRadiusLimit = null;
  44595. _this.upperRadiusLimit = null;
  44596. _this.inertialPanningX = 0;
  44597. _this.inertialPanningY = 0;
  44598. _this.pinchToPanMaxDistance = 20;
  44599. _this.panningDistanceLimit = null;
  44600. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44601. _this.panningInertia = 0.9;
  44602. //-- end properties for backward compatibility for inputs
  44603. _this.zoomOnFactor = 1;
  44604. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44605. _this.allowUpsideDown = true;
  44606. _this._viewMatrix = new BABYLON.Matrix();
  44607. // Panning
  44608. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44609. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44610. _this.checkCollisions = false;
  44611. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44612. _this._previousPosition = BABYLON.Vector3.Zero();
  44613. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44614. _this._newPosition = BABYLON.Vector3.Zero();
  44615. _this._computationVector = BABYLON.Vector3.Zero();
  44616. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44617. if (collidedMesh === void 0) { collidedMesh = null; }
  44618. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44619. newPosition.multiplyInPlace(_this._collider._radius);
  44620. }
  44621. if (!collidedMesh) {
  44622. _this._previousPosition.copyFrom(_this.position);
  44623. }
  44624. else {
  44625. _this.setPosition(newPosition);
  44626. if (_this.onCollide) {
  44627. _this.onCollide(collidedMesh);
  44628. }
  44629. }
  44630. // Recompute because of constraints
  44631. var cosa = Math.cos(_this.alpha);
  44632. var sina = Math.sin(_this.alpha);
  44633. var cosb = Math.cos(_this.beta);
  44634. var sinb = Math.sin(_this.beta);
  44635. if (sinb === 0) {
  44636. sinb = 0.0001;
  44637. }
  44638. var target = _this._getTargetPosition();
  44639. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44640. target.addToRef(_this._computationVector, _this._newPosition);
  44641. _this.position.copyFrom(_this._newPosition);
  44642. var up = _this.upVector;
  44643. if (_this.allowUpsideDown && _this.beta < 0) {
  44644. up = up.clone();
  44645. up = up.negate();
  44646. }
  44647. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44648. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44649. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44650. _this._collisionTriggered = false;
  44651. };
  44652. _this._target = BABYLON.Vector3.Zero();
  44653. if (target) {
  44654. _this.setTarget(target);
  44655. }
  44656. _this.alpha = alpha;
  44657. _this.beta = beta;
  44658. _this.radius = radius;
  44659. _this.getViewMatrix();
  44660. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44661. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44662. return _this;
  44663. }
  44664. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44665. get: function () {
  44666. return this._target;
  44667. },
  44668. set: function (value) {
  44669. this.setTarget(value);
  44670. },
  44671. enumerable: true,
  44672. configurable: true
  44673. });
  44674. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44675. //-- begin properties for backward compatibility for inputs
  44676. get: function () {
  44677. var pointers = this.inputs.attached["pointers"];
  44678. if (pointers)
  44679. return pointers.angularSensibilityX;
  44680. return 0;
  44681. },
  44682. set: function (value) {
  44683. var pointers = this.inputs.attached["pointers"];
  44684. if (pointers) {
  44685. pointers.angularSensibilityX = value;
  44686. }
  44687. },
  44688. enumerable: true,
  44689. configurable: true
  44690. });
  44691. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44692. get: function () {
  44693. var pointers = this.inputs.attached["pointers"];
  44694. if (pointers)
  44695. return pointers.angularSensibilityY;
  44696. return 0;
  44697. },
  44698. set: function (value) {
  44699. var pointers = this.inputs.attached["pointers"];
  44700. if (pointers) {
  44701. pointers.angularSensibilityY = value;
  44702. }
  44703. },
  44704. enumerable: true,
  44705. configurable: true
  44706. });
  44707. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44708. get: function () {
  44709. var pointers = this.inputs.attached["pointers"];
  44710. if (pointers)
  44711. return pointers.pinchPrecision;
  44712. return 0;
  44713. },
  44714. set: function (value) {
  44715. var pointers = this.inputs.attached["pointers"];
  44716. if (pointers) {
  44717. pointers.pinchPrecision = value;
  44718. }
  44719. },
  44720. enumerable: true,
  44721. configurable: true
  44722. });
  44723. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44724. get: function () {
  44725. var pointers = this.inputs.attached["pointers"];
  44726. if (pointers)
  44727. return pointers.pinchDeltaPercentage;
  44728. return 0;
  44729. },
  44730. set: function (value) {
  44731. var pointers = this.inputs.attached["pointers"];
  44732. if (pointers) {
  44733. pointers.pinchDeltaPercentage = value;
  44734. }
  44735. },
  44736. enumerable: true,
  44737. configurable: true
  44738. });
  44739. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44740. get: function () {
  44741. var pointers = this.inputs.attached["pointers"];
  44742. if (pointers)
  44743. return pointers.panningSensibility;
  44744. return 0;
  44745. },
  44746. set: function (value) {
  44747. var pointers = this.inputs.attached["pointers"];
  44748. if (pointers) {
  44749. pointers.panningSensibility = value;
  44750. }
  44751. },
  44752. enumerable: true,
  44753. configurable: true
  44754. });
  44755. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44756. get: function () {
  44757. var keyboard = this.inputs.attached["keyboard"];
  44758. if (keyboard)
  44759. return keyboard.keysUp;
  44760. return [];
  44761. },
  44762. set: function (value) {
  44763. var keyboard = this.inputs.attached["keyboard"];
  44764. if (keyboard)
  44765. keyboard.keysUp = value;
  44766. },
  44767. enumerable: true,
  44768. configurable: true
  44769. });
  44770. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44771. get: function () {
  44772. var keyboard = this.inputs.attached["keyboard"];
  44773. if (keyboard)
  44774. return keyboard.keysDown;
  44775. return [];
  44776. },
  44777. set: function (value) {
  44778. var keyboard = this.inputs.attached["keyboard"];
  44779. if (keyboard)
  44780. keyboard.keysDown = value;
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44786. get: function () {
  44787. var keyboard = this.inputs.attached["keyboard"];
  44788. if (keyboard)
  44789. return keyboard.keysLeft;
  44790. return [];
  44791. },
  44792. set: function (value) {
  44793. var keyboard = this.inputs.attached["keyboard"];
  44794. if (keyboard)
  44795. keyboard.keysLeft = value;
  44796. },
  44797. enumerable: true,
  44798. configurable: true
  44799. });
  44800. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44801. get: function () {
  44802. var keyboard = this.inputs.attached["keyboard"];
  44803. if (keyboard)
  44804. return keyboard.keysRight;
  44805. return [];
  44806. },
  44807. set: function (value) {
  44808. var keyboard = this.inputs.attached["keyboard"];
  44809. if (keyboard)
  44810. keyboard.keysRight = value;
  44811. },
  44812. enumerable: true,
  44813. configurable: true
  44814. });
  44815. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44816. get: function () {
  44817. var mousewheel = this.inputs.attached["mousewheel"];
  44818. if (mousewheel)
  44819. return mousewheel.wheelPrecision;
  44820. return 0;
  44821. },
  44822. set: function (value) {
  44823. var mousewheel = this.inputs.attached["mousewheel"];
  44824. if (mousewheel)
  44825. mousewheel.wheelPrecision = value;
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44831. get: function () {
  44832. var mousewheel = this.inputs.attached["mousewheel"];
  44833. if (mousewheel)
  44834. return mousewheel.wheelDeltaPercentage;
  44835. return 0;
  44836. },
  44837. set: function (value) {
  44838. var mousewheel = this.inputs.attached["mousewheel"];
  44839. if (mousewheel)
  44840. mousewheel.wheelDeltaPercentage = value;
  44841. },
  44842. enumerable: true,
  44843. configurable: true
  44844. });
  44845. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44846. get: function () {
  44847. return this._bouncingBehavior;
  44848. },
  44849. enumerable: true,
  44850. configurable: true
  44851. });
  44852. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44853. get: function () {
  44854. return this._bouncingBehavior != null;
  44855. },
  44856. set: function (value) {
  44857. if (value === this.useBouncingBehavior) {
  44858. return;
  44859. }
  44860. if (value) {
  44861. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44862. this.addBehavior(this._bouncingBehavior);
  44863. }
  44864. else if (this._bouncingBehavior) {
  44865. this.removeBehavior(this._bouncingBehavior);
  44866. this._bouncingBehavior = null;
  44867. }
  44868. },
  44869. enumerable: true,
  44870. configurable: true
  44871. });
  44872. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44873. get: function () {
  44874. return this._framingBehavior;
  44875. },
  44876. enumerable: true,
  44877. configurable: true
  44878. });
  44879. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44880. get: function () {
  44881. return this._framingBehavior != null;
  44882. },
  44883. set: function (value) {
  44884. if (value === this.useFramingBehavior) {
  44885. return;
  44886. }
  44887. if (value) {
  44888. this._framingBehavior = new BABYLON.FramingBehavior();
  44889. this.addBehavior(this._framingBehavior);
  44890. }
  44891. else if (this._framingBehavior) {
  44892. this.removeBehavior(this._framingBehavior);
  44893. this._framingBehavior = null;
  44894. }
  44895. },
  44896. enumerable: true,
  44897. configurable: true
  44898. });
  44899. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44900. get: function () {
  44901. return this._autoRotationBehavior;
  44902. },
  44903. enumerable: true,
  44904. configurable: true
  44905. });
  44906. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44907. get: function () {
  44908. return this._autoRotationBehavior != null;
  44909. },
  44910. set: function (value) {
  44911. if (value === this.useAutoRotationBehavior) {
  44912. return;
  44913. }
  44914. if (value) {
  44915. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44916. this.addBehavior(this._autoRotationBehavior);
  44917. }
  44918. else if (this._autoRotationBehavior) {
  44919. this.removeBehavior(this._autoRotationBehavior);
  44920. this._autoRotationBehavior = null;
  44921. }
  44922. },
  44923. enumerable: true,
  44924. configurable: true
  44925. });
  44926. // Cache
  44927. ArcRotateCamera.prototype._initCache = function () {
  44928. _super.prototype._initCache.call(this);
  44929. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44930. this._cache.alpha = undefined;
  44931. this._cache.beta = undefined;
  44932. this._cache.radius = undefined;
  44933. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44934. };
  44935. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44936. if (!ignoreParentClass) {
  44937. _super.prototype._updateCache.call(this);
  44938. }
  44939. this._cache._target.copyFrom(this._getTargetPosition());
  44940. this._cache.alpha = this.alpha;
  44941. this._cache.beta = this.beta;
  44942. this._cache.radius = this.radius;
  44943. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44944. };
  44945. ArcRotateCamera.prototype._getTargetPosition = function () {
  44946. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44947. var pos = this._targetHost.getAbsolutePosition();
  44948. if (this._targetBoundingCenter) {
  44949. pos.addToRef(this._targetBoundingCenter, this._target);
  44950. }
  44951. else {
  44952. this._target.copyFrom(pos);
  44953. }
  44954. }
  44955. var lockedTargetPosition = this._getLockedTargetPosition();
  44956. if (lockedTargetPosition) {
  44957. return lockedTargetPosition;
  44958. }
  44959. return this._target;
  44960. };
  44961. ArcRotateCamera.prototype.storeState = function () {
  44962. this._storedAlpha = this.alpha;
  44963. this._storedBeta = this.beta;
  44964. this._storedRadius = this.radius;
  44965. this._storedTarget = this._getTargetPosition().clone();
  44966. return _super.prototype.storeState.call(this);
  44967. };
  44968. /**
  44969. * Restored camera state. You must call storeState() first
  44970. */
  44971. ArcRotateCamera.prototype._restoreStateValues = function () {
  44972. if (!_super.prototype._restoreStateValues.call(this)) {
  44973. return false;
  44974. }
  44975. this.alpha = this._storedAlpha;
  44976. this.beta = this._storedBeta;
  44977. this.radius = this._storedRadius;
  44978. this.setTarget(this._storedTarget.clone());
  44979. this.inertialAlphaOffset = 0;
  44980. this.inertialBetaOffset = 0;
  44981. this.inertialRadiusOffset = 0;
  44982. this.inertialPanningX = 0;
  44983. this.inertialPanningY = 0;
  44984. return true;
  44985. };
  44986. // Synchronized
  44987. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44988. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44989. return false;
  44990. return this._cache._target.equals(this._getTargetPosition())
  44991. && this._cache.alpha === this.alpha
  44992. && this._cache.beta === this.beta
  44993. && this._cache.radius === this.radius
  44994. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44995. };
  44996. // Methods
  44997. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44998. var _this = this;
  44999. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45000. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45001. this._useCtrlForPanning = useCtrlForPanning;
  45002. this._panningMouseButton = panningMouseButton;
  45003. this.inputs.attachElement(element, noPreventDefault);
  45004. this._reset = function () {
  45005. _this.inertialAlphaOffset = 0;
  45006. _this.inertialBetaOffset = 0;
  45007. _this.inertialRadiusOffset = 0;
  45008. _this.inertialPanningX = 0;
  45009. _this.inertialPanningY = 0;
  45010. };
  45011. };
  45012. ArcRotateCamera.prototype.detachControl = function (element) {
  45013. this.inputs.detachElement(element);
  45014. if (this._reset) {
  45015. this._reset();
  45016. }
  45017. };
  45018. ArcRotateCamera.prototype._checkInputs = function () {
  45019. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45020. if (this._collisionTriggered) {
  45021. return;
  45022. }
  45023. this.inputs.checkInputs();
  45024. // Inertia
  45025. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45026. if (this.getScene().useRightHandedSystem) {
  45027. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45028. }
  45029. else {
  45030. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45031. }
  45032. this.beta += this.inertialBetaOffset;
  45033. this.radius -= this.inertialRadiusOffset;
  45034. this.inertialAlphaOffset *= this.inertia;
  45035. this.inertialBetaOffset *= this.inertia;
  45036. this.inertialRadiusOffset *= this.inertia;
  45037. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45038. this.inertialAlphaOffset = 0;
  45039. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45040. this.inertialBetaOffset = 0;
  45041. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45042. this.inertialRadiusOffset = 0;
  45043. }
  45044. // Panning inertia
  45045. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45046. if (!this._localDirection) {
  45047. this._localDirection = BABYLON.Vector3.Zero();
  45048. this._transformedDirection = BABYLON.Vector3.Zero();
  45049. }
  45050. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45051. this._localDirection.multiplyInPlace(this.panningAxis);
  45052. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45053. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45054. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45055. if (!this.panningAxis.y) {
  45056. this._transformedDirection.y = 0;
  45057. }
  45058. if (!this._targetHost) {
  45059. if (this.panningDistanceLimit) {
  45060. this._transformedDirection.addInPlace(this._target);
  45061. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45062. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45063. this._target.copyFrom(this._transformedDirection);
  45064. }
  45065. }
  45066. else {
  45067. this._target.addInPlace(this._transformedDirection);
  45068. }
  45069. }
  45070. this.inertialPanningX *= this.panningInertia;
  45071. this.inertialPanningY *= this.panningInertia;
  45072. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45073. this.inertialPanningX = 0;
  45074. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45075. this.inertialPanningY = 0;
  45076. }
  45077. // Limits
  45078. this._checkLimits();
  45079. _super.prototype._checkInputs.call(this);
  45080. };
  45081. ArcRotateCamera.prototype._checkLimits = function () {
  45082. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45083. if (this.allowUpsideDown && this.beta > Math.PI) {
  45084. this.beta = this.beta - (2 * Math.PI);
  45085. }
  45086. }
  45087. else {
  45088. if (this.beta < this.lowerBetaLimit) {
  45089. this.beta = this.lowerBetaLimit;
  45090. }
  45091. }
  45092. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45093. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45094. this.beta = this.beta + (2 * Math.PI);
  45095. }
  45096. }
  45097. else {
  45098. if (this.beta > this.upperBetaLimit) {
  45099. this.beta = this.upperBetaLimit;
  45100. }
  45101. }
  45102. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45103. this.alpha = this.lowerAlphaLimit;
  45104. }
  45105. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45106. this.alpha = this.upperAlphaLimit;
  45107. }
  45108. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45109. this.radius = this.lowerRadiusLimit;
  45110. }
  45111. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45112. this.radius = this.upperRadiusLimit;
  45113. }
  45114. };
  45115. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45116. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45117. this.radius = this._computationVector.length();
  45118. if (this.radius === 0) {
  45119. this.radius = 0.0001; // Just to avoid division by zero
  45120. }
  45121. // Alpha
  45122. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45123. if (this._computationVector.z < 0) {
  45124. this.alpha = 2 * Math.PI - this.alpha;
  45125. }
  45126. // Beta
  45127. this.beta = Math.acos(this._computationVector.y / this.radius);
  45128. this._checkLimits();
  45129. };
  45130. ArcRotateCamera.prototype.setPosition = function (position) {
  45131. if (this.position.equals(position)) {
  45132. return;
  45133. }
  45134. this.position.copyFrom(position);
  45135. this.rebuildAnglesAndRadius();
  45136. };
  45137. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45138. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45139. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45140. if (target.getBoundingInfo) {
  45141. if (toBoundingCenter) {
  45142. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45143. }
  45144. else {
  45145. this._targetBoundingCenter = null;
  45146. }
  45147. this._targetHost = target;
  45148. this._target = this._getTargetPosition();
  45149. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45150. }
  45151. else {
  45152. var newTarget = target;
  45153. var currentTarget = this._getTargetPosition();
  45154. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45155. return;
  45156. }
  45157. this._targetHost = null;
  45158. this._target = newTarget;
  45159. this._targetBoundingCenter = null;
  45160. this.onMeshTargetChangedObservable.notifyObservers(null);
  45161. }
  45162. this.rebuildAnglesAndRadius();
  45163. };
  45164. ArcRotateCamera.prototype._getViewMatrix = function () {
  45165. // Compute
  45166. var cosa = Math.cos(this.alpha);
  45167. var sina = Math.sin(this.alpha);
  45168. var cosb = Math.cos(this.beta);
  45169. var sinb = Math.sin(this.beta);
  45170. if (sinb === 0) {
  45171. sinb = 0.0001;
  45172. }
  45173. var target = this._getTargetPosition();
  45174. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45175. target.addToRef(this._computationVector, this._newPosition);
  45176. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45177. if (!this._collider) {
  45178. this._collider = new BABYLON.Collider();
  45179. }
  45180. this._collider._radius = this.collisionRadius;
  45181. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45182. this._collisionTriggered = true;
  45183. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45184. }
  45185. else {
  45186. this.position.copyFrom(this._newPosition);
  45187. var up = this.upVector;
  45188. if (this.allowUpsideDown && sinb < 0) {
  45189. up = up.clone();
  45190. up = up.negate();
  45191. }
  45192. if (this.getScene().useRightHandedSystem) {
  45193. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45194. }
  45195. else {
  45196. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45197. }
  45198. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45199. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45200. }
  45201. this._currentTarget = target;
  45202. return this._viewMatrix;
  45203. };
  45204. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45205. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45206. meshes = meshes || this.getScene().meshes;
  45207. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45208. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45209. this.radius = distance * this.zoomOnFactor;
  45210. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45211. };
  45212. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45213. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45214. var meshesOrMinMaxVector;
  45215. var distance;
  45216. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45217. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45218. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45219. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45220. }
  45221. else {
  45222. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45223. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45224. distance = minMaxVectorAndDistance.distance;
  45225. }
  45226. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45227. if (!doNotUpdateMaxZ) {
  45228. this.maxZ = distance * 2;
  45229. }
  45230. };
  45231. /**
  45232. * @override
  45233. * Override Camera.createRigCamera
  45234. */
  45235. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45236. var alphaShift = 0;
  45237. switch (this.cameraRigMode) {
  45238. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45239. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45240. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45241. case BABYLON.Camera.RIG_MODE_VR:
  45242. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45243. break;
  45244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45245. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45246. break;
  45247. }
  45248. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45249. rigCam._cameraRigParams = {};
  45250. return rigCam;
  45251. };
  45252. /**
  45253. * @override
  45254. * Override Camera._updateRigCameras
  45255. */
  45256. ArcRotateCamera.prototype._updateRigCameras = function () {
  45257. var camLeft = this._rigCameras[0];
  45258. var camRight = this._rigCameras[1];
  45259. camLeft.beta = camRight.beta = this.beta;
  45260. camLeft.radius = camRight.radius = this.radius;
  45261. switch (this.cameraRigMode) {
  45262. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45263. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45265. case BABYLON.Camera.RIG_MODE_VR:
  45266. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45267. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45268. break;
  45269. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45270. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45271. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45272. break;
  45273. }
  45274. _super.prototype._updateRigCameras.call(this);
  45275. };
  45276. ArcRotateCamera.prototype.dispose = function () {
  45277. this.inputs.clear();
  45278. _super.prototype.dispose.call(this);
  45279. };
  45280. ArcRotateCamera.prototype.getClassName = function () {
  45281. return "ArcRotateCamera";
  45282. };
  45283. __decorate([
  45284. BABYLON.serialize()
  45285. ], ArcRotateCamera.prototype, "alpha", void 0);
  45286. __decorate([
  45287. BABYLON.serialize()
  45288. ], ArcRotateCamera.prototype, "beta", void 0);
  45289. __decorate([
  45290. BABYLON.serialize()
  45291. ], ArcRotateCamera.prototype, "radius", void 0);
  45292. __decorate([
  45293. BABYLON.serializeAsVector3("target")
  45294. ], ArcRotateCamera.prototype, "_target", void 0);
  45295. __decorate([
  45296. BABYLON.serialize()
  45297. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45298. __decorate([
  45299. BABYLON.serialize()
  45300. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45301. __decorate([
  45302. BABYLON.serialize()
  45303. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45304. __decorate([
  45305. BABYLON.serialize()
  45306. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45307. __decorate([
  45308. BABYLON.serialize()
  45309. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45310. __decorate([
  45311. BABYLON.serialize()
  45312. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45313. __decorate([
  45314. BABYLON.serialize()
  45315. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45316. __decorate([
  45317. BABYLON.serialize()
  45318. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45319. __decorate([
  45320. BABYLON.serialize()
  45321. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45322. __decorate([
  45323. BABYLON.serialize()
  45324. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45328. __decorate([
  45329. BABYLON.serialize()
  45330. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45331. __decorate([
  45332. BABYLON.serialize()
  45333. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45334. __decorate([
  45335. BABYLON.serializeAsVector3()
  45336. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45337. __decorate([
  45338. BABYLON.serialize()
  45339. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45340. __decorate([
  45341. BABYLON.serialize()
  45342. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45343. __decorate([
  45344. BABYLON.serialize()
  45345. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45346. return ArcRotateCamera;
  45347. }(BABYLON.TargetCamera));
  45348. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45349. })(BABYLON || (BABYLON = {}));
  45350. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45351. var BABYLON;
  45352. (function (BABYLON) {
  45353. /**
  45354. * The HemisphericLight simulates the ambient environment light,
  45355. * so the passed direction is the light reflection direction, not the incoming direction.
  45356. */
  45357. var HemisphericLight = /** @class */ (function (_super) {
  45358. __extends(HemisphericLight, _super);
  45359. /**
  45360. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45361. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45362. * The HemisphericLight can't cast shadows.
  45363. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45364. * @param name The friendly name of the light
  45365. * @param direction The direction of the light reflection
  45366. * @param scene The scene the light belongs to
  45367. */
  45368. function HemisphericLight(name, direction, scene) {
  45369. var _this = _super.call(this, name, scene) || this;
  45370. /**
  45371. * The groundColor is the light in the opposite direction to the one specified during creation.
  45372. * 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.
  45373. */
  45374. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45375. _this.direction = direction || BABYLON.Vector3.Up();
  45376. return _this;
  45377. }
  45378. HemisphericLight.prototype._buildUniformLayout = function () {
  45379. this._uniformBuffer.addUniform("vLightData", 4);
  45380. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45381. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45382. this._uniformBuffer.addUniform("vLightGround", 3);
  45383. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45384. this._uniformBuffer.addUniform("depthValues", 2);
  45385. this._uniformBuffer.create();
  45386. };
  45387. /**
  45388. * Returns the string "HemisphericLight".
  45389. * @return The class name
  45390. */
  45391. HemisphericLight.prototype.getClassName = function () {
  45392. return "HemisphericLight";
  45393. };
  45394. /**
  45395. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45396. * Returns the updated direction.
  45397. * @param target The target the direction should point to
  45398. * @return The computed direction
  45399. */
  45400. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45401. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45402. return this.direction;
  45403. };
  45404. /**
  45405. * Returns the shadow generator associated to the light.
  45406. * @returns Always null for hemispheric lights because it does not support shadows.
  45407. */
  45408. HemisphericLight.prototype.getShadowGenerator = function () {
  45409. return null;
  45410. };
  45411. /**
  45412. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45413. * @param effect The effect to update
  45414. * @param lightIndex The index of the light in the effect to update
  45415. * @returns The hemispheric light
  45416. */
  45417. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45418. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45419. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45420. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45421. return this;
  45422. };
  45423. /**
  45424. * @ignore internal use only.
  45425. */
  45426. HemisphericLight.prototype._getWorldMatrix = function () {
  45427. if (!this._worldMatrix) {
  45428. this._worldMatrix = BABYLON.Matrix.Identity();
  45429. }
  45430. return this._worldMatrix;
  45431. };
  45432. /**
  45433. * Returns the integer 3.
  45434. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45435. */
  45436. HemisphericLight.prototype.getTypeID = function () {
  45437. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45438. };
  45439. __decorate([
  45440. BABYLON.serializeAsColor3()
  45441. ], HemisphericLight.prototype, "groundColor", void 0);
  45442. __decorate([
  45443. BABYLON.serializeAsVector3()
  45444. ], HemisphericLight.prototype, "direction", void 0);
  45445. return HemisphericLight;
  45446. }(BABYLON.Light));
  45447. BABYLON.HemisphericLight = HemisphericLight;
  45448. })(BABYLON || (BABYLON = {}));
  45449. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45450. var BABYLON;
  45451. (function (BABYLON) {
  45452. /**
  45453. * Base implementation of @see IShadowLight
  45454. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45455. */
  45456. var ShadowLight = /** @class */ (function (_super) {
  45457. __extends(ShadowLight, _super);
  45458. function ShadowLight() {
  45459. var _this = _super !== null && _super.apply(this, arguments) || this;
  45460. _this._needProjectionMatrixCompute = true;
  45461. return _this;
  45462. }
  45463. ShadowLight.prototype._setPosition = function (value) {
  45464. this._position = value;
  45465. };
  45466. Object.defineProperty(ShadowLight.prototype, "position", {
  45467. /**
  45468. * Sets the position the shadow will be casted from. Also use as the light position for both
  45469. * point and spot lights.
  45470. */
  45471. get: function () {
  45472. return this._position;
  45473. },
  45474. /**
  45475. * Sets the position the shadow will be casted from. Also use as the light position for both
  45476. * point and spot lights.
  45477. */
  45478. set: function (value) {
  45479. this._setPosition(value);
  45480. },
  45481. enumerable: true,
  45482. configurable: true
  45483. });
  45484. ShadowLight.prototype._setDirection = function (value) {
  45485. this._direction = value;
  45486. };
  45487. Object.defineProperty(ShadowLight.prototype, "direction", {
  45488. /**
  45489. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45490. * Also use as the light direction on spot and directional lights.
  45491. */
  45492. get: function () {
  45493. return this._direction;
  45494. },
  45495. /**
  45496. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45497. * Also use as the light direction on spot and directional lights.
  45498. */
  45499. set: function (value) {
  45500. this._setDirection(value);
  45501. },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45506. /**
  45507. * Gets the shadow projection clipping minimum z value.
  45508. */
  45509. get: function () {
  45510. return this._shadowMinZ;
  45511. },
  45512. /**
  45513. * Sets the shadow projection clipping minimum z value.
  45514. */
  45515. set: function (value) {
  45516. this._shadowMinZ = value;
  45517. this.forceProjectionMatrixCompute();
  45518. },
  45519. enumerable: true,
  45520. configurable: true
  45521. });
  45522. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45523. /**
  45524. * Sets the shadow projection clipping maximum z value.
  45525. */
  45526. get: function () {
  45527. return this._shadowMaxZ;
  45528. },
  45529. /**
  45530. * Gets the shadow projection clipping maximum z value.
  45531. */
  45532. set: function (value) {
  45533. this._shadowMaxZ = value;
  45534. this.forceProjectionMatrixCompute();
  45535. },
  45536. enumerable: true,
  45537. configurable: true
  45538. });
  45539. /**
  45540. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45541. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45542. */
  45543. ShadowLight.prototype.computeTransformedInformation = function () {
  45544. if (this.parent && this.parent.getWorldMatrix) {
  45545. if (!this.transformedPosition) {
  45546. this.transformedPosition = BABYLON.Vector3.Zero();
  45547. }
  45548. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45549. // In case the direction is present.
  45550. if (this.direction) {
  45551. if (!this.transformedDirection) {
  45552. this.transformedDirection = BABYLON.Vector3.Zero();
  45553. }
  45554. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45555. }
  45556. return true;
  45557. }
  45558. return false;
  45559. };
  45560. /**
  45561. * Return the depth scale used for the shadow map.
  45562. * @returns the depth scale.
  45563. */
  45564. ShadowLight.prototype.getDepthScale = function () {
  45565. return 50.0;
  45566. };
  45567. /**
  45568. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45569. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45570. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45571. */
  45572. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45573. return this.transformedDirection ? this.transformedDirection : this.direction;
  45574. };
  45575. /**
  45576. * Returns the ShadowLight absolute position in the World.
  45577. * @returns the position vector in world space
  45578. */
  45579. ShadowLight.prototype.getAbsolutePosition = function () {
  45580. return this.transformedPosition ? this.transformedPosition : this.position;
  45581. };
  45582. /**
  45583. * Sets the ShadowLight direction toward the passed target.
  45584. * @param target The point tot target in local space
  45585. * @returns the updated ShadowLight direction
  45586. */
  45587. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45588. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45589. return this.direction;
  45590. };
  45591. /**
  45592. * Returns the light rotation in euler definition.
  45593. * @returns the x y z rotation in local space.
  45594. */
  45595. ShadowLight.prototype.getRotation = function () {
  45596. this.direction.normalize();
  45597. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45598. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45599. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45600. };
  45601. /**
  45602. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45603. * @returns true if a cube texture needs to be use
  45604. */
  45605. ShadowLight.prototype.needCube = function () {
  45606. return false;
  45607. };
  45608. /**
  45609. * Detects if the projection matrix requires to be recomputed this frame.
  45610. * @returns true if it requires to be recomputed otherwise, false.
  45611. */
  45612. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45613. return this._needProjectionMatrixCompute;
  45614. };
  45615. /**
  45616. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45617. */
  45618. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45619. this._needProjectionMatrixCompute = true;
  45620. };
  45621. /**
  45622. * Get the world matrix of the sahdow lights.
  45623. * @ignore Internal Use Only
  45624. */
  45625. ShadowLight.prototype._getWorldMatrix = function () {
  45626. if (!this._worldMatrix) {
  45627. this._worldMatrix = BABYLON.Matrix.Identity();
  45628. }
  45629. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45630. return this._worldMatrix;
  45631. };
  45632. /**
  45633. * Gets the minZ used for shadow according to both the scene and the light.
  45634. * @param activeCamera The camera we are returning the min for
  45635. * @returns the depth min z
  45636. */
  45637. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45638. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45639. };
  45640. /**
  45641. * Gets the maxZ used for shadow according to both the scene and the light.
  45642. * @param activeCamera The camera we are returning the max for
  45643. * @returns the depth max z
  45644. */
  45645. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45646. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45647. };
  45648. /**
  45649. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45650. * @param matrix The materix to updated with the projection information
  45651. * @param viewMatrix The transform matrix of the light
  45652. * @param renderList The list of mesh to render in the map
  45653. * @returns The current light
  45654. */
  45655. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45656. if (this.customProjectionMatrixBuilder) {
  45657. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45658. }
  45659. else {
  45660. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45661. }
  45662. return this;
  45663. };
  45664. __decorate([
  45665. BABYLON.serializeAsVector3()
  45666. ], ShadowLight.prototype, "position", null);
  45667. __decorate([
  45668. BABYLON.serializeAsVector3()
  45669. ], ShadowLight.prototype, "direction", null);
  45670. __decorate([
  45671. BABYLON.serialize()
  45672. ], ShadowLight.prototype, "shadowMinZ", null);
  45673. __decorate([
  45674. BABYLON.serialize()
  45675. ], ShadowLight.prototype, "shadowMaxZ", null);
  45676. return ShadowLight;
  45677. }(BABYLON.Light));
  45678. BABYLON.ShadowLight = ShadowLight;
  45679. })(BABYLON || (BABYLON = {}));
  45680. //# sourceMappingURL=babylon.shadowLight.js.map
  45681. var BABYLON;
  45682. (function (BABYLON) {
  45683. /**
  45684. * A point light is a light defined by an unique point in world space.
  45685. * The light is emitted in every direction from this point.
  45686. * A good example of a point light is a standard light bulb.
  45687. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45688. */
  45689. var PointLight = /** @class */ (function (_super) {
  45690. __extends(PointLight, _super);
  45691. /**
  45692. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45693. * A PointLight emits the light in every direction.
  45694. * It can cast shadows.
  45695. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45696. * ```javascript
  45697. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45698. * ```
  45699. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45700. * @param name The light friendly name
  45701. * @param position The position of the point light in the scene
  45702. * @param scene The scene the lights belongs to
  45703. */
  45704. function PointLight(name, position, scene) {
  45705. var _this = _super.call(this, name, scene) || this;
  45706. _this._shadowAngle = Math.PI / 2;
  45707. _this.position = position;
  45708. return _this;
  45709. }
  45710. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45711. /**
  45712. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45713. * This specifies what angle the shadow will use to be created.
  45714. *
  45715. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45716. */
  45717. get: function () {
  45718. return this._shadowAngle;
  45719. },
  45720. /**
  45721. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45722. * This specifies what angle the shadow will use to be created.
  45723. *
  45724. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45725. */
  45726. set: function (value) {
  45727. this._shadowAngle = value;
  45728. this.forceProjectionMatrixCompute();
  45729. },
  45730. enumerable: true,
  45731. configurable: true
  45732. });
  45733. Object.defineProperty(PointLight.prototype, "direction", {
  45734. /**
  45735. * Gets the direction if it has been set.
  45736. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45737. */
  45738. get: function () {
  45739. return this._direction;
  45740. },
  45741. /**
  45742. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45743. */
  45744. set: function (value) {
  45745. var previousNeedCube = this.needCube();
  45746. this._direction = value;
  45747. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45748. this._shadowGenerator.recreateShadowMap();
  45749. }
  45750. },
  45751. enumerable: true,
  45752. configurable: true
  45753. });
  45754. /**
  45755. * Returns the string "PointLight"
  45756. * @returns the class name
  45757. */
  45758. PointLight.prototype.getClassName = function () {
  45759. return "PointLight";
  45760. };
  45761. /**
  45762. * Returns the integer 0.
  45763. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45764. */
  45765. PointLight.prototype.getTypeID = function () {
  45766. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45767. };
  45768. /**
  45769. * Specifies wether or not the shadowmap should be a cube texture.
  45770. * @returns true if the shadowmap needs to be a cube texture.
  45771. */
  45772. PointLight.prototype.needCube = function () {
  45773. return !this.direction;
  45774. };
  45775. /**
  45776. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45777. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45778. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45779. */
  45780. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45781. if (this.direction) {
  45782. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45783. }
  45784. else {
  45785. switch (faceIndex) {
  45786. case 0:
  45787. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45788. case 1:
  45789. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45790. case 2:
  45791. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45792. case 3:
  45793. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45794. case 4:
  45795. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45796. case 5:
  45797. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45798. }
  45799. }
  45800. return BABYLON.Vector3.Zero();
  45801. };
  45802. /**
  45803. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45804. * - fov = PI / 2
  45805. * - aspect ratio : 1.0
  45806. * - z-near and far equal to the active camera minZ and maxZ.
  45807. * Returns the PointLight.
  45808. */
  45809. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45810. var activeCamera = this.getScene().activeCamera;
  45811. if (!activeCamera) {
  45812. return;
  45813. }
  45814. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45815. };
  45816. PointLight.prototype._buildUniformLayout = function () {
  45817. this._uniformBuffer.addUniform("vLightData", 4);
  45818. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45819. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45820. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45821. this._uniformBuffer.addUniform("depthValues", 2);
  45822. this._uniformBuffer.create();
  45823. };
  45824. /**
  45825. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45826. * @param effect The effect to update
  45827. * @param lightIndex The index of the light in the effect to update
  45828. * @returns The point light
  45829. */
  45830. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45831. if (this.computeTransformedInformation()) {
  45832. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45833. return this;
  45834. }
  45835. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45836. return this;
  45837. };
  45838. __decorate([
  45839. BABYLON.serialize()
  45840. ], PointLight.prototype, "shadowAngle", null);
  45841. return PointLight;
  45842. }(BABYLON.ShadowLight));
  45843. BABYLON.PointLight = PointLight;
  45844. })(BABYLON || (BABYLON = {}));
  45845. //# sourceMappingURL=babylon.pointLight.js.map
  45846. var BABYLON;
  45847. (function (BABYLON) {
  45848. /**
  45849. * A directional light is defined by a direction (what a surprise!).
  45850. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45851. * 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.
  45852. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45853. */
  45854. var DirectionalLight = /** @class */ (function (_super) {
  45855. __extends(DirectionalLight, _super);
  45856. /**
  45857. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45858. * The directional light is emitted from everywhere in the given direction.
  45859. * It can cast shawdows.
  45860. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45861. * @param name The friendly name of the light
  45862. * @param direction The direction of the light
  45863. * @param scene The scene the light belongs to
  45864. */
  45865. function DirectionalLight(name, direction, scene) {
  45866. var _this = _super.call(this, name, scene) || this;
  45867. _this._shadowFrustumSize = 0;
  45868. _this._shadowOrthoScale = 0.5;
  45869. /**
  45870. * Automatically compute the projection matrix to best fit (including all the casters)
  45871. * on each frame.
  45872. */
  45873. _this.autoUpdateExtends = true;
  45874. // Cache
  45875. _this._orthoLeft = Number.MAX_VALUE;
  45876. _this._orthoRight = Number.MIN_VALUE;
  45877. _this._orthoTop = Number.MIN_VALUE;
  45878. _this._orthoBottom = Number.MAX_VALUE;
  45879. _this.position = direction.scale(-1.0);
  45880. _this.direction = direction;
  45881. return _this;
  45882. }
  45883. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45884. /**
  45885. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45886. */
  45887. get: function () {
  45888. return this._shadowFrustumSize;
  45889. },
  45890. /**
  45891. * Specifies a fix frustum size for the shadow generation.
  45892. */
  45893. set: function (value) {
  45894. this._shadowFrustumSize = value;
  45895. this.forceProjectionMatrixCompute();
  45896. },
  45897. enumerable: true,
  45898. configurable: true
  45899. });
  45900. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45901. /**
  45902. * Gets the shadow projection scale against the optimal computed one.
  45903. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45904. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45905. */
  45906. get: function () {
  45907. return this._shadowOrthoScale;
  45908. },
  45909. /**
  45910. * Sets the shadow projection scale against the optimal computed one.
  45911. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45912. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45913. */
  45914. set: function (value) {
  45915. this._shadowOrthoScale = value;
  45916. this.forceProjectionMatrixCompute();
  45917. },
  45918. enumerable: true,
  45919. configurable: true
  45920. });
  45921. /**
  45922. * Returns the string "DirectionalLight".
  45923. * @return The class name
  45924. */
  45925. DirectionalLight.prototype.getClassName = function () {
  45926. return "DirectionalLight";
  45927. };
  45928. /**
  45929. * Returns the integer 1.
  45930. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45931. */
  45932. DirectionalLight.prototype.getTypeID = function () {
  45933. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45934. };
  45935. /**
  45936. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45937. * Returns the DirectionalLight Shadow projection matrix.
  45938. */
  45939. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45940. if (this.shadowFrustumSize > 0) {
  45941. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45942. }
  45943. else {
  45944. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45945. }
  45946. };
  45947. /**
  45948. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45949. * Returns the DirectionalLight Shadow projection matrix.
  45950. */
  45951. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45952. var activeCamera = this.getScene().activeCamera;
  45953. if (!activeCamera) {
  45954. return;
  45955. }
  45956. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45957. };
  45958. /**
  45959. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45960. * Returns the DirectionalLight Shadow projection matrix.
  45961. */
  45962. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45963. var activeCamera = this.getScene().activeCamera;
  45964. if (!activeCamera) {
  45965. return;
  45966. }
  45967. // Check extends
  45968. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45969. var tempVector3 = BABYLON.Vector3.Zero();
  45970. this._orthoLeft = Number.MAX_VALUE;
  45971. this._orthoRight = Number.MIN_VALUE;
  45972. this._orthoTop = Number.MIN_VALUE;
  45973. this._orthoBottom = Number.MAX_VALUE;
  45974. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45975. var mesh = renderList[meshIndex];
  45976. if (!mesh) {
  45977. continue;
  45978. }
  45979. var boundingInfo = mesh.getBoundingInfo();
  45980. var boundingBox = boundingInfo.boundingBox;
  45981. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45982. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45983. if (tempVector3.x < this._orthoLeft)
  45984. this._orthoLeft = tempVector3.x;
  45985. if (tempVector3.y < this._orthoBottom)
  45986. this._orthoBottom = tempVector3.y;
  45987. if (tempVector3.x > this._orthoRight)
  45988. this._orthoRight = tempVector3.x;
  45989. if (tempVector3.y > this._orthoTop)
  45990. this._orthoTop = tempVector3.y;
  45991. }
  45992. }
  45993. }
  45994. var xOffset = this._orthoRight - this._orthoLeft;
  45995. var yOffset = this._orthoTop - this._orthoBottom;
  45996. 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);
  45997. };
  45998. DirectionalLight.prototype._buildUniformLayout = function () {
  45999. this._uniformBuffer.addUniform("vLightData", 4);
  46000. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46001. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46002. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46003. this._uniformBuffer.addUniform("depthValues", 2);
  46004. this._uniformBuffer.create();
  46005. };
  46006. /**
  46007. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46008. * @param effect The effect to update
  46009. * @param lightIndex The index of the light in the effect to update
  46010. * @returns The directional light
  46011. */
  46012. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46013. if (this.computeTransformedInformation()) {
  46014. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46015. return this;
  46016. }
  46017. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46018. return this;
  46019. };
  46020. /**
  46021. * Gets the minZ used for shadow according to both the scene and the light.
  46022. *
  46023. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46024. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46025. * @param activeCamera The camera we are returning the min for
  46026. * @returns the depth min z
  46027. */
  46028. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46029. return 1;
  46030. };
  46031. /**
  46032. * Gets the maxZ used for shadow according to both the scene and the light.
  46033. *
  46034. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46035. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46036. * @param activeCamera The camera we are returning the max for
  46037. * @returns the depth max z
  46038. */
  46039. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46040. return 1;
  46041. };
  46042. __decorate([
  46043. BABYLON.serialize()
  46044. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46045. __decorate([
  46046. BABYLON.serialize()
  46047. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46048. __decorate([
  46049. BABYLON.serialize()
  46050. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46051. return DirectionalLight;
  46052. }(BABYLON.ShadowLight));
  46053. BABYLON.DirectionalLight = DirectionalLight;
  46054. })(BABYLON || (BABYLON = {}));
  46055. //# sourceMappingURL=babylon.directionalLight.js.map
  46056. var BABYLON;
  46057. (function (BABYLON) {
  46058. /**
  46059. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46060. * These values define a cone of light starting from the position, emitting toward the direction.
  46061. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46062. * and the exponent defines the speed of the decay of the light with distance (reach).
  46063. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46064. */
  46065. var SpotLight = /** @class */ (function (_super) {
  46066. __extends(SpotLight, _super);
  46067. /**
  46068. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46069. * It can cast shadows.
  46070. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46071. * @param name The light friendly name
  46072. * @param position The position of the spot light in the scene
  46073. * @param direction The direction of the light in the scene
  46074. * @param angle The cone angle of the light in Radians
  46075. * @param exponent The light decay speed with the distance from the emission spot
  46076. * @param scene The scene the lights belongs to
  46077. */
  46078. function SpotLight(name, position, direction, angle, exponent, scene) {
  46079. var _this = _super.call(this, name, scene) || this;
  46080. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46081. _this._projectionTextureLightNear = 1e-6;
  46082. _this._projectionTextureLightFar = 1000.0;
  46083. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46084. _this._projectionTextureViewLightDirty = true;
  46085. _this._projectionTextureProjectionLightDirty = true;
  46086. _this._projectionTextureDirty = true;
  46087. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46088. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46089. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46090. _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);
  46091. _this.position = position;
  46092. _this.direction = direction;
  46093. _this.angle = angle;
  46094. _this.exponent = exponent;
  46095. return _this;
  46096. }
  46097. Object.defineProperty(SpotLight.prototype, "angle", {
  46098. /**
  46099. * Gets the cone angle of the spot light in Radians.
  46100. */
  46101. get: function () {
  46102. return this._angle;
  46103. },
  46104. /**
  46105. * Sets the cone angle of the spot light in Radians.
  46106. */
  46107. set: function (value) {
  46108. this._angle = value;
  46109. this._projectionTextureProjectionLightDirty = true;
  46110. this.forceProjectionMatrixCompute();
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46116. /**
  46117. * Allows scaling the angle of the light for shadow generation only.
  46118. */
  46119. get: function () {
  46120. return this._shadowAngleScale;
  46121. },
  46122. /**
  46123. * Allows scaling the angle of the light for shadow generation only.
  46124. */
  46125. set: function (value) {
  46126. this._shadowAngleScale = value;
  46127. this.forceProjectionMatrixCompute();
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46133. /**
  46134. * Allows reading the projecton texture
  46135. */
  46136. get: function () {
  46137. return this._projectionTextureMatrix;
  46138. },
  46139. enumerable: true,
  46140. configurable: true
  46141. });
  46142. ;
  46143. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46144. /**
  46145. * Gets the near clip of the Spotlight for texture projection.
  46146. */
  46147. get: function () {
  46148. return this._projectionTextureLightNear;
  46149. },
  46150. /**
  46151. * Sets the near clip of the Spotlight for texture projection.
  46152. */
  46153. set: function (value) {
  46154. this._projectionTextureLightNear = value;
  46155. this._projectionTextureProjectionLightDirty = true;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46161. /**
  46162. * Gets the far clip of the Spotlight for texture projection.
  46163. */
  46164. get: function () {
  46165. return this._projectionTextureLightFar;
  46166. },
  46167. /**
  46168. * Sets the far clip of the Spotlight for texture projection.
  46169. */
  46170. set: function (value) {
  46171. this._projectionTextureLightFar = value;
  46172. this._projectionTextureProjectionLightDirty = true;
  46173. },
  46174. enumerable: true,
  46175. configurable: true
  46176. });
  46177. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46178. /**
  46179. * Gets the Up vector of the Spotlight for texture projection.
  46180. */
  46181. get: function () {
  46182. return this._projectionTextureUpDirection;
  46183. },
  46184. /**
  46185. * Sets the Up vector of the Spotlight for texture projection.
  46186. */
  46187. set: function (value) {
  46188. this._projectionTextureUpDirection = value;
  46189. this._projectionTextureProjectionLightDirty = true;
  46190. },
  46191. enumerable: true,
  46192. configurable: true
  46193. });
  46194. ;
  46195. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46196. /**
  46197. * Gets the projection texture of the light.
  46198. */
  46199. get: function () {
  46200. return this._projectionTexture;
  46201. },
  46202. /**
  46203. * Sets the projection texture of the light.
  46204. */
  46205. set: function (value) {
  46206. this._projectionTexture = value;
  46207. this._projectionTextureDirty = true;
  46208. },
  46209. enumerable: true,
  46210. configurable: true
  46211. });
  46212. /**
  46213. * Returns the string "SpotLight".
  46214. * @returns the class name
  46215. */
  46216. SpotLight.prototype.getClassName = function () {
  46217. return "SpotLight";
  46218. };
  46219. /**
  46220. * Returns the integer 2.
  46221. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46222. */
  46223. SpotLight.prototype.getTypeID = function () {
  46224. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46225. };
  46226. /**
  46227. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46228. */
  46229. SpotLight.prototype._setDirection = function (value) {
  46230. _super.prototype._setDirection.call(this, value);
  46231. this._projectionTextureViewLightDirty = true;
  46232. };
  46233. /**
  46234. * Overrides the position setter to recompute the projection texture view light Matrix.
  46235. */
  46236. SpotLight.prototype._setPosition = function (value) {
  46237. _super.prototype._setPosition.call(this, value);
  46238. this._projectionTextureViewLightDirty = true;
  46239. };
  46240. /**
  46241. * 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.
  46242. * Returns the SpotLight.
  46243. */
  46244. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46245. var activeCamera = this.getScene().activeCamera;
  46246. if (!activeCamera) {
  46247. return;
  46248. }
  46249. this._shadowAngleScale = this._shadowAngleScale || 1;
  46250. var angle = this._shadowAngleScale * this._angle;
  46251. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46252. };
  46253. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46254. this._projectionTextureViewLightDirty = false;
  46255. this._projectionTextureDirty = true;
  46256. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46257. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46258. };
  46259. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46260. this._projectionTextureProjectionLightDirty = false;
  46261. this._projectionTextureDirty = true;
  46262. var light_far = this.projectionTextureLightFar;
  46263. var light_near = this.projectionTextureLightNear;
  46264. var P = light_far / (light_far - light_near);
  46265. var Q = -P * light_near;
  46266. var S = 1.0 / Math.tan(this._angle / 2.0);
  46267. var A = 1.0;
  46268. 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);
  46269. };
  46270. /**
  46271. * Main function for light texture projection matrix computing.
  46272. */
  46273. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46274. this._projectionTextureDirty = false;
  46275. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46276. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46277. };
  46278. SpotLight.prototype._buildUniformLayout = function () {
  46279. this._uniformBuffer.addUniform("vLightData", 4);
  46280. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46281. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46282. this._uniformBuffer.addUniform("vLightDirection", 3);
  46283. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46284. this._uniformBuffer.addUniform("depthValues", 2);
  46285. this._uniformBuffer.create();
  46286. };
  46287. /**
  46288. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46289. * @param effect The effect to update
  46290. * @param lightIndex The index of the light in the effect to update
  46291. * @returns The spot light
  46292. */
  46293. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46294. var normalizeDirection;
  46295. if (this.computeTransformedInformation()) {
  46296. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46297. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46298. }
  46299. else {
  46300. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46301. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46302. }
  46303. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46304. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46305. if (this._projectionTextureViewLightDirty) {
  46306. this._computeProjectionTextureViewLightMatrix();
  46307. }
  46308. if (this._projectionTextureProjectionLightDirty) {
  46309. this._computeProjectionTextureProjectionLightMatrix();
  46310. }
  46311. if (this._projectionTextureDirty) {
  46312. this._computeProjectionTextureMatrix();
  46313. }
  46314. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46315. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46316. }
  46317. return this;
  46318. };
  46319. /**
  46320. * Disposes the light and the associated resources.
  46321. */
  46322. SpotLight.prototype.dispose = function () {
  46323. _super.prototype.dispose.call(this);
  46324. if (this._projectionTexture) {
  46325. this._projectionTexture.dispose();
  46326. }
  46327. };
  46328. __decorate([
  46329. BABYLON.serialize()
  46330. ], SpotLight.prototype, "angle", null);
  46331. __decorate([
  46332. BABYLON.serialize()
  46333. ], SpotLight.prototype, "shadowAngleScale", null);
  46334. __decorate([
  46335. BABYLON.serialize()
  46336. ], SpotLight.prototype, "exponent", void 0);
  46337. __decorate([
  46338. BABYLON.serialize()
  46339. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46340. __decorate([
  46341. BABYLON.serialize()
  46342. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46343. __decorate([
  46344. BABYLON.serialize()
  46345. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46346. __decorate([
  46347. BABYLON.serializeAsTexture("projectedLightTexture")
  46348. ], SpotLight.prototype, "_projectionTexture", void 0);
  46349. return SpotLight;
  46350. }(BABYLON.ShadowLight));
  46351. BABYLON.SpotLight = SpotLight;
  46352. })(BABYLON || (BABYLON = {}));
  46353. //# sourceMappingURL=babylon.spotLight.js.map
  46354. var BABYLON;
  46355. (function (BABYLON) {
  46356. /**
  46357. * Class used to override all child animations of a given target
  46358. */
  46359. var AnimationPropertiesOverride = /** @class */ (function () {
  46360. function AnimationPropertiesOverride() {
  46361. /**
  46362. * Gets or sets a value indicating if animation blending must be used
  46363. */
  46364. this.enableBlending = false;
  46365. /**
  46366. * Gets or sets the blending speed to use when enableBlending is true
  46367. */
  46368. this.blendingSpeed = 0.01;
  46369. /**
  46370. * Gets or sets the default loop mode to use
  46371. */
  46372. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46373. }
  46374. return AnimationPropertiesOverride;
  46375. }());
  46376. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46377. })(BABYLON || (BABYLON = {}));
  46378. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46379. var BABYLON;
  46380. (function (BABYLON) {
  46381. var AnimationRange = /** @class */ (function () {
  46382. function AnimationRange(name, from, to) {
  46383. this.name = name;
  46384. this.from = from;
  46385. this.to = to;
  46386. }
  46387. AnimationRange.prototype.clone = function () {
  46388. return new AnimationRange(this.name, this.from, this.to);
  46389. };
  46390. return AnimationRange;
  46391. }());
  46392. BABYLON.AnimationRange = AnimationRange;
  46393. /**
  46394. * Composed of a frame, and an action function
  46395. */
  46396. var AnimationEvent = /** @class */ (function () {
  46397. function AnimationEvent(frame, action, onlyOnce) {
  46398. this.frame = frame;
  46399. this.action = action;
  46400. this.onlyOnce = onlyOnce;
  46401. this.isDone = false;
  46402. }
  46403. return AnimationEvent;
  46404. }());
  46405. BABYLON.AnimationEvent = AnimationEvent;
  46406. var PathCursor = /** @class */ (function () {
  46407. function PathCursor(path) {
  46408. this.path = path;
  46409. this._onchange = new Array();
  46410. this.value = 0;
  46411. this.animations = new Array();
  46412. }
  46413. PathCursor.prototype.getPoint = function () {
  46414. var point = this.path.getPointAtLengthPosition(this.value);
  46415. return new BABYLON.Vector3(point.x, 0, point.y);
  46416. };
  46417. PathCursor.prototype.moveAhead = function (step) {
  46418. if (step === void 0) { step = 0.002; }
  46419. this.move(step);
  46420. return this;
  46421. };
  46422. PathCursor.prototype.moveBack = function (step) {
  46423. if (step === void 0) { step = 0.002; }
  46424. this.move(-step);
  46425. return this;
  46426. };
  46427. PathCursor.prototype.move = function (step) {
  46428. if (Math.abs(step) > 1) {
  46429. throw "step size should be less than 1.";
  46430. }
  46431. this.value += step;
  46432. this.ensureLimits();
  46433. this.raiseOnChange();
  46434. return this;
  46435. };
  46436. PathCursor.prototype.ensureLimits = function () {
  46437. while (this.value > 1) {
  46438. this.value -= 1;
  46439. }
  46440. while (this.value < 0) {
  46441. this.value += 1;
  46442. }
  46443. return this;
  46444. };
  46445. // used by animation engine
  46446. PathCursor.prototype.raiseOnChange = function () {
  46447. var _this = this;
  46448. this._onchange.forEach(function (f) { return f(_this); });
  46449. return this;
  46450. };
  46451. PathCursor.prototype.onchange = function (f) {
  46452. this._onchange.push(f);
  46453. return this;
  46454. };
  46455. return PathCursor;
  46456. }());
  46457. BABYLON.PathCursor = PathCursor;
  46458. var AnimationKeyInterpolation;
  46459. (function (AnimationKeyInterpolation) {
  46460. /**
  46461. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46462. */
  46463. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46464. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46465. var Animation = /** @class */ (function () {
  46466. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46467. this.name = name;
  46468. this.targetProperty = targetProperty;
  46469. this.framePerSecond = framePerSecond;
  46470. this.dataType = dataType;
  46471. this.loopMode = loopMode;
  46472. this.enableBlending = enableBlending;
  46473. this._runtimeAnimations = new Array();
  46474. // The set of event that will be linked to this animation
  46475. this._events = new Array();
  46476. this.blendingSpeed = 0.01;
  46477. this._ranges = {};
  46478. this.targetPropertyPath = targetProperty.split(".");
  46479. this.dataType = dataType;
  46480. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46481. }
  46482. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46483. var dataType = undefined;
  46484. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46485. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46486. }
  46487. else if (from instanceof BABYLON.Quaternion) {
  46488. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46489. }
  46490. else if (from instanceof BABYLON.Vector3) {
  46491. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46492. }
  46493. else if (from instanceof BABYLON.Vector2) {
  46494. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46495. }
  46496. else if (from instanceof BABYLON.Color3) {
  46497. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46498. }
  46499. else if (from instanceof BABYLON.Size) {
  46500. dataType = Animation.ANIMATIONTYPE_SIZE;
  46501. }
  46502. if (dataType == undefined) {
  46503. return null;
  46504. }
  46505. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46506. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46507. animation.setKeys(keys);
  46508. if (easingFunction !== undefined) {
  46509. animation.setEasingFunction(easingFunction);
  46510. }
  46511. return animation;
  46512. };
  46513. /**
  46514. * Sets up an animation.
  46515. * @param property the property to animate
  46516. * @param animationType the animation type to apply
  46517. * @param easingFunction the easing function used in the animation
  46518. * @returns The created animation
  46519. */
  46520. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46521. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46522. animation.setEasingFunction(easingFunction);
  46523. return animation;
  46524. };
  46525. /**
  46526. * Create and start an animation on a node
  46527. * @param {string} name defines the name of the global animation that will be run on all nodes
  46528. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46529. * @param {string} targetProperty defines property to animate
  46530. * @param {number} framePerSecond defines the number of frame per second yo use
  46531. * @param {number} totalFrame defines the number of frames in total
  46532. * @param {any} from defines the initial value
  46533. * @param {any} to defines the final value
  46534. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46535. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46536. * @param onAnimationEnd defines the callback to call when animation end
  46537. * @returns the animatable created for this animation
  46538. */
  46539. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46540. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46541. if (!animation) {
  46542. return null;
  46543. }
  46544. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46545. };
  46546. /**
  46547. * Create and start an animation on a node and its descendants
  46548. * @param {string} name defines the name of the global animation that will be run on all nodes
  46549. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46550. * @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.
  46551. * @param {string} targetProperty defines property to animate
  46552. * @param {number} framePerSecond defines the number of frame per second yo use
  46553. * @param {number} totalFrame defines the number of frames in total
  46554. * @param {any} from defines the initial value
  46555. * @param {any} to defines the final value
  46556. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46557. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46558. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46559. * @returns the list of animatables created for all nodes
  46560. * @example https://www.babylonjs-playground.com/#MH0VLI
  46561. */
  46562. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46563. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46564. if (!animation) {
  46565. return null;
  46566. }
  46567. var scene = node.getScene();
  46568. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46569. };
  46570. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46571. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46572. if (!animation) {
  46573. return null;
  46574. }
  46575. node.animations.push(animation);
  46576. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46577. };
  46578. /**
  46579. * Transition property of the Camera to the target Value.
  46580. * @param property The property to transition
  46581. * @param targetValue The target Value of the property
  46582. * @param host The object where the property to animate belongs
  46583. * @param scene Scene used to run the animation
  46584. * @param frameRate Framerate (in frame/s) to use
  46585. * @param transition The transition type we want to use
  46586. * @param duration The duration of the animation, in milliseconds
  46587. * @param onAnimationEnd Call back trigger at the end of the animation.
  46588. */
  46589. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46590. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46591. if (duration <= 0) {
  46592. host[property] = targetValue;
  46593. if (onAnimationEnd) {
  46594. onAnimationEnd();
  46595. }
  46596. return null;
  46597. }
  46598. var endFrame = frameRate * (duration / 1000);
  46599. transition.setKeys([{
  46600. frame: 0,
  46601. value: host[property].clone ? host[property].clone() : host[property]
  46602. },
  46603. {
  46604. frame: endFrame,
  46605. value: targetValue
  46606. }]);
  46607. if (!host.animations) {
  46608. host.animations = [];
  46609. }
  46610. host.animations.push(transition);
  46611. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46612. animation.onAnimationEnd = onAnimationEnd;
  46613. return animation;
  46614. };
  46615. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46616. /**
  46617. * Return the array of runtime animations currently using this animation
  46618. */
  46619. get: function () {
  46620. return this._runtimeAnimations;
  46621. },
  46622. enumerable: true,
  46623. configurable: true
  46624. });
  46625. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46626. get: function () {
  46627. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46628. var runtimeAnimation = _a[_i];
  46629. if (!runtimeAnimation.isStopped) {
  46630. return true;
  46631. }
  46632. }
  46633. return false;
  46634. },
  46635. enumerable: true,
  46636. configurable: true
  46637. });
  46638. // Methods
  46639. /**
  46640. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46641. */
  46642. Animation.prototype.toString = function (fullDetails) {
  46643. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46644. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46645. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46646. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46647. if (fullDetails) {
  46648. ret += ", Ranges: {";
  46649. var first = true;
  46650. for (var name in this._ranges) {
  46651. if (first) {
  46652. ret += ", ";
  46653. first = false;
  46654. }
  46655. ret += name;
  46656. }
  46657. ret += "}";
  46658. }
  46659. return ret;
  46660. };
  46661. /**
  46662. * Add an event to this animation.
  46663. */
  46664. Animation.prototype.addEvent = function (event) {
  46665. this._events.push(event);
  46666. };
  46667. /**
  46668. * Remove all events found at the given frame
  46669. * @param frame
  46670. */
  46671. Animation.prototype.removeEvents = function (frame) {
  46672. for (var index = 0; index < this._events.length; index++) {
  46673. if (this._events[index].frame === frame) {
  46674. this._events.splice(index, 1);
  46675. index--;
  46676. }
  46677. }
  46678. };
  46679. Animation.prototype.getEvents = function () {
  46680. return this._events;
  46681. };
  46682. Animation.prototype.createRange = function (name, from, to) {
  46683. // check name not already in use; could happen for bones after serialized
  46684. if (!this._ranges[name]) {
  46685. this._ranges[name] = new AnimationRange(name, from, to);
  46686. }
  46687. };
  46688. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46689. if (deleteFrames === void 0) { deleteFrames = true; }
  46690. var range = this._ranges[name];
  46691. if (!range) {
  46692. return;
  46693. }
  46694. if (deleteFrames) {
  46695. var from = range.from;
  46696. var to = range.to;
  46697. // this loop MUST go high to low for multiple splices to work
  46698. for (var key = this._keys.length - 1; key >= 0; key--) {
  46699. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46700. this._keys.splice(key, 1);
  46701. }
  46702. }
  46703. }
  46704. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46705. };
  46706. Animation.prototype.getRange = function (name) {
  46707. return this._ranges[name];
  46708. };
  46709. Animation.prototype.getKeys = function () {
  46710. return this._keys;
  46711. };
  46712. Animation.prototype.getHighestFrame = function () {
  46713. var ret = 0;
  46714. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46715. if (ret < this._keys[key].frame) {
  46716. ret = this._keys[key].frame;
  46717. }
  46718. }
  46719. return ret;
  46720. };
  46721. Animation.prototype.getEasingFunction = function () {
  46722. return this._easingFunction;
  46723. };
  46724. Animation.prototype.setEasingFunction = function (easingFunction) {
  46725. this._easingFunction = easingFunction;
  46726. };
  46727. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46728. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46729. };
  46730. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46731. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46732. };
  46733. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46734. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46735. };
  46736. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46737. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46738. };
  46739. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46740. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46741. };
  46742. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46743. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46744. };
  46745. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46746. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46747. };
  46748. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46749. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46750. };
  46751. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46752. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46753. };
  46754. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46755. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46756. };
  46757. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46758. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46759. };
  46760. Animation.prototype.clone = function () {
  46761. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46762. clone.enableBlending = this.enableBlending;
  46763. clone.blendingSpeed = this.blendingSpeed;
  46764. if (this._keys) {
  46765. clone.setKeys(this._keys);
  46766. }
  46767. if (this._ranges) {
  46768. clone._ranges = {};
  46769. for (var name in this._ranges) {
  46770. var range = this._ranges[name];
  46771. if (!range) {
  46772. continue;
  46773. }
  46774. clone._ranges[name] = range.clone();
  46775. }
  46776. }
  46777. return clone;
  46778. };
  46779. Animation.prototype.setKeys = function (values) {
  46780. this._keys = values.slice(0);
  46781. };
  46782. Animation.prototype.serialize = function () {
  46783. var serializationObject = {};
  46784. serializationObject.name = this.name;
  46785. serializationObject.property = this.targetProperty;
  46786. serializationObject.framePerSecond = this.framePerSecond;
  46787. serializationObject.dataType = this.dataType;
  46788. serializationObject.loopBehavior = this.loopMode;
  46789. serializationObject.enableBlending = this.enableBlending;
  46790. serializationObject.blendingSpeed = this.blendingSpeed;
  46791. var dataType = this.dataType;
  46792. serializationObject.keys = [];
  46793. var keys = this.getKeys();
  46794. for (var index = 0; index < keys.length; index++) {
  46795. var animationKey = keys[index];
  46796. var key = {};
  46797. key.frame = animationKey.frame;
  46798. switch (dataType) {
  46799. case Animation.ANIMATIONTYPE_FLOAT:
  46800. key.values = [animationKey.value];
  46801. break;
  46802. case Animation.ANIMATIONTYPE_QUATERNION:
  46803. case Animation.ANIMATIONTYPE_MATRIX:
  46804. case Animation.ANIMATIONTYPE_VECTOR3:
  46805. case Animation.ANIMATIONTYPE_COLOR3:
  46806. key.values = animationKey.value.asArray();
  46807. break;
  46808. }
  46809. serializationObject.keys.push(key);
  46810. }
  46811. serializationObject.ranges = [];
  46812. for (var name in this._ranges) {
  46813. var source = this._ranges[name];
  46814. if (!source) {
  46815. continue;
  46816. }
  46817. var range = {};
  46818. range.name = name;
  46819. range.from = source.from;
  46820. range.to = source.to;
  46821. serializationObject.ranges.push(range);
  46822. }
  46823. return serializationObject;
  46824. };
  46825. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46826. get: function () {
  46827. return Animation._ANIMATIONTYPE_FLOAT;
  46828. },
  46829. enumerable: true,
  46830. configurable: true
  46831. });
  46832. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46833. get: function () {
  46834. return Animation._ANIMATIONTYPE_VECTOR3;
  46835. },
  46836. enumerable: true,
  46837. configurable: true
  46838. });
  46839. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46840. get: function () {
  46841. return Animation._ANIMATIONTYPE_VECTOR2;
  46842. },
  46843. enumerable: true,
  46844. configurable: true
  46845. });
  46846. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46847. get: function () {
  46848. return Animation._ANIMATIONTYPE_SIZE;
  46849. },
  46850. enumerable: true,
  46851. configurable: true
  46852. });
  46853. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46854. get: function () {
  46855. return Animation._ANIMATIONTYPE_QUATERNION;
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46861. get: function () {
  46862. return Animation._ANIMATIONTYPE_MATRIX;
  46863. },
  46864. enumerable: true,
  46865. configurable: true
  46866. });
  46867. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46868. get: function () {
  46869. return Animation._ANIMATIONTYPE_COLOR3;
  46870. },
  46871. enumerable: true,
  46872. configurable: true
  46873. });
  46874. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46875. get: function () {
  46876. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46882. get: function () {
  46883. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46889. get: function () {
  46890. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46891. },
  46892. enumerable: true,
  46893. configurable: true
  46894. });
  46895. Animation.Parse = function (parsedAnimation) {
  46896. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46897. var dataType = parsedAnimation.dataType;
  46898. var keys = [];
  46899. var data;
  46900. var index;
  46901. if (parsedAnimation.enableBlending) {
  46902. animation.enableBlending = parsedAnimation.enableBlending;
  46903. }
  46904. if (parsedAnimation.blendingSpeed) {
  46905. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46906. }
  46907. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46908. var key = parsedAnimation.keys[index];
  46909. var inTangent;
  46910. var outTangent;
  46911. switch (dataType) {
  46912. case Animation.ANIMATIONTYPE_FLOAT:
  46913. data = key.values[0];
  46914. if (key.values.length >= 1) {
  46915. inTangent = key.values[1];
  46916. }
  46917. if (key.values.length >= 2) {
  46918. outTangent = key.values[2];
  46919. }
  46920. break;
  46921. case Animation.ANIMATIONTYPE_QUATERNION:
  46922. data = BABYLON.Quaternion.FromArray(key.values);
  46923. if (key.values.length >= 8) {
  46924. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46925. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46926. inTangent = _inTangent;
  46927. }
  46928. }
  46929. if (key.values.length >= 12) {
  46930. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46931. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46932. outTangent = _outTangent;
  46933. }
  46934. }
  46935. break;
  46936. case Animation.ANIMATIONTYPE_MATRIX:
  46937. data = BABYLON.Matrix.FromArray(key.values);
  46938. break;
  46939. case Animation.ANIMATIONTYPE_COLOR3:
  46940. data = BABYLON.Color3.FromArray(key.values);
  46941. break;
  46942. case Animation.ANIMATIONTYPE_VECTOR3:
  46943. default:
  46944. data = BABYLON.Vector3.FromArray(key.values);
  46945. break;
  46946. }
  46947. var keyData = {};
  46948. keyData.frame = key.frame;
  46949. keyData.value = data;
  46950. if (inTangent != undefined) {
  46951. keyData.inTangent = inTangent;
  46952. }
  46953. if (outTangent != undefined) {
  46954. keyData.outTangent = outTangent;
  46955. }
  46956. keys.push(keyData);
  46957. }
  46958. animation.setKeys(keys);
  46959. if (parsedAnimation.ranges) {
  46960. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46961. data = parsedAnimation.ranges[index];
  46962. animation.createRange(data.name, data.from, data.to);
  46963. }
  46964. }
  46965. return animation;
  46966. };
  46967. Animation.AppendSerializedAnimations = function (source, destination) {
  46968. if (source.animations) {
  46969. destination.animations = [];
  46970. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46971. var animation = source.animations[animationIndex];
  46972. destination.animations.push(animation.serialize());
  46973. }
  46974. }
  46975. };
  46976. Animation.AllowMatricesInterpolation = false;
  46977. // Statics
  46978. Animation._ANIMATIONTYPE_FLOAT = 0;
  46979. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46980. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46981. Animation._ANIMATIONTYPE_MATRIX = 3;
  46982. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46983. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46984. Animation._ANIMATIONTYPE_SIZE = 6;
  46985. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46986. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46987. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46988. return Animation;
  46989. }());
  46990. BABYLON.Animation = Animation;
  46991. })(BABYLON || (BABYLON = {}));
  46992. //# sourceMappingURL=babylon.animation.js.map
  46993. var BABYLON;
  46994. (function (BABYLON) {
  46995. /**
  46996. * This class defines the direct association between an animation and a target
  46997. */
  46998. var TargetedAnimation = /** @class */ (function () {
  46999. function TargetedAnimation() {
  47000. }
  47001. return TargetedAnimation;
  47002. }());
  47003. BABYLON.TargetedAnimation = TargetedAnimation;
  47004. /**
  47005. * Use this class to create coordinated animations on multiple targets
  47006. */
  47007. var AnimationGroup = /** @class */ (function () {
  47008. function AnimationGroup(name, scene) {
  47009. if (scene === void 0) { scene = null; }
  47010. this.name = name;
  47011. this._targetedAnimations = new Array();
  47012. this._animatables = new Array();
  47013. this._from = Number.MAX_VALUE;
  47014. this._to = -Number.MAX_VALUE;
  47015. this._speedRatio = 1;
  47016. this.onAnimationEndObservable = new BABYLON.Observable();
  47017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47018. this._scene.animationGroups.push(this);
  47019. }
  47020. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47021. /**
  47022. * Define if the animations are started
  47023. */
  47024. get: function () {
  47025. return this._isStarted;
  47026. },
  47027. enumerable: true,
  47028. configurable: true
  47029. });
  47030. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47031. /**
  47032. * Gets or sets the speed ratio to use for all animations
  47033. */
  47034. get: function () {
  47035. return this._speedRatio;
  47036. },
  47037. /**
  47038. * Gets or sets the speed ratio to use for all animations
  47039. */
  47040. set: function (value) {
  47041. if (this._speedRatio === value) {
  47042. return;
  47043. }
  47044. this._speedRatio = value;
  47045. for (var index = 0; index < this._animatables.length; index++) {
  47046. var animatable = this._animatables[index];
  47047. animatable.speedRatio = this._speedRatio;
  47048. }
  47049. },
  47050. enumerable: true,
  47051. configurable: true
  47052. });
  47053. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47054. /**
  47055. * Gets the targeted animations for this animation group
  47056. */
  47057. get: function () {
  47058. return this._targetedAnimations;
  47059. },
  47060. enumerable: true,
  47061. configurable: true
  47062. });
  47063. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47064. /**
  47065. * returning the list of animatables controlled by this animation group.
  47066. */
  47067. get: function () {
  47068. return this._animatables;
  47069. },
  47070. enumerable: true,
  47071. configurable: true
  47072. });
  47073. /**
  47074. * Add an animation (with its target) in the group
  47075. * @param animation defines the animation we want to add
  47076. * @param target defines the target of the animation
  47077. * @returns the {BABYLON.TargetedAnimation} object
  47078. */
  47079. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47080. var targetedAnimation = {
  47081. animation: animation,
  47082. target: target
  47083. };
  47084. var keys = animation.getKeys();
  47085. if (this._from > keys[0].frame) {
  47086. this._from = keys[0].frame;
  47087. }
  47088. if (this._to < keys[keys.length - 1].frame) {
  47089. this._to = keys[keys.length - 1].frame;
  47090. }
  47091. this._targetedAnimations.push(targetedAnimation);
  47092. return targetedAnimation;
  47093. };
  47094. /**
  47095. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47096. * It can add constant keys at begin or end
  47097. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47098. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47099. */
  47100. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47101. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47102. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47103. beginFrame = Math.max(beginFrame, this._from);
  47104. endFrame = Math.min(endFrame, this._to);
  47105. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47106. var targetedAnimation = this._targetedAnimations[index];
  47107. var keys = targetedAnimation.animation.getKeys();
  47108. var startKey = keys[0];
  47109. var endKey = keys[keys.length - 1];
  47110. if (startKey.frame > beginFrame) {
  47111. var newKey = {
  47112. frame: beginFrame,
  47113. value: startKey.value,
  47114. inTangent: startKey.inTangent,
  47115. outTangent: startKey.outTangent,
  47116. interpolation: startKey.interpolation
  47117. };
  47118. keys.splice(0, 0, newKey);
  47119. }
  47120. if (endKey.frame < endFrame) {
  47121. var newKey = {
  47122. frame: endFrame,
  47123. value: endKey.value,
  47124. inTangent: endKey.outTangent,
  47125. outTangent: endKey.outTangent,
  47126. interpolation: endKey.interpolation
  47127. };
  47128. keys.push(newKey);
  47129. }
  47130. }
  47131. return this;
  47132. };
  47133. /**
  47134. * Start all animations on given targets
  47135. * @param loop defines if animations must loop
  47136. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47137. */
  47138. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47139. var _this = this;
  47140. if (loop === void 0) { loop = false; }
  47141. if (speedRatio === void 0) { speedRatio = 1; }
  47142. if (this._isStarted || this._targetedAnimations.length === 0) {
  47143. return this;
  47144. }
  47145. var _loop_1 = function () {
  47146. var targetedAnimation = this_1._targetedAnimations[index];
  47147. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47148. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47149. }));
  47150. };
  47151. var this_1 = this;
  47152. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47153. _loop_1();
  47154. }
  47155. this._speedRatio = speedRatio;
  47156. this._isStarted = true;
  47157. return this;
  47158. };
  47159. /**
  47160. * Pause all animations
  47161. */
  47162. AnimationGroup.prototype.pause = function () {
  47163. if (!this._isStarted) {
  47164. return this;
  47165. }
  47166. for (var index = 0; index < this._animatables.length; index++) {
  47167. var animatable = this._animatables[index];
  47168. animatable.pause();
  47169. }
  47170. return this;
  47171. };
  47172. /**
  47173. * Play all animations to initial state
  47174. * This function will start() the animations if they were not started or will restart() them if they were paused
  47175. * @param loop defines if animations must loop
  47176. */
  47177. AnimationGroup.prototype.play = function (loop) {
  47178. if (this.isStarted) {
  47179. if (loop !== undefined) {
  47180. for (var index = 0; index < this._animatables.length; index++) {
  47181. var animatable = this._animatables[index];
  47182. animatable.loopAnimation = loop;
  47183. }
  47184. }
  47185. this.restart();
  47186. }
  47187. else {
  47188. this.start(loop, this._speedRatio);
  47189. }
  47190. return this;
  47191. };
  47192. /**
  47193. * Reset all animations to initial state
  47194. */
  47195. AnimationGroup.prototype.reset = function () {
  47196. if (!this._isStarted) {
  47197. return this;
  47198. }
  47199. for (var index = 0; index < this._animatables.length; index++) {
  47200. var animatable = this._animatables[index];
  47201. animatable.reset();
  47202. }
  47203. return this;
  47204. };
  47205. /**
  47206. * Restart animations from key 0
  47207. */
  47208. AnimationGroup.prototype.restart = function () {
  47209. if (!this._isStarted) {
  47210. return this;
  47211. }
  47212. for (var index = 0; index < this._animatables.length; index++) {
  47213. var animatable = this._animatables[index];
  47214. animatable.restart();
  47215. }
  47216. return this;
  47217. };
  47218. /**
  47219. * Stop all animations
  47220. */
  47221. AnimationGroup.prototype.stop = function () {
  47222. if (!this._isStarted) {
  47223. return this;
  47224. }
  47225. for (var index = 0; index < this._animatables.length; index++) {
  47226. var animatable = this._animatables[index];
  47227. animatable.stop();
  47228. }
  47229. this._isStarted = false;
  47230. return this;
  47231. };
  47232. /**
  47233. * Goes to a specific frame in this animation group
  47234. *
  47235. * @param frame the frame number to go to
  47236. * @return the animationGroup
  47237. */
  47238. AnimationGroup.prototype.goToFrame = function (frame) {
  47239. if (!this._isStarted) {
  47240. return this;
  47241. }
  47242. for (var index = 0; index < this._animatables.length; index++) {
  47243. var animatable = this._animatables[index];
  47244. animatable.goToFrame(frame);
  47245. }
  47246. return this;
  47247. };
  47248. /**
  47249. * Dispose all associated resources
  47250. */
  47251. AnimationGroup.prototype.dispose = function () {
  47252. this._targetedAnimations = [];
  47253. this._animatables = [];
  47254. var index = this._scene.animationGroups.indexOf(this);
  47255. if (index > -1) {
  47256. this._scene.animationGroups.splice(index, 1);
  47257. }
  47258. };
  47259. return AnimationGroup;
  47260. }());
  47261. BABYLON.AnimationGroup = AnimationGroup;
  47262. })(BABYLON || (BABYLON = {}));
  47263. //# sourceMappingURL=babylon.animationGroup.js.map
  47264. var BABYLON;
  47265. (function (BABYLON) {
  47266. var RuntimeAnimation = /** @class */ (function () {
  47267. function RuntimeAnimation(target, animation) {
  47268. this._offsetsCache = {};
  47269. this._highLimitsCache = {};
  47270. this._stopped = false;
  47271. this._blendingFactor = 0;
  47272. this._ratioOffset = 0;
  47273. this._animation = animation;
  47274. this._target = target;
  47275. animation._runtimeAnimations.push(this);
  47276. }
  47277. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47278. get: function () {
  47279. return this._animation;
  47280. },
  47281. enumerable: true,
  47282. configurable: true
  47283. });
  47284. RuntimeAnimation.prototype.reset = function () {
  47285. this._offsetsCache = {};
  47286. this._highLimitsCache = {};
  47287. this.currentFrame = 0;
  47288. this._blendingFactor = 0;
  47289. this._originalBlendValue = null;
  47290. };
  47291. RuntimeAnimation.prototype.isStopped = function () {
  47292. return this._stopped;
  47293. };
  47294. RuntimeAnimation.prototype.dispose = function () {
  47295. var index = this._animation.runtimeAnimations.indexOf(this);
  47296. if (index > -1) {
  47297. this._animation.runtimeAnimations.splice(index, 1);
  47298. }
  47299. };
  47300. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47301. if (typeof value === "function") {
  47302. return value();
  47303. }
  47304. return value;
  47305. };
  47306. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47307. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47308. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47309. }
  47310. this.currentFrame = currentFrame;
  47311. var keys = this._animation.getKeys();
  47312. // Try to get a hash to find the right key
  47313. 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));
  47314. if (keys[startKeyIndex].frame >= currentFrame) {
  47315. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47316. startKeyIndex--;
  47317. }
  47318. }
  47319. for (var key = startKeyIndex; key < keys.length; key++) {
  47320. var endKey = keys[key + 1];
  47321. if (endKey.frame >= currentFrame) {
  47322. var startKey = keys[key];
  47323. var startValue = this._getKeyValue(startKey.value);
  47324. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47325. return startValue;
  47326. }
  47327. var endValue = this._getKeyValue(endKey.value);
  47328. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47329. var frameDelta = endKey.frame - startKey.frame;
  47330. // gradient : percent of currentFrame between the frame inf and the frame sup
  47331. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47332. // check for easingFunction and correction of gradient
  47333. var easingFunction = this._animation.getEasingFunction();
  47334. if (easingFunction != null) {
  47335. gradient = easingFunction.ease(gradient);
  47336. }
  47337. switch (this._animation.dataType) {
  47338. // Float
  47339. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47340. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47341. switch (loopMode) {
  47342. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47343. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47344. return floatValue;
  47345. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47346. return offsetValue * repeatCount + floatValue;
  47347. }
  47348. break;
  47349. // Quaternion
  47350. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47351. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47352. switch (loopMode) {
  47353. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47354. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47355. return quatValue;
  47356. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47357. return quatValue.add(offsetValue.scale(repeatCount));
  47358. }
  47359. return quatValue;
  47360. // Vector3
  47361. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47362. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47363. switch (loopMode) {
  47364. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47365. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47366. return vec3Value;
  47367. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47368. return vec3Value.add(offsetValue.scale(repeatCount));
  47369. }
  47370. // Vector2
  47371. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47372. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47373. switch (loopMode) {
  47374. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47375. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47376. return vec2Value;
  47377. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47378. return vec2Value.add(offsetValue.scale(repeatCount));
  47379. }
  47380. // Size
  47381. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47382. switch (loopMode) {
  47383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47385. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47387. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47388. }
  47389. // Color3
  47390. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47391. switch (loopMode) {
  47392. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47393. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47394. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47395. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47396. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47397. }
  47398. // Matrix
  47399. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47400. switch (loopMode) {
  47401. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47402. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47403. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47404. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47405. }
  47406. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47407. return startValue;
  47408. }
  47409. default:
  47410. break;
  47411. }
  47412. break;
  47413. }
  47414. }
  47415. return this._getKeyValue(keys[keys.length - 1].value);
  47416. };
  47417. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47418. if (blend === void 0) { blend = false; }
  47419. // Set value
  47420. var path;
  47421. var destination;
  47422. var targetPropertyPath = this._animation.targetPropertyPath;
  47423. if (targetPropertyPath.length > 1) {
  47424. var property = this._target[targetPropertyPath[0]];
  47425. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47426. property = property[targetPropertyPath[index]];
  47427. }
  47428. path = targetPropertyPath[targetPropertyPath.length - 1];
  47429. destination = property;
  47430. }
  47431. else {
  47432. path = targetPropertyPath[0];
  47433. destination = this._target;
  47434. }
  47435. // Blending
  47436. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47437. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47438. if (enableBlending && this._blendingFactor <= 1.0) {
  47439. if (!this._originalBlendValue) {
  47440. if (destination[path].clone) {
  47441. this._originalBlendValue = destination[path].clone();
  47442. }
  47443. else {
  47444. this._originalBlendValue = destination[path];
  47445. }
  47446. }
  47447. if (this._originalBlendValue.prototype) {
  47448. if (this._originalBlendValue.prototype.Lerp) {
  47449. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47450. }
  47451. else {
  47452. destination[path] = currentValue;
  47453. }
  47454. }
  47455. else if (this._originalBlendValue.m) {
  47456. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47457. }
  47458. else {
  47459. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47460. }
  47461. this._blendingFactor += blendingSpeed;
  47462. }
  47463. else {
  47464. destination[path] = currentValue;
  47465. }
  47466. if (this._target.markAsDirty) {
  47467. this._target.markAsDirty(this._animation.targetProperty);
  47468. }
  47469. };
  47470. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47471. if (this._target && this._target.animationPropertiesOverride) {
  47472. return this._target.animationPropertiesOverride.loopMode;
  47473. }
  47474. return this._animation.loopMode;
  47475. };
  47476. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47477. var keys = this._animation.getKeys();
  47478. if (frame < keys[0].frame) {
  47479. frame = keys[0].frame;
  47480. }
  47481. else if (frame > keys[keys.length - 1].frame) {
  47482. frame = keys[keys.length - 1].frame;
  47483. }
  47484. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47485. this.setValue(currentValue);
  47486. };
  47487. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47488. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47489. this._ratioOffset = this._previousRatio - newRatio;
  47490. };
  47491. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47492. if (blend === void 0) { blend = false; }
  47493. var targetPropertyPath = this._animation.targetPropertyPath;
  47494. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47495. this._stopped = true;
  47496. return false;
  47497. }
  47498. var returnValue = true;
  47499. var keys = this._animation.getKeys();
  47500. // Adding a start key at frame 0 if missing
  47501. if (keys[0].frame !== 0) {
  47502. var newKey = { frame: 0, value: keys[0].value };
  47503. keys.splice(0, 0, newKey);
  47504. }
  47505. // Check limits
  47506. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47507. from = keys[0].frame;
  47508. }
  47509. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47510. to = keys[keys.length - 1].frame;
  47511. }
  47512. //to and from cannot be the same key
  47513. if (from === to) {
  47514. if (from > keys[0].frame) {
  47515. from--;
  47516. }
  47517. else if (to < keys[keys.length - 1].frame) {
  47518. to++;
  47519. }
  47520. }
  47521. // Compute ratio
  47522. var range = to - from;
  47523. var offsetValue;
  47524. // ratio represents the frame delta between from and to
  47525. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47526. var highLimitValue = 0;
  47527. this._previousDelay = delay;
  47528. this._previousRatio = ratio;
  47529. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47530. returnValue = false;
  47531. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47532. }
  47533. else {
  47534. // Get max value if required
  47535. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47536. var keyOffset = to.toString() + from.toString();
  47537. if (!this._offsetsCache[keyOffset]) {
  47538. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47539. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47540. switch (this._animation.dataType) {
  47541. // Float
  47542. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47543. this._offsetsCache[keyOffset] = toValue - fromValue;
  47544. break;
  47545. // Quaternion
  47546. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47547. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47548. break;
  47549. // Vector3
  47550. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47551. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47552. // Vector2
  47553. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47554. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47555. // Size
  47556. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47557. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47558. // Color3
  47559. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47560. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47561. default:
  47562. break;
  47563. }
  47564. this._highLimitsCache[keyOffset] = toValue;
  47565. }
  47566. highLimitValue = this._highLimitsCache[keyOffset];
  47567. offsetValue = this._offsetsCache[keyOffset];
  47568. }
  47569. }
  47570. if (offsetValue === undefined) {
  47571. switch (this._animation.dataType) {
  47572. // Float
  47573. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47574. offsetValue = 0;
  47575. break;
  47576. // Quaternion
  47577. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47578. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47579. break;
  47580. // Vector3
  47581. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47582. offsetValue = BABYLON.Vector3.Zero();
  47583. break;
  47584. // Vector2
  47585. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47586. offsetValue = BABYLON.Vector2.Zero();
  47587. break;
  47588. // Size
  47589. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47590. offsetValue = BABYLON.Size.Zero();
  47591. break;
  47592. // Color3
  47593. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47594. offsetValue = BABYLON.Color3.Black();
  47595. }
  47596. }
  47597. // Compute value
  47598. var repeatCount = (ratio / range) >> 0;
  47599. var currentFrame = returnValue ? from + ratio % range : to;
  47600. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47601. // Set value
  47602. this.setValue(currentValue);
  47603. // Check events
  47604. var events = this._animation.getEvents();
  47605. for (var index = 0; index < events.length; index++) {
  47606. // Make sure current frame has passed event frame and that event frame is within the current range
  47607. // Also, handle both forward and reverse animations
  47608. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47609. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47610. var event = events[index];
  47611. if (!event.isDone) {
  47612. // If event should be done only once, remove it.
  47613. if (event.onlyOnce) {
  47614. events.splice(index, 1);
  47615. index--;
  47616. }
  47617. event.isDone = true;
  47618. event.action();
  47619. } // Don't do anything if the event has already be done.
  47620. }
  47621. else if (events[index].isDone && !events[index].onlyOnce) {
  47622. // reset event, the animation is looping
  47623. events[index].isDone = false;
  47624. }
  47625. }
  47626. if (!returnValue) {
  47627. this._stopped = true;
  47628. }
  47629. return returnValue;
  47630. };
  47631. return RuntimeAnimation;
  47632. }());
  47633. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47634. })(BABYLON || (BABYLON = {}));
  47635. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47636. var BABYLON;
  47637. (function (BABYLON) {
  47638. var Animatable = /** @class */ (function () {
  47639. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47640. if (fromFrame === void 0) { fromFrame = 0; }
  47641. if (toFrame === void 0) { toFrame = 100; }
  47642. if (loopAnimation === void 0) { loopAnimation = false; }
  47643. if (speedRatio === void 0) { speedRatio = 1.0; }
  47644. this.target = target;
  47645. this.fromFrame = fromFrame;
  47646. this.toFrame = toFrame;
  47647. this.loopAnimation = loopAnimation;
  47648. this.onAnimationEnd = onAnimationEnd;
  47649. this._localDelayOffset = null;
  47650. this._pausedDelay = null;
  47651. this._runtimeAnimations = new Array();
  47652. this._paused = false;
  47653. this._speedRatio = 1;
  47654. this.animationStarted = false;
  47655. if (animations) {
  47656. this.appendAnimations(target, animations);
  47657. }
  47658. this._speedRatio = speedRatio;
  47659. this._scene = scene;
  47660. scene._activeAnimatables.push(this);
  47661. }
  47662. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47663. get: function () {
  47664. return this._speedRatio;
  47665. },
  47666. set: function (value) {
  47667. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47668. var animation = this._runtimeAnimations[index];
  47669. animation._prepareForSpeedRatioChange(value);
  47670. }
  47671. this._speedRatio = value;
  47672. },
  47673. enumerable: true,
  47674. configurable: true
  47675. });
  47676. // Methods
  47677. Animatable.prototype.getAnimations = function () {
  47678. return this._runtimeAnimations;
  47679. };
  47680. Animatable.prototype.appendAnimations = function (target, animations) {
  47681. for (var index = 0; index < animations.length; index++) {
  47682. var animation = animations[index];
  47683. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47684. }
  47685. };
  47686. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47687. var runtimeAnimations = this._runtimeAnimations;
  47688. for (var index = 0; index < runtimeAnimations.length; index++) {
  47689. if (runtimeAnimations[index].animation.targetProperty === property) {
  47690. return runtimeAnimations[index].animation;
  47691. }
  47692. }
  47693. return null;
  47694. };
  47695. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47696. var runtimeAnimations = this._runtimeAnimations;
  47697. for (var index = 0; index < runtimeAnimations.length; index++) {
  47698. if (runtimeAnimations[index].animation.targetProperty === property) {
  47699. return runtimeAnimations[index];
  47700. }
  47701. }
  47702. return null;
  47703. };
  47704. Animatable.prototype.reset = function () {
  47705. var runtimeAnimations = this._runtimeAnimations;
  47706. for (var index = 0; index < runtimeAnimations.length; index++) {
  47707. runtimeAnimations[index].reset();
  47708. }
  47709. // Reset to original value
  47710. for (index = 0; index < runtimeAnimations.length; index++) {
  47711. var animation = runtimeAnimations[index];
  47712. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47713. }
  47714. this._localDelayOffset = null;
  47715. this._pausedDelay = null;
  47716. };
  47717. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47718. var runtimeAnimations = this._runtimeAnimations;
  47719. for (var index = 0; index < runtimeAnimations.length; index++) {
  47720. runtimeAnimations[index].animation.enableBlending = true;
  47721. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47722. }
  47723. };
  47724. Animatable.prototype.disableBlending = function () {
  47725. var runtimeAnimations = this._runtimeAnimations;
  47726. for (var index = 0; index < runtimeAnimations.length; index++) {
  47727. runtimeAnimations[index].animation.enableBlending = false;
  47728. }
  47729. };
  47730. Animatable.prototype.goToFrame = function (frame) {
  47731. var runtimeAnimations = this._runtimeAnimations;
  47732. if (runtimeAnimations[0]) {
  47733. var fps = runtimeAnimations[0].animation.framePerSecond;
  47734. var currentFrame = runtimeAnimations[0].currentFrame;
  47735. var adjustTime = frame - currentFrame;
  47736. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47737. if (this._localDelayOffset === null) {
  47738. this._localDelayOffset = 0;
  47739. }
  47740. this._localDelayOffset -= delay;
  47741. }
  47742. for (var index = 0; index < runtimeAnimations.length; index++) {
  47743. runtimeAnimations[index].goToFrame(frame);
  47744. }
  47745. };
  47746. Animatable.prototype.pause = function () {
  47747. if (this._paused) {
  47748. return;
  47749. }
  47750. this._paused = true;
  47751. };
  47752. Animatable.prototype.restart = function () {
  47753. this._paused = false;
  47754. };
  47755. Animatable.prototype.stop = function (animationName) {
  47756. if (animationName) {
  47757. var idx = this._scene._activeAnimatables.indexOf(this);
  47758. if (idx > -1) {
  47759. var runtimeAnimations = this._runtimeAnimations;
  47760. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47761. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47762. continue;
  47763. }
  47764. runtimeAnimations[index].dispose();
  47765. runtimeAnimations.splice(index, 1);
  47766. }
  47767. if (runtimeAnimations.length == 0) {
  47768. this._scene._activeAnimatables.splice(idx, 1);
  47769. if (this.onAnimationEnd) {
  47770. this.onAnimationEnd();
  47771. }
  47772. }
  47773. }
  47774. }
  47775. else {
  47776. var index = this._scene._activeAnimatables.indexOf(this);
  47777. if (index > -1) {
  47778. this._scene._activeAnimatables.splice(index, 1);
  47779. var runtimeAnimations = this._runtimeAnimations;
  47780. for (var index = 0; index < runtimeAnimations.length; index++) {
  47781. runtimeAnimations[index].dispose();
  47782. }
  47783. if (this.onAnimationEnd) {
  47784. this.onAnimationEnd();
  47785. }
  47786. }
  47787. }
  47788. };
  47789. Animatable.prototype._animate = function (delay) {
  47790. if (this._paused) {
  47791. this.animationStarted = false;
  47792. if (this._pausedDelay === null) {
  47793. this._pausedDelay = delay;
  47794. }
  47795. return true;
  47796. }
  47797. if (this._localDelayOffset === null) {
  47798. this._localDelayOffset = delay;
  47799. this._pausedDelay = null;
  47800. }
  47801. else if (this._pausedDelay !== null) {
  47802. this._localDelayOffset += delay - this._pausedDelay;
  47803. this._pausedDelay = null;
  47804. }
  47805. // Animating
  47806. var running = false;
  47807. var runtimeAnimations = this._runtimeAnimations;
  47808. var index;
  47809. for (index = 0; index < runtimeAnimations.length; index++) {
  47810. var animation = runtimeAnimations[index];
  47811. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47812. running = running || isRunning;
  47813. }
  47814. this.animationStarted = running;
  47815. if (!running) {
  47816. // Remove from active animatables
  47817. index = this._scene._activeAnimatables.indexOf(this);
  47818. this._scene._activeAnimatables.splice(index, 1);
  47819. // Dispose all runtime animations
  47820. for (index = 0; index < runtimeAnimations.length; index++) {
  47821. runtimeAnimations[index].dispose();
  47822. }
  47823. }
  47824. if (!running && this.onAnimationEnd) {
  47825. this.onAnimationEnd();
  47826. this.onAnimationEnd = null;
  47827. }
  47828. return running;
  47829. };
  47830. return Animatable;
  47831. }());
  47832. BABYLON.Animatable = Animatable;
  47833. })(BABYLON || (BABYLON = {}));
  47834. //# sourceMappingURL=babylon.animatable.js.map
  47835. var BABYLON;
  47836. (function (BABYLON) {
  47837. var EasingFunction = /** @class */ (function () {
  47838. function EasingFunction() {
  47839. // Properties
  47840. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47841. }
  47842. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47843. get: function () {
  47844. return EasingFunction._EASINGMODE_EASEIN;
  47845. },
  47846. enumerable: true,
  47847. configurable: true
  47848. });
  47849. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47850. get: function () {
  47851. return EasingFunction._EASINGMODE_EASEOUT;
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47857. get: function () {
  47858. return EasingFunction._EASINGMODE_EASEINOUT;
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47864. var n = Math.min(Math.max(easingMode, 0), 2);
  47865. this._easingMode = n;
  47866. };
  47867. EasingFunction.prototype.getEasingMode = function () {
  47868. return this._easingMode;
  47869. };
  47870. EasingFunction.prototype.easeInCore = function (gradient) {
  47871. throw new Error('You must implement this method');
  47872. };
  47873. EasingFunction.prototype.ease = function (gradient) {
  47874. switch (this._easingMode) {
  47875. case EasingFunction.EASINGMODE_EASEIN:
  47876. return this.easeInCore(gradient);
  47877. case EasingFunction.EASINGMODE_EASEOUT:
  47878. return (1 - this.easeInCore(1 - gradient));
  47879. }
  47880. if (gradient >= 0.5) {
  47881. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47882. }
  47883. return (this.easeInCore(gradient * 2) * 0.5);
  47884. };
  47885. //Statics
  47886. EasingFunction._EASINGMODE_EASEIN = 0;
  47887. EasingFunction._EASINGMODE_EASEOUT = 1;
  47888. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47889. return EasingFunction;
  47890. }());
  47891. BABYLON.EasingFunction = EasingFunction;
  47892. var CircleEase = /** @class */ (function (_super) {
  47893. __extends(CircleEase, _super);
  47894. function CircleEase() {
  47895. return _super !== null && _super.apply(this, arguments) || this;
  47896. }
  47897. CircleEase.prototype.easeInCore = function (gradient) {
  47898. gradient = Math.max(0, Math.min(1, gradient));
  47899. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47900. };
  47901. return CircleEase;
  47902. }(EasingFunction));
  47903. BABYLON.CircleEase = CircleEase;
  47904. var BackEase = /** @class */ (function (_super) {
  47905. __extends(BackEase, _super);
  47906. function BackEase(amplitude) {
  47907. if (amplitude === void 0) { amplitude = 1; }
  47908. var _this = _super.call(this) || this;
  47909. _this.amplitude = amplitude;
  47910. return _this;
  47911. }
  47912. BackEase.prototype.easeInCore = function (gradient) {
  47913. var num = Math.max(0, this.amplitude);
  47914. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47915. };
  47916. return BackEase;
  47917. }(EasingFunction));
  47918. BABYLON.BackEase = BackEase;
  47919. var BounceEase = /** @class */ (function (_super) {
  47920. __extends(BounceEase, _super);
  47921. function BounceEase(bounces, bounciness) {
  47922. if (bounces === void 0) { bounces = 3; }
  47923. if (bounciness === void 0) { bounciness = 2; }
  47924. var _this = _super.call(this) || this;
  47925. _this.bounces = bounces;
  47926. _this.bounciness = bounciness;
  47927. return _this;
  47928. }
  47929. BounceEase.prototype.easeInCore = function (gradient) {
  47930. var y = Math.max(0.0, this.bounces);
  47931. var bounciness = this.bounciness;
  47932. if (bounciness <= 1.0) {
  47933. bounciness = 1.001;
  47934. }
  47935. var num9 = Math.pow(bounciness, y);
  47936. var num5 = 1.0 - bounciness;
  47937. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47938. var num15 = gradient * num4;
  47939. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47940. var num3 = Math.floor(num65);
  47941. var num13 = num3 + 1.0;
  47942. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47943. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47944. var num7 = (num8 + num12) * 0.5;
  47945. var num6 = gradient - num7;
  47946. var num2 = num7 - num8;
  47947. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47948. };
  47949. return BounceEase;
  47950. }(EasingFunction));
  47951. BABYLON.BounceEase = BounceEase;
  47952. var CubicEase = /** @class */ (function (_super) {
  47953. __extends(CubicEase, _super);
  47954. function CubicEase() {
  47955. return _super !== null && _super.apply(this, arguments) || this;
  47956. }
  47957. CubicEase.prototype.easeInCore = function (gradient) {
  47958. return (gradient * gradient * gradient);
  47959. };
  47960. return CubicEase;
  47961. }(EasingFunction));
  47962. BABYLON.CubicEase = CubicEase;
  47963. var ElasticEase = /** @class */ (function (_super) {
  47964. __extends(ElasticEase, _super);
  47965. function ElasticEase(oscillations, springiness) {
  47966. if (oscillations === void 0) { oscillations = 3; }
  47967. if (springiness === void 0) { springiness = 3; }
  47968. var _this = _super.call(this) || this;
  47969. _this.oscillations = oscillations;
  47970. _this.springiness = springiness;
  47971. return _this;
  47972. }
  47973. ElasticEase.prototype.easeInCore = function (gradient) {
  47974. var num2;
  47975. var num3 = Math.max(0.0, this.oscillations);
  47976. var num = Math.max(0.0, this.springiness);
  47977. if (num == 0) {
  47978. num2 = gradient;
  47979. }
  47980. else {
  47981. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47982. }
  47983. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47984. };
  47985. return ElasticEase;
  47986. }(EasingFunction));
  47987. BABYLON.ElasticEase = ElasticEase;
  47988. var ExponentialEase = /** @class */ (function (_super) {
  47989. __extends(ExponentialEase, _super);
  47990. function ExponentialEase(exponent) {
  47991. if (exponent === void 0) { exponent = 2; }
  47992. var _this = _super.call(this) || this;
  47993. _this.exponent = exponent;
  47994. return _this;
  47995. }
  47996. ExponentialEase.prototype.easeInCore = function (gradient) {
  47997. if (this.exponent <= 0) {
  47998. return gradient;
  47999. }
  48000. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48001. };
  48002. return ExponentialEase;
  48003. }(EasingFunction));
  48004. BABYLON.ExponentialEase = ExponentialEase;
  48005. var PowerEase = /** @class */ (function (_super) {
  48006. __extends(PowerEase, _super);
  48007. function PowerEase(power) {
  48008. if (power === void 0) { power = 2; }
  48009. var _this = _super.call(this) || this;
  48010. _this.power = power;
  48011. return _this;
  48012. }
  48013. PowerEase.prototype.easeInCore = function (gradient) {
  48014. var y = Math.max(0.0, this.power);
  48015. return Math.pow(gradient, y);
  48016. };
  48017. return PowerEase;
  48018. }(EasingFunction));
  48019. BABYLON.PowerEase = PowerEase;
  48020. var QuadraticEase = /** @class */ (function (_super) {
  48021. __extends(QuadraticEase, _super);
  48022. function QuadraticEase() {
  48023. return _super !== null && _super.apply(this, arguments) || this;
  48024. }
  48025. QuadraticEase.prototype.easeInCore = function (gradient) {
  48026. return (gradient * gradient);
  48027. };
  48028. return QuadraticEase;
  48029. }(EasingFunction));
  48030. BABYLON.QuadraticEase = QuadraticEase;
  48031. var QuarticEase = /** @class */ (function (_super) {
  48032. __extends(QuarticEase, _super);
  48033. function QuarticEase() {
  48034. return _super !== null && _super.apply(this, arguments) || this;
  48035. }
  48036. QuarticEase.prototype.easeInCore = function (gradient) {
  48037. return (gradient * gradient * gradient * gradient);
  48038. };
  48039. return QuarticEase;
  48040. }(EasingFunction));
  48041. BABYLON.QuarticEase = QuarticEase;
  48042. var QuinticEase = /** @class */ (function (_super) {
  48043. __extends(QuinticEase, _super);
  48044. function QuinticEase() {
  48045. return _super !== null && _super.apply(this, arguments) || this;
  48046. }
  48047. QuinticEase.prototype.easeInCore = function (gradient) {
  48048. return (gradient * gradient * gradient * gradient * gradient);
  48049. };
  48050. return QuinticEase;
  48051. }(EasingFunction));
  48052. BABYLON.QuinticEase = QuinticEase;
  48053. var SineEase = /** @class */ (function (_super) {
  48054. __extends(SineEase, _super);
  48055. function SineEase() {
  48056. return _super !== null && _super.apply(this, arguments) || this;
  48057. }
  48058. SineEase.prototype.easeInCore = function (gradient) {
  48059. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48060. };
  48061. return SineEase;
  48062. }(EasingFunction));
  48063. BABYLON.SineEase = SineEase;
  48064. var BezierCurveEase = /** @class */ (function (_super) {
  48065. __extends(BezierCurveEase, _super);
  48066. function BezierCurveEase(x1, y1, x2, y2) {
  48067. if (x1 === void 0) { x1 = 0; }
  48068. if (y1 === void 0) { y1 = 0; }
  48069. if (x2 === void 0) { x2 = 1; }
  48070. if (y2 === void 0) { y2 = 1; }
  48071. var _this = _super.call(this) || this;
  48072. _this.x1 = x1;
  48073. _this.y1 = y1;
  48074. _this.x2 = x2;
  48075. _this.y2 = y2;
  48076. return _this;
  48077. }
  48078. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48079. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48080. };
  48081. return BezierCurveEase;
  48082. }(EasingFunction));
  48083. BABYLON.BezierCurveEase = BezierCurveEase;
  48084. })(BABYLON || (BABYLON = {}));
  48085. //# sourceMappingURL=babylon.easing.js.map
  48086. var BABYLON;
  48087. (function (BABYLON) {
  48088. var Condition = /** @class */ (function () {
  48089. function Condition(actionManager) {
  48090. this._actionManager = actionManager;
  48091. }
  48092. Condition.prototype.isValid = function () {
  48093. return true;
  48094. };
  48095. Condition.prototype._getProperty = function (propertyPath) {
  48096. return this._actionManager._getProperty(propertyPath);
  48097. };
  48098. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48099. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48100. };
  48101. Condition.prototype.serialize = function () {
  48102. };
  48103. Condition.prototype._serialize = function (serializedCondition) {
  48104. return {
  48105. type: 2,
  48106. children: [],
  48107. name: serializedCondition.name,
  48108. properties: serializedCondition.properties
  48109. };
  48110. };
  48111. return Condition;
  48112. }());
  48113. BABYLON.Condition = Condition;
  48114. var ValueCondition = /** @class */ (function (_super) {
  48115. __extends(ValueCondition, _super);
  48116. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48117. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48118. var _this = _super.call(this, actionManager) || this;
  48119. _this.propertyPath = propertyPath;
  48120. _this.value = value;
  48121. _this.operator = operator;
  48122. _this._target = target;
  48123. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48124. _this._property = _this._getProperty(_this.propertyPath);
  48125. return _this;
  48126. }
  48127. Object.defineProperty(ValueCondition, "IsEqual", {
  48128. get: function () {
  48129. return ValueCondition._IsEqual;
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. Object.defineProperty(ValueCondition, "IsDifferent", {
  48135. get: function () {
  48136. return ValueCondition._IsDifferent;
  48137. },
  48138. enumerable: true,
  48139. configurable: true
  48140. });
  48141. Object.defineProperty(ValueCondition, "IsGreater", {
  48142. get: function () {
  48143. return ValueCondition._IsGreater;
  48144. },
  48145. enumerable: true,
  48146. configurable: true
  48147. });
  48148. Object.defineProperty(ValueCondition, "IsLesser", {
  48149. get: function () {
  48150. return ValueCondition._IsLesser;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. // Methods
  48156. ValueCondition.prototype.isValid = function () {
  48157. switch (this.operator) {
  48158. case ValueCondition.IsGreater:
  48159. return this._effectiveTarget[this._property] > this.value;
  48160. case ValueCondition.IsLesser:
  48161. return this._effectiveTarget[this._property] < this.value;
  48162. case ValueCondition.IsEqual:
  48163. case ValueCondition.IsDifferent:
  48164. var check;
  48165. if (this.value.equals) {
  48166. check = this.value.equals(this._effectiveTarget[this._property]);
  48167. }
  48168. else {
  48169. check = this.value === this._effectiveTarget[this._property];
  48170. }
  48171. return this.operator === ValueCondition.IsEqual ? check : !check;
  48172. }
  48173. return false;
  48174. };
  48175. ValueCondition.prototype.serialize = function () {
  48176. return this._serialize({
  48177. name: "ValueCondition",
  48178. properties: [
  48179. BABYLON.Action._GetTargetProperty(this._target),
  48180. { name: "propertyPath", value: this.propertyPath },
  48181. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48182. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48183. ]
  48184. });
  48185. };
  48186. ValueCondition.GetOperatorName = function (operator) {
  48187. switch (operator) {
  48188. case ValueCondition._IsEqual: return "IsEqual";
  48189. case ValueCondition._IsDifferent: return "IsDifferent";
  48190. case ValueCondition._IsGreater: return "IsGreater";
  48191. case ValueCondition._IsLesser: return "IsLesser";
  48192. default: return "";
  48193. }
  48194. };
  48195. // Statics
  48196. ValueCondition._IsEqual = 0;
  48197. ValueCondition._IsDifferent = 1;
  48198. ValueCondition._IsGreater = 2;
  48199. ValueCondition._IsLesser = 3;
  48200. return ValueCondition;
  48201. }(Condition));
  48202. BABYLON.ValueCondition = ValueCondition;
  48203. var PredicateCondition = /** @class */ (function (_super) {
  48204. __extends(PredicateCondition, _super);
  48205. function PredicateCondition(actionManager, predicate) {
  48206. var _this = _super.call(this, actionManager) || this;
  48207. _this.predicate = predicate;
  48208. return _this;
  48209. }
  48210. PredicateCondition.prototype.isValid = function () {
  48211. return this.predicate();
  48212. };
  48213. return PredicateCondition;
  48214. }(Condition));
  48215. BABYLON.PredicateCondition = PredicateCondition;
  48216. var StateCondition = /** @class */ (function (_super) {
  48217. __extends(StateCondition, _super);
  48218. function StateCondition(actionManager, target, value) {
  48219. var _this = _super.call(this, actionManager) || this;
  48220. _this.value = value;
  48221. _this._target = target;
  48222. return _this;
  48223. }
  48224. // Methods
  48225. StateCondition.prototype.isValid = function () {
  48226. return this._target.state === this.value;
  48227. };
  48228. StateCondition.prototype.serialize = function () {
  48229. return this._serialize({
  48230. name: "StateCondition",
  48231. properties: [
  48232. BABYLON.Action._GetTargetProperty(this._target),
  48233. { name: "value", value: this.value }
  48234. ]
  48235. });
  48236. };
  48237. return StateCondition;
  48238. }(Condition));
  48239. BABYLON.StateCondition = StateCondition;
  48240. })(BABYLON || (BABYLON = {}));
  48241. //# sourceMappingURL=babylon.condition.js.map
  48242. var BABYLON;
  48243. (function (BABYLON) {
  48244. var Action = /** @class */ (function () {
  48245. function Action(triggerOptions, condition) {
  48246. this.triggerOptions = triggerOptions;
  48247. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48248. if (triggerOptions.parameter) {
  48249. this.trigger = triggerOptions.trigger;
  48250. this._triggerParameter = triggerOptions.parameter;
  48251. }
  48252. else {
  48253. this.trigger = triggerOptions;
  48254. }
  48255. this._nextActiveAction = this;
  48256. this._condition = condition;
  48257. }
  48258. // Methods
  48259. Action.prototype._prepare = function () {
  48260. };
  48261. Action.prototype.getTriggerParameter = function () {
  48262. return this._triggerParameter;
  48263. };
  48264. Action.prototype._executeCurrent = function (evt) {
  48265. if (this._nextActiveAction._condition) {
  48266. var condition = this._nextActiveAction._condition;
  48267. var currentRenderId = this._actionManager.getScene().getRenderId();
  48268. // We cache the current evaluation for the current frame
  48269. if (condition._evaluationId === currentRenderId) {
  48270. if (!condition._currentResult) {
  48271. return;
  48272. }
  48273. }
  48274. else {
  48275. condition._evaluationId = currentRenderId;
  48276. if (!condition.isValid()) {
  48277. condition._currentResult = false;
  48278. return;
  48279. }
  48280. condition._currentResult = true;
  48281. }
  48282. }
  48283. this.onBeforeExecuteObservable.notifyObservers(this);
  48284. this._nextActiveAction.execute(evt);
  48285. this.skipToNextActiveAction();
  48286. };
  48287. Action.prototype.execute = function (evt) {
  48288. };
  48289. Action.prototype.skipToNextActiveAction = function () {
  48290. if (this._nextActiveAction._child) {
  48291. if (!this._nextActiveAction._child._actionManager) {
  48292. this._nextActiveAction._child._actionManager = this._actionManager;
  48293. }
  48294. this._nextActiveAction = this._nextActiveAction._child;
  48295. }
  48296. else {
  48297. this._nextActiveAction = this;
  48298. }
  48299. };
  48300. Action.prototype.then = function (action) {
  48301. this._child = action;
  48302. action._actionManager = this._actionManager;
  48303. action._prepare();
  48304. return action;
  48305. };
  48306. Action.prototype._getProperty = function (propertyPath) {
  48307. return this._actionManager._getProperty(propertyPath);
  48308. };
  48309. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48310. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48311. };
  48312. Action.prototype.serialize = function (parent) {
  48313. };
  48314. // Called by BABYLON.Action objects in serialize(...). Internal use
  48315. Action.prototype._serialize = function (serializedAction, parent) {
  48316. var serializationObject = {
  48317. type: 1,
  48318. children: [],
  48319. name: serializedAction.name,
  48320. properties: serializedAction.properties || []
  48321. };
  48322. // Serialize child
  48323. if (this._child) {
  48324. this._child.serialize(serializationObject);
  48325. }
  48326. // Check if "this" has a condition
  48327. if (this._condition) {
  48328. var serializedCondition = this._condition.serialize();
  48329. serializedCondition.children.push(serializationObject);
  48330. if (parent) {
  48331. parent.children.push(serializedCondition);
  48332. }
  48333. return serializedCondition;
  48334. }
  48335. if (parent) {
  48336. parent.children.push(serializationObject);
  48337. }
  48338. return serializationObject;
  48339. };
  48340. Action._SerializeValueAsString = function (value) {
  48341. if (typeof value === "number") {
  48342. return value.toString();
  48343. }
  48344. if (typeof value === "boolean") {
  48345. return value ? "true" : "false";
  48346. }
  48347. if (value instanceof BABYLON.Vector2) {
  48348. return value.x + ", " + value.y;
  48349. }
  48350. if (value instanceof BABYLON.Vector3) {
  48351. return value.x + ", " + value.y + ", " + value.z;
  48352. }
  48353. if (value instanceof BABYLON.Color3) {
  48354. return value.r + ", " + value.g + ", " + value.b;
  48355. }
  48356. if (value instanceof BABYLON.Color4) {
  48357. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48358. }
  48359. return value; // string
  48360. };
  48361. Action._GetTargetProperty = function (target) {
  48362. return {
  48363. name: "target",
  48364. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48365. : target instanceof BABYLON.Light ? "LightProperties"
  48366. : target instanceof BABYLON.Camera ? "CameraProperties"
  48367. : "SceneProperties",
  48368. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48369. };
  48370. };
  48371. return Action;
  48372. }());
  48373. BABYLON.Action = Action;
  48374. })(BABYLON || (BABYLON = {}));
  48375. //# sourceMappingURL=babylon.action.js.map
  48376. var BABYLON;
  48377. (function (BABYLON) {
  48378. /**
  48379. * ActionEvent is the event beint sent when an action is triggered.
  48380. */
  48381. var ActionEvent = /** @class */ (function () {
  48382. /**
  48383. * @param source The mesh or sprite that triggered the action.
  48384. * @param pointerX The X mouse cursor position at the time of the event
  48385. * @param pointerY The Y mouse cursor position at the time of the event
  48386. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48387. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48388. */
  48389. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48390. this.source = source;
  48391. this.pointerX = pointerX;
  48392. this.pointerY = pointerY;
  48393. this.meshUnderPointer = meshUnderPointer;
  48394. this.sourceEvent = sourceEvent;
  48395. this.additionalData = additionalData;
  48396. }
  48397. /**
  48398. * Helper function to auto-create an ActionEvent from a source mesh.
  48399. * @param source The source mesh that triggered the event
  48400. * @param evt {Event} The original (browser) event
  48401. */
  48402. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48403. var scene = source.getScene();
  48404. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48405. };
  48406. /**
  48407. * Helper function to auto-create an ActionEvent from a source mesh.
  48408. * @param source The source sprite that triggered the event
  48409. * @param scene Scene associated with the sprite
  48410. * @param evt {Event} The original (browser) event
  48411. */
  48412. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48413. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48414. };
  48415. /**
  48416. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48417. * @param scene the scene where the event occurred
  48418. * @param evt {Event} The original (browser) event
  48419. */
  48420. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48421. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48422. };
  48423. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48424. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48425. };
  48426. return ActionEvent;
  48427. }());
  48428. BABYLON.ActionEvent = ActionEvent;
  48429. /**
  48430. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48431. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48432. */
  48433. var ActionManager = /** @class */ (function () {
  48434. function ActionManager(scene) {
  48435. // Members
  48436. this.actions = new Array();
  48437. this.hoverCursor = '';
  48438. this._scene = scene;
  48439. scene._actionManagers.push(this);
  48440. }
  48441. Object.defineProperty(ActionManager, "NothingTrigger", {
  48442. get: function () {
  48443. return ActionManager._NothingTrigger;
  48444. },
  48445. enumerable: true,
  48446. configurable: true
  48447. });
  48448. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48449. get: function () {
  48450. return ActionManager._OnPickTrigger;
  48451. },
  48452. enumerable: true,
  48453. configurable: true
  48454. });
  48455. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48456. get: function () {
  48457. return ActionManager._OnLeftPickTrigger;
  48458. },
  48459. enumerable: true,
  48460. configurable: true
  48461. });
  48462. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48463. get: function () {
  48464. return ActionManager._OnRightPickTrigger;
  48465. },
  48466. enumerable: true,
  48467. configurable: true
  48468. });
  48469. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48470. get: function () {
  48471. return ActionManager._OnCenterPickTrigger;
  48472. },
  48473. enumerable: true,
  48474. configurable: true
  48475. });
  48476. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48477. get: function () {
  48478. return ActionManager._OnPickDownTrigger;
  48479. },
  48480. enumerable: true,
  48481. configurable: true
  48482. });
  48483. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48484. get: function () {
  48485. return ActionManager._OnDoublePickTrigger;
  48486. },
  48487. enumerable: true,
  48488. configurable: true
  48489. });
  48490. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48491. get: function () {
  48492. return ActionManager._OnPickUpTrigger;
  48493. },
  48494. enumerable: true,
  48495. configurable: true
  48496. });
  48497. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48498. /// This trigger will only be raised if you also declared a OnPickDown
  48499. get: function () {
  48500. return ActionManager._OnPickOutTrigger;
  48501. },
  48502. enumerable: true,
  48503. configurable: true
  48504. });
  48505. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48506. get: function () {
  48507. return ActionManager._OnLongPressTrigger;
  48508. },
  48509. enumerable: true,
  48510. configurable: true
  48511. });
  48512. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48513. get: function () {
  48514. return ActionManager._OnPointerOverTrigger;
  48515. },
  48516. enumerable: true,
  48517. configurable: true
  48518. });
  48519. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48520. get: function () {
  48521. return ActionManager._OnPointerOutTrigger;
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48527. get: function () {
  48528. return ActionManager._OnEveryFrameTrigger;
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48534. get: function () {
  48535. return ActionManager._OnIntersectionEnterTrigger;
  48536. },
  48537. enumerable: true,
  48538. configurable: true
  48539. });
  48540. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48541. get: function () {
  48542. return ActionManager._OnIntersectionExitTrigger;
  48543. },
  48544. enumerable: true,
  48545. configurable: true
  48546. });
  48547. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48548. get: function () {
  48549. return ActionManager._OnKeyDownTrigger;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48555. get: function () {
  48556. return ActionManager._OnKeyUpTrigger;
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. // Methods
  48562. ActionManager.prototype.dispose = function () {
  48563. var index = this._scene._actionManagers.indexOf(this);
  48564. for (var i = 0; i < this.actions.length; i++) {
  48565. var action = this.actions[i];
  48566. ActionManager.Triggers[action.trigger]--;
  48567. if (ActionManager.Triggers[action.trigger] === 0) {
  48568. delete ActionManager.Triggers[action.trigger];
  48569. }
  48570. }
  48571. if (index > -1) {
  48572. this._scene._actionManagers.splice(index, 1);
  48573. }
  48574. };
  48575. ActionManager.prototype.getScene = function () {
  48576. return this._scene;
  48577. };
  48578. /**
  48579. * Does this action manager handles actions of any of the given triggers
  48580. * @param {number[]} triggers - the triggers to be tested
  48581. * @return {boolean} whether one (or more) of the triggers is handeled
  48582. */
  48583. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48584. for (var index = 0; index < this.actions.length; index++) {
  48585. var action = this.actions[index];
  48586. if (triggers.indexOf(action.trigger) > -1) {
  48587. return true;
  48588. }
  48589. }
  48590. return false;
  48591. };
  48592. /**
  48593. * Does this action manager handles actions of a given trigger
  48594. * @param {number} trigger - the trigger to be tested
  48595. * @return {boolean} whether the trigger is handeled
  48596. */
  48597. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48598. for (var index = 0; index < this.actions.length; index++) {
  48599. var action = this.actions[index];
  48600. if (action.trigger === trigger) {
  48601. return true;
  48602. }
  48603. }
  48604. return false;
  48605. };
  48606. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48607. /**
  48608. * Does this action manager has pointer triggers
  48609. * @return {boolean} whether or not it has pointer triggers
  48610. */
  48611. get: function () {
  48612. for (var index = 0; index < this.actions.length; index++) {
  48613. var action = this.actions[index];
  48614. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48615. return true;
  48616. }
  48617. }
  48618. return false;
  48619. },
  48620. enumerable: true,
  48621. configurable: true
  48622. });
  48623. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48624. /**
  48625. * Does this action manager has pick triggers
  48626. * @return {boolean} whether or not it has pick triggers
  48627. */
  48628. get: function () {
  48629. for (var index = 0; index < this.actions.length; index++) {
  48630. var action = this.actions[index];
  48631. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48632. return true;
  48633. }
  48634. }
  48635. return false;
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(ActionManager, "HasTriggers", {
  48641. /**
  48642. * Does exist one action manager with at least one trigger
  48643. * @return {boolean} whether or not it exists one action manager with one trigger
  48644. **/
  48645. get: function () {
  48646. for (var t in ActionManager.Triggers) {
  48647. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48648. return true;
  48649. }
  48650. }
  48651. return false;
  48652. },
  48653. enumerable: true,
  48654. configurable: true
  48655. });
  48656. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48657. /**
  48658. * Does exist one action manager with at least one pick trigger
  48659. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48660. **/
  48661. get: function () {
  48662. for (var t in ActionManager.Triggers) {
  48663. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48664. var t_int = parseInt(t);
  48665. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48666. return true;
  48667. }
  48668. }
  48669. }
  48670. return false;
  48671. },
  48672. enumerable: true,
  48673. configurable: true
  48674. });
  48675. /**
  48676. * Does exist one action manager that handles actions of a given trigger
  48677. * @param {number} trigger - the trigger to be tested
  48678. * @return {boolean} whether the trigger is handeled by at least one action manager
  48679. **/
  48680. ActionManager.HasSpecificTrigger = function (trigger) {
  48681. for (var t in ActionManager.Triggers) {
  48682. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48683. var t_int = parseInt(t);
  48684. if (t_int === trigger) {
  48685. return true;
  48686. }
  48687. }
  48688. }
  48689. return false;
  48690. };
  48691. /**
  48692. * Registers an action to this action manager
  48693. * @param {BABYLON.Action} action - the action to be registered
  48694. * @return {BABYLON.Action} the action amended (prepared) after registration
  48695. */
  48696. ActionManager.prototype.registerAction = function (action) {
  48697. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48698. if (this.getScene().actionManager !== this) {
  48699. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48700. return null;
  48701. }
  48702. }
  48703. this.actions.push(action);
  48704. if (ActionManager.Triggers[action.trigger]) {
  48705. ActionManager.Triggers[action.trigger]++;
  48706. }
  48707. else {
  48708. ActionManager.Triggers[action.trigger] = 1;
  48709. }
  48710. action._actionManager = this;
  48711. action._prepare();
  48712. return action;
  48713. };
  48714. /**
  48715. * Unregisters an action to this action manager
  48716. * @param action The action to be unregistered
  48717. * @return whether the action has been unregistered
  48718. */
  48719. ActionManager.prototype.unregisterAction = function (action) {
  48720. var index = this.actions.indexOf(action);
  48721. if (index !== -1) {
  48722. this.actions.splice(index, 1);
  48723. ActionManager.Triggers[action.trigger] -= 1;
  48724. if (ActionManager.Triggers[action.trigger] === 0) {
  48725. delete ActionManager.Triggers[action.trigger];
  48726. }
  48727. delete action._actionManager;
  48728. return true;
  48729. }
  48730. return false;
  48731. };
  48732. /**
  48733. * Process a specific trigger
  48734. * @param {number} trigger - the trigger to process
  48735. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48736. */
  48737. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48738. for (var index = 0; index < this.actions.length; index++) {
  48739. var action = this.actions[index];
  48740. if (action.trigger === trigger) {
  48741. if (evt) {
  48742. if (trigger === ActionManager.OnKeyUpTrigger
  48743. || trigger === ActionManager.OnKeyDownTrigger) {
  48744. var parameter = action.getTriggerParameter();
  48745. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48746. if (!parameter.toLowerCase) {
  48747. continue;
  48748. }
  48749. var lowerCase = parameter.toLowerCase();
  48750. if (lowerCase !== evt.sourceEvent.key) {
  48751. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48752. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48753. if (actualkey !== lowerCase) {
  48754. continue;
  48755. }
  48756. }
  48757. }
  48758. }
  48759. }
  48760. action._executeCurrent(evt);
  48761. }
  48762. }
  48763. };
  48764. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48765. var properties = propertyPath.split(".");
  48766. for (var index = 0; index < properties.length - 1; index++) {
  48767. target = target[properties[index]];
  48768. }
  48769. return target;
  48770. };
  48771. ActionManager.prototype._getProperty = function (propertyPath) {
  48772. var properties = propertyPath.split(".");
  48773. return properties[properties.length - 1];
  48774. };
  48775. ActionManager.prototype.serialize = function (name) {
  48776. var root = {
  48777. children: new Array(),
  48778. name: name,
  48779. type: 3,
  48780. properties: new Array() // Empty for root but required
  48781. };
  48782. for (var i = 0; i < this.actions.length; i++) {
  48783. var triggerObject = {
  48784. type: 0,
  48785. children: new Array(),
  48786. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48787. properties: new Array()
  48788. };
  48789. var triggerOptions = this.actions[i].triggerOptions;
  48790. if (triggerOptions && typeof triggerOptions !== "number") {
  48791. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48792. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48793. }
  48794. else {
  48795. var parameter = {};
  48796. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48797. if (triggerOptions.parameter.mesh) {
  48798. parameter._meshId = triggerOptions.parameter.mesh.id;
  48799. }
  48800. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48801. }
  48802. }
  48803. // Serialize child action, recursively
  48804. this.actions[i].serialize(triggerObject);
  48805. // Add serialized trigger
  48806. root.children.push(triggerObject);
  48807. }
  48808. return root;
  48809. };
  48810. ActionManager.Parse = function (parsedActions, object, scene) {
  48811. var actionManager = new ActionManager(scene);
  48812. if (object === null)
  48813. scene.actionManager = actionManager;
  48814. else
  48815. object.actionManager = actionManager;
  48816. // instanciate a new object
  48817. var instanciate = function (name, params) {
  48818. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48819. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48820. newInstance.constructor.apply(newInstance, params);
  48821. return newInstance;
  48822. };
  48823. var parseParameter = function (name, value, target, propertyPath) {
  48824. if (propertyPath === null) {
  48825. // String, boolean or float
  48826. var floatValue = parseFloat(value);
  48827. if (value === "true" || value === "false")
  48828. return value === "true";
  48829. else
  48830. return isNaN(floatValue) ? value : floatValue;
  48831. }
  48832. var effectiveTarget = propertyPath.split(".");
  48833. var values = value.split(",");
  48834. // Get effective Target
  48835. for (var i = 0; i < effectiveTarget.length; i++) {
  48836. target = target[effectiveTarget[i]];
  48837. }
  48838. // Return appropriate value with its type
  48839. if (typeof (target) === "boolean")
  48840. return values[0] === "true";
  48841. if (typeof (target) === "string")
  48842. return values[0];
  48843. // Parameters with multiple values such as Vector3 etc.
  48844. var split = new Array();
  48845. for (var i = 0; i < values.length; i++)
  48846. split.push(parseFloat(values[i]));
  48847. if (target instanceof BABYLON.Vector3)
  48848. return BABYLON.Vector3.FromArray(split);
  48849. if (target instanceof BABYLON.Vector4)
  48850. return BABYLON.Vector4.FromArray(split);
  48851. if (target instanceof BABYLON.Color3)
  48852. return BABYLON.Color3.FromArray(split);
  48853. if (target instanceof BABYLON.Color4)
  48854. return BABYLON.Color4.FromArray(split);
  48855. return parseFloat(values[0]);
  48856. };
  48857. // traverse graph per trigger
  48858. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48859. if (combineArray === void 0) { combineArray = null; }
  48860. if (parsedAction.detached)
  48861. return;
  48862. var parameters = new Array();
  48863. var target = null;
  48864. var propertyPath = null;
  48865. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48866. // Parameters
  48867. if (parsedAction.type === 2)
  48868. parameters.push(actionManager);
  48869. else
  48870. parameters.push(trigger);
  48871. if (combine) {
  48872. var actions = new Array();
  48873. for (var j = 0; j < parsedAction.combine.length; j++) {
  48874. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48875. }
  48876. parameters.push(actions);
  48877. }
  48878. else {
  48879. for (var i = 0; i < parsedAction.properties.length; i++) {
  48880. var value = parsedAction.properties[i].value;
  48881. var name = parsedAction.properties[i].name;
  48882. var targetType = parsedAction.properties[i].targetType;
  48883. if (name === "target")
  48884. if (targetType !== null && targetType === "SceneProperties")
  48885. value = target = scene;
  48886. else
  48887. value = target = scene.getNodeByName(value);
  48888. else if (name === "parent")
  48889. value = scene.getNodeByName(value);
  48890. else if (name === "sound")
  48891. value = scene.getSoundByName(value);
  48892. else if (name !== "propertyPath") {
  48893. if (parsedAction.type === 2 && name === "operator")
  48894. value = BABYLON.ValueCondition[value];
  48895. else
  48896. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48897. }
  48898. else {
  48899. propertyPath = value;
  48900. }
  48901. parameters.push(value);
  48902. }
  48903. }
  48904. if (combineArray === null) {
  48905. parameters.push(condition);
  48906. }
  48907. else {
  48908. parameters.push(null);
  48909. }
  48910. // If interpolate value action
  48911. if (parsedAction.name === "InterpolateValueAction") {
  48912. var param = parameters[parameters.length - 2];
  48913. parameters[parameters.length - 1] = param;
  48914. parameters[parameters.length - 2] = condition;
  48915. }
  48916. // Action or condition(s) and not CombineAction
  48917. var newAction = instanciate(parsedAction.name, parameters);
  48918. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48919. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48920. if (action)
  48921. action.then(nothing);
  48922. else
  48923. actionManager.registerAction(nothing);
  48924. action = nothing;
  48925. }
  48926. if (combineArray === null) {
  48927. if (newAction instanceof BABYLON.Condition) {
  48928. condition = newAction;
  48929. newAction = action;
  48930. }
  48931. else {
  48932. condition = null;
  48933. if (action)
  48934. action.then(newAction);
  48935. else
  48936. actionManager.registerAction(newAction);
  48937. }
  48938. }
  48939. else {
  48940. combineArray.push(newAction);
  48941. }
  48942. for (var i = 0; i < parsedAction.children.length; i++)
  48943. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48944. };
  48945. // triggers
  48946. for (var i = 0; i < parsedActions.children.length; i++) {
  48947. var triggerParams;
  48948. var trigger = parsedActions.children[i];
  48949. if (trigger.properties.length > 0) {
  48950. var param = trigger.properties[0].value;
  48951. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48952. if (value._meshId) {
  48953. value.mesh = scene.getMeshByID(value._meshId);
  48954. }
  48955. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48956. }
  48957. else
  48958. triggerParams = ActionManager[trigger.name];
  48959. for (var j = 0; j < trigger.children.length; j++) {
  48960. if (!trigger.detached)
  48961. traverse(trigger.children[j], triggerParams, null, null);
  48962. }
  48963. }
  48964. };
  48965. ActionManager.GetTriggerName = function (trigger) {
  48966. switch (trigger) {
  48967. case 0: return "NothingTrigger";
  48968. case 1: return "OnPickTrigger";
  48969. case 2: return "OnLeftPickTrigger";
  48970. case 3: return "OnRightPickTrigger";
  48971. case 4: return "OnCenterPickTrigger";
  48972. case 5: return "OnPickDownTrigger";
  48973. case 6: return "OnPickUpTrigger";
  48974. case 7: return "OnLongPressTrigger";
  48975. case 8: return "OnPointerOverTrigger";
  48976. case 9: return "OnPointerOutTrigger";
  48977. case 10: return "OnEveryFrameTrigger";
  48978. case 11: return "OnIntersectionEnterTrigger";
  48979. case 12: return "OnIntersectionExitTrigger";
  48980. case 13: return "OnKeyDownTrigger";
  48981. case 14: return "OnKeyUpTrigger";
  48982. case 15: return "OnPickOutTrigger";
  48983. default: return "";
  48984. }
  48985. };
  48986. // Statics
  48987. ActionManager._NothingTrigger = 0;
  48988. ActionManager._OnPickTrigger = 1;
  48989. ActionManager._OnLeftPickTrigger = 2;
  48990. ActionManager._OnRightPickTrigger = 3;
  48991. ActionManager._OnCenterPickTrigger = 4;
  48992. ActionManager._OnPickDownTrigger = 5;
  48993. ActionManager._OnDoublePickTrigger = 6;
  48994. ActionManager._OnPickUpTrigger = 7;
  48995. ActionManager._OnLongPressTrigger = 8;
  48996. ActionManager._OnPointerOverTrigger = 9;
  48997. ActionManager._OnPointerOutTrigger = 10;
  48998. ActionManager._OnEveryFrameTrigger = 11;
  48999. ActionManager._OnIntersectionEnterTrigger = 12;
  49000. ActionManager._OnIntersectionExitTrigger = 13;
  49001. ActionManager._OnKeyDownTrigger = 14;
  49002. ActionManager._OnKeyUpTrigger = 15;
  49003. ActionManager._OnPickOutTrigger = 16;
  49004. ActionManager.Triggers = {};
  49005. return ActionManager;
  49006. }());
  49007. BABYLON.ActionManager = ActionManager;
  49008. })(BABYLON || (BABYLON = {}));
  49009. //# sourceMappingURL=babylon.actionManager.js.map
  49010. var BABYLON;
  49011. (function (BABYLON) {
  49012. var InterpolateValueAction = /** @class */ (function (_super) {
  49013. __extends(InterpolateValueAction, _super);
  49014. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49015. if (duration === void 0) { duration = 1000; }
  49016. var _this = _super.call(this, triggerOptions, condition) || this;
  49017. _this.propertyPath = propertyPath;
  49018. _this.value = value;
  49019. _this.duration = duration;
  49020. _this.stopOtherAnimations = stopOtherAnimations;
  49021. _this.onInterpolationDone = onInterpolationDone;
  49022. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49023. _this._target = _this._effectiveTarget = target;
  49024. return _this;
  49025. }
  49026. InterpolateValueAction.prototype._prepare = function () {
  49027. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49028. this._property = this._getProperty(this.propertyPath);
  49029. };
  49030. InterpolateValueAction.prototype.execute = function () {
  49031. var _this = this;
  49032. var scene = this._actionManager.getScene();
  49033. var keys = [
  49034. {
  49035. frame: 0,
  49036. value: this._effectiveTarget[this._property]
  49037. }, {
  49038. frame: 100,
  49039. value: this.value
  49040. }
  49041. ];
  49042. var dataType;
  49043. if (typeof this.value === "number") {
  49044. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49045. }
  49046. else if (this.value instanceof BABYLON.Color3) {
  49047. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49048. }
  49049. else if (this.value instanceof BABYLON.Vector3) {
  49050. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49051. }
  49052. else if (this.value instanceof BABYLON.Matrix) {
  49053. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49054. }
  49055. else if (this.value instanceof BABYLON.Quaternion) {
  49056. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49057. }
  49058. else {
  49059. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49060. return;
  49061. }
  49062. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49063. animation.setKeys(keys);
  49064. if (this.stopOtherAnimations) {
  49065. scene.stopAnimation(this._effectiveTarget);
  49066. }
  49067. var wrapper = function () {
  49068. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49069. if (_this.onInterpolationDone) {
  49070. _this.onInterpolationDone();
  49071. }
  49072. };
  49073. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49074. };
  49075. InterpolateValueAction.prototype.serialize = function (parent) {
  49076. return _super.prototype._serialize.call(this, {
  49077. name: "InterpolateValueAction",
  49078. properties: [
  49079. BABYLON.Action._GetTargetProperty(this._target),
  49080. { name: "propertyPath", value: this.propertyPath },
  49081. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49082. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49083. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49084. ]
  49085. }, parent);
  49086. };
  49087. return InterpolateValueAction;
  49088. }(BABYLON.Action));
  49089. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49090. })(BABYLON || (BABYLON = {}));
  49091. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49092. var BABYLON;
  49093. (function (BABYLON) {
  49094. var SwitchBooleanAction = /** @class */ (function (_super) {
  49095. __extends(SwitchBooleanAction, _super);
  49096. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49097. var _this = _super.call(this, triggerOptions, condition) || this;
  49098. _this.propertyPath = propertyPath;
  49099. _this._target = _this._effectiveTarget = target;
  49100. return _this;
  49101. }
  49102. SwitchBooleanAction.prototype._prepare = function () {
  49103. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49104. this._property = this._getProperty(this.propertyPath);
  49105. };
  49106. SwitchBooleanAction.prototype.execute = function () {
  49107. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49108. };
  49109. SwitchBooleanAction.prototype.serialize = function (parent) {
  49110. return _super.prototype._serialize.call(this, {
  49111. name: "SwitchBooleanAction",
  49112. properties: [
  49113. BABYLON.Action._GetTargetProperty(this._target),
  49114. { name: "propertyPath", value: this.propertyPath }
  49115. ]
  49116. }, parent);
  49117. };
  49118. return SwitchBooleanAction;
  49119. }(BABYLON.Action));
  49120. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49121. var SetStateAction = /** @class */ (function (_super) {
  49122. __extends(SetStateAction, _super);
  49123. function SetStateAction(triggerOptions, target, value, condition) {
  49124. var _this = _super.call(this, triggerOptions, condition) || this;
  49125. _this.value = value;
  49126. _this._target = target;
  49127. return _this;
  49128. }
  49129. SetStateAction.prototype.execute = function () {
  49130. this._target.state = this.value;
  49131. };
  49132. SetStateAction.prototype.serialize = function (parent) {
  49133. return _super.prototype._serialize.call(this, {
  49134. name: "SetStateAction",
  49135. properties: [
  49136. BABYLON.Action._GetTargetProperty(this._target),
  49137. { name: "value", value: this.value }
  49138. ]
  49139. }, parent);
  49140. };
  49141. return SetStateAction;
  49142. }(BABYLON.Action));
  49143. BABYLON.SetStateAction = SetStateAction;
  49144. var SetValueAction = /** @class */ (function (_super) {
  49145. __extends(SetValueAction, _super);
  49146. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49147. var _this = _super.call(this, triggerOptions, condition) || this;
  49148. _this.propertyPath = propertyPath;
  49149. _this.value = value;
  49150. _this._target = _this._effectiveTarget = target;
  49151. return _this;
  49152. }
  49153. SetValueAction.prototype._prepare = function () {
  49154. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49155. this._property = this._getProperty(this.propertyPath);
  49156. };
  49157. SetValueAction.prototype.execute = function () {
  49158. this._effectiveTarget[this._property] = this.value;
  49159. if (this._target.markAsDirty) {
  49160. this._target.markAsDirty(this._property);
  49161. }
  49162. };
  49163. SetValueAction.prototype.serialize = function (parent) {
  49164. return _super.prototype._serialize.call(this, {
  49165. name: "SetValueAction",
  49166. properties: [
  49167. BABYLON.Action._GetTargetProperty(this._target),
  49168. { name: "propertyPath", value: this.propertyPath },
  49169. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49170. ]
  49171. }, parent);
  49172. };
  49173. return SetValueAction;
  49174. }(BABYLON.Action));
  49175. BABYLON.SetValueAction = SetValueAction;
  49176. var IncrementValueAction = /** @class */ (function (_super) {
  49177. __extends(IncrementValueAction, _super);
  49178. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49179. var _this = _super.call(this, triggerOptions, condition) || this;
  49180. _this.propertyPath = propertyPath;
  49181. _this.value = value;
  49182. _this._target = _this._effectiveTarget = target;
  49183. return _this;
  49184. }
  49185. IncrementValueAction.prototype._prepare = function () {
  49186. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49187. this._property = this._getProperty(this.propertyPath);
  49188. if (typeof this._effectiveTarget[this._property] !== "number") {
  49189. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49190. }
  49191. };
  49192. IncrementValueAction.prototype.execute = function () {
  49193. this._effectiveTarget[this._property] += this.value;
  49194. if (this._target.markAsDirty) {
  49195. this._target.markAsDirty(this._property);
  49196. }
  49197. };
  49198. IncrementValueAction.prototype.serialize = function (parent) {
  49199. return _super.prototype._serialize.call(this, {
  49200. name: "IncrementValueAction",
  49201. properties: [
  49202. BABYLON.Action._GetTargetProperty(this._target),
  49203. { name: "propertyPath", value: this.propertyPath },
  49204. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49205. ]
  49206. }, parent);
  49207. };
  49208. return IncrementValueAction;
  49209. }(BABYLON.Action));
  49210. BABYLON.IncrementValueAction = IncrementValueAction;
  49211. var PlayAnimationAction = /** @class */ (function (_super) {
  49212. __extends(PlayAnimationAction, _super);
  49213. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49214. var _this = _super.call(this, triggerOptions, condition) || this;
  49215. _this.from = from;
  49216. _this.to = to;
  49217. _this.loop = loop;
  49218. _this._target = target;
  49219. return _this;
  49220. }
  49221. PlayAnimationAction.prototype._prepare = function () {
  49222. };
  49223. PlayAnimationAction.prototype.execute = function () {
  49224. var scene = this._actionManager.getScene();
  49225. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49226. };
  49227. PlayAnimationAction.prototype.serialize = function (parent) {
  49228. return _super.prototype._serialize.call(this, {
  49229. name: "PlayAnimationAction",
  49230. properties: [
  49231. BABYLON.Action._GetTargetProperty(this._target),
  49232. { name: "from", value: String(this.from) },
  49233. { name: "to", value: String(this.to) },
  49234. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49235. ]
  49236. }, parent);
  49237. };
  49238. return PlayAnimationAction;
  49239. }(BABYLON.Action));
  49240. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49241. var StopAnimationAction = /** @class */ (function (_super) {
  49242. __extends(StopAnimationAction, _super);
  49243. function StopAnimationAction(triggerOptions, target, condition) {
  49244. var _this = _super.call(this, triggerOptions, condition) || this;
  49245. _this._target = target;
  49246. return _this;
  49247. }
  49248. StopAnimationAction.prototype._prepare = function () {
  49249. };
  49250. StopAnimationAction.prototype.execute = function () {
  49251. var scene = this._actionManager.getScene();
  49252. scene.stopAnimation(this._target);
  49253. };
  49254. StopAnimationAction.prototype.serialize = function (parent) {
  49255. return _super.prototype._serialize.call(this, {
  49256. name: "StopAnimationAction",
  49257. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49258. }, parent);
  49259. };
  49260. return StopAnimationAction;
  49261. }(BABYLON.Action));
  49262. BABYLON.StopAnimationAction = StopAnimationAction;
  49263. var DoNothingAction = /** @class */ (function (_super) {
  49264. __extends(DoNothingAction, _super);
  49265. function DoNothingAction(triggerOptions, condition) {
  49266. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49267. return _super.call(this, triggerOptions, condition) || this;
  49268. }
  49269. DoNothingAction.prototype.execute = function () {
  49270. };
  49271. DoNothingAction.prototype.serialize = function (parent) {
  49272. return _super.prototype._serialize.call(this, {
  49273. name: "DoNothingAction",
  49274. properties: []
  49275. }, parent);
  49276. };
  49277. return DoNothingAction;
  49278. }(BABYLON.Action));
  49279. BABYLON.DoNothingAction = DoNothingAction;
  49280. var CombineAction = /** @class */ (function (_super) {
  49281. __extends(CombineAction, _super);
  49282. function CombineAction(triggerOptions, children, condition) {
  49283. var _this = _super.call(this, triggerOptions, condition) || this;
  49284. _this.children = children;
  49285. return _this;
  49286. }
  49287. CombineAction.prototype._prepare = function () {
  49288. for (var index = 0; index < this.children.length; index++) {
  49289. this.children[index]._actionManager = this._actionManager;
  49290. this.children[index]._prepare();
  49291. }
  49292. };
  49293. CombineAction.prototype.execute = function (evt) {
  49294. for (var index = 0; index < this.children.length; index++) {
  49295. this.children[index].execute(evt);
  49296. }
  49297. };
  49298. CombineAction.prototype.serialize = function (parent) {
  49299. var serializationObject = _super.prototype._serialize.call(this, {
  49300. name: "CombineAction",
  49301. properties: [],
  49302. combine: []
  49303. }, parent);
  49304. for (var i = 0; i < this.children.length; i++) {
  49305. serializationObject.combine.push(this.children[i].serialize(null));
  49306. }
  49307. return serializationObject;
  49308. };
  49309. return CombineAction;
  49310. }(BABYLON.Action));
  49311. BABYLON.CombineAction = CombineAction;
  49312. var ExecuteCodeAction = /** @class */ (function (_super) {
  49313. __extends(ExecuteCodeAction, _super);
  49314. function ExecuteCodeAction(triggerOptions, func, condition) {
  49315. var _this = _super.call(this, triggerOptions, condition) || this;
  49316. _this.func = func;
  49317. return _this;
  49318. }
  49319. ExecuteCodeAction.prototype.execute = function (evt) {
  49320. this.func(evt);
  49321. };
  49322. return ExecuteCodeAction;
  49323. }(BABYLON.Action));
  49324. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49325. var SetParentAction = /** @class */ (function (_super) {
  49326. __extends(SetParentAction, _super);
  49327. function SetParentAction(triggerOptions, target, parent, condition) {
  49328. var _this = _super.call(this, triggerOptions, condition) || this;
  49329. _this._target = target;
  49330. _this._parent = parent;
  49331. return _this;
  49332. }
  49333. SetParentAction.prototype._prepare = function () {
  49334. };
  49335. SetParentAction.prototype.execute = function () {
  49336. if (this._target.parent === this._parent) {
  49337. return;
  49338. }
  49339. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49340. invertParentWorldMatrix.invert();
  49341. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49342. this._target.parent = this._parent;
  49343. };
  49344. SetParentAction.prototype.serialize = function (parent) {
  49345. return _super.prototype._serialize.call(this, {
  49346. name: "SetParentAction",
  49347. properties: [
  49348. BABYLON.Action._GetTargetProperty(this._target),
  49349. BABYLON.Action._GetTargetProperty(this._parent),
  49350. ]
  49351. }, parent);
  49352. };
  49353. return SetParentAction;
  49354. }(BABYLON.Action));
  49355. BABYLON.SetParentAction = SetParentAction;
  49356. var PlaySoundAction = /** @class */ (function (_super) {
  49357. __extends(PlaySoundAction, _super);
  49358. function PlaySoundAction(triggerOptions, sound, condition) {
  49359. var _this = _super.call(this, triggerOptions, condition) || this;
  49360. _this._sound = sound;
  49361. return _this;
  49362. }
  49363. PlaySoundAction.prototype._prepare = function () {
  49364. };
  49365. PlaySoundAction.prototype.execute = function () {
  49366. if (this._sound !== undefined)
  49367. this._sound.play();
  49368. };
  49369. PlaySoundAction.prototype.serialize = function (parent) {
  49370. return _super.prototype._serialize.call(this, {
  49371. name: "PlaySoundAction",
  49372. properties: [{ name: "sound", value: this._sound.name }]
  49373. }, parent);
  49374. };
  49375. return PlaySoundAction;
  49376. }(BABYLON.Action));
  49377. BABYLON.PlaySoundAction = PlaySoundAction;
  49378. var StopSoundAction = /** @class */ (function (_super) {
  49379. __extends(StopSoundAction, _super);
  49380. function StopSoundAction(triggerOptions, sound, condition) {
  49381. var _this = _super.call(this, triggerOptions, condition) || this;
  49382. _this._sound = sound;
  49383. return _this;
  49384. }
  49385. StopSoundAction.prototype._prepare = function () {
  49386. };
  49387. StopSoundAction.prototype.execute = function () {
  49388. if (this._sound !== undefined)
  49389. this._sound.stop();
  49390. };
  49391. StopSoundAction.prototype.serialize = function (parent) {
  49392. return _super.prototype._serialize.call(this, {
  49393. name: "StopSoundAction",
  49394. properties: [{ name: "sound", value: this._sound.name }]
  49395. }, parent);
  49396. };
  49397. return StopSoundAction;
  49398. }(BABYLON.Action));
  49399. BABYLON.StopSoundAction = StopSoundAction;
  49400. })(BABYLON || (BABYLON = {}));
  49401. //# sourceMappingURL=babylon.directActions.js.map
  49402. var BABYLON;
  49403. (function (BABYLON) {
  49404. var SpriteManager = /** @class */ (function () {
  49405. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49406. if (epsilon === void 0) { epsilon = 0.01; }
  49407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49408. this.name = name;
  49409. this.sprites = new Array();
  49410. this.renderingGroupId = 0;
  49411. this.layerMask = 0x0FFFFFFF;
  49412. this.fogEnabled = true;
  49413. this.isPickable = false;
  49414. /**
  49415. * An event triggered when the manager is disposed.
  49416. * @type {BABYLON.Observable}
  49417. */
  49418. this.onDisposeObservable = new BABYLON.Observable();
  49419. this._vertexBuffers = {};
  49420. this._capacity = capacity;
  49421. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49422. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49423. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49424. if (cellSize.width && cellSize.height) {
  49425. this.cellWidth = cellSize.width;
  49426. this.cellHeight = cellSize.height;
  49427. }
  49428. else if (cellSize !== undefined) {
  49429. this.cellWidth = cellSize;
  49430. this.cellHeight = cellSize;
  49431. }
  49432. else {
  49433. return;
  49434. }
  49435. this._epsilon = epsilon;
  49436. this._scene = scene;
  49437. this._scene.spriteManagers.push(this);
  49438. var indices = [];
  49439. var index = 0;
  49440. for (var count = 0; count < capacity; count++) {
  49441. indices.push(index);
  49442. indices.push(index + 1);
  49443. indices.push(index + 2);
  49444. indices.push(index);
  49445. indices.push(index + 2);
  49446. indices.push(index + 3);
  49447. index += 4;
  49448. }
  49449. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49450. // VBO
  49451. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49452. this._vertexData = new Float32Array(capacity * 16 * 4);
  49453. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49454. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49455. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49456. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49457. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49458. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49459. this._vertexBuffers["options"] = options;
  49460. this._vertexBuffers["cellInfo"] = cellInfo;
  49461. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49462. // Effects
  49463. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49464. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49465. }
  49466. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49467. set: function (callback) {
  49468. if (this._onDisposeObserver) {
  49469. this.onDisposeObservable.remove(this._onDisposeObserver);
  49470. }
  49471. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49472. },
  49473. enumerable: true,
  49474. configurable: true
  49475. });
  49476. Object.defineProperty(SpriteManager.prototype, "texture", {
  49477. get: function () {
  49478. return this._spriteTexture;
  49479. },
  49480. set: function (value) {
  49481. this._spriteTexture = value;
  49482. },
  49483. enumerable: true,
  49484. configurable: true
  49485. });
  49486. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49487. var arrayOffset = index * 16;
  49488. if (offsetX === 0)
  49489. offsetX = this._epsilon;
  49490. else if (offsetX === 1)
  49491. offsetX = 1 - this._epsilon;
  49492. if (offsetY === 0)
  49493. offsetY = this._epsilon;
  49494. else if (offsetY === 1)
  49495. offsetY = 1 - this._epsilon;
  49496. this._vertexData[arrayOffset] = sprite.position.x;
  49497. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49498. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49499. this._vertexData[arrayOffset + 3] = sprite.angle;
  49500. this._vertexData[arrayOffset + 4] = sprite.width;
  49501. this._vertexData[arrayOffset + 5] = sprite.height;
  49502. this._vertexData[arrayOffset + 6] = offsetX;
  49503. this._vertexData[arrayOffset + 7] = offsetY;
  49504. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49505. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49506. var offset = (sprite.cellIndex / rowSize) >> 0;
  49507. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49508. this._vertexData[arrayOffset + 11] = offset;
  49509. // Color
  49510. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49511. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49512. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49513. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49514. };
  49515. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49516. var count = Math.min(this._capacity, this.sprites.length);
  49517. var min = BABYLON.Vector3.Zero();
  49518. var max = BABYLON.Vector3.Zero();
  49519. var distance = Number.MAX_VALUE;
  49520. var currentSprite = null;
  49521. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49522. var cameraView = camera.getViewMatrix();
  49523. for (var index = 0; index < count; index++) {
  49524. var sprite = this.sprites[index];
  49525. if (!sprite) {
  49526. continue;
  49527. }
  49528. if (predicate) {
  49529. if (!predicate(sprite)) {
  49530. continue;
  49531. }
  49532. }
  49533. else if (!sprite.isPickable) {
  49534. continue;
  49535. }
  49536. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49537. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49538. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49539. if (ray.intersectsBoxMinMax(min, max)) {
  49540. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49541. if (distance > currentDistance) {
  49542. distance = currentDistance;
  49543. currentSprite = sprite;
  49544. if (fastCheck) {
  49545. break;
  49546. }
  49547. }
  49548. }
  49549. }
  49550. if (currentSprite) {
  49551. var result = new BABYLON.PickingInfo();
  49552. result.hit = true;
  49553. result.pickedSprite = currentSprite;
  49554. result.distance = distance;
  49555. return result;
  49556. }
  49557. return null;
  49558. };
  49559. SpriteManager.prototype.render = function () {
  49560. // Check
  49561. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49562. return;
  49563. var engine = this._scene.getEngine();
  49564. var baseSize = this._spriteTexture.getBaseSize();
  49565. // Sprites
  49566. var deltaTime = engine.getDeltaTime();
  49567. var max = Math.min(this._capacity, this.sprites.length);
  49568. var rowSize = baseSize.width / this.cellWidth;
  49569. var offset = 0;
  49570. for (var index = 0; index < max; index++) {
  49571. var sprite = this.sprites[index];
  49572. if (!sprite) {
  49573. continue;
  49574. }
  49575. sprite._animate(deltaTime);
  49576. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49577. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49578. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49579. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49580. }
  49581. this._buffer.update(this._vertexData);
  49582. // Render
  49583. var effect = this._effectBase;
  49584. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49585. effect = this._effectFog;
  49586. }
  49587. engine.enableEffect(effect);
  49588. var viewMatrix = this._scene.getViewMatrix();
  49589. effect.setTexture("diffuseSampler", this._spriteTexture);
  49590. effect.setMatrix("view", viewMatrix);
  49591. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49592. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49593. // Fog
  49594. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49595. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49596. effect.setColor3("vFogColor", this._scene.fogColor);
  49597. }
  49598. // VBOs
  49599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49600. // Draw order
  49601. engine.setDepthFunctionToLessOrEqual();
  49602. effect.setBool("alphaTest", true);
  49603. engine.setColorWrite(false);
  49604. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49605. engine.setColorWrite(true);
  49606. effect.setBool("alphaTest", false);
  49607. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49608. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49609. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49610. };
  49611. SpriteManager.prototype.dispose = function () {
  49612. if (this._buffer) {
  49613. this._buffer.dispose();
  49614. this._buffer = null;
  49615. }
  49616. if (this._indexBuffer) {
  49617. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49618. this._indexBuffer = null;
  49619. }
  49620. if (this._spriteTexture) {
  49621. this._spriteTexture.dispose();
  49622. this._spriteTexture = null;
  49623. }
  49624. // Remove from scene
  49625. var index = this._scene.spriteManagers.indexOf(this);
  49626. this._scene.spriteManagers.splice(index, 1);
  49627. // Callback
  49628. this.onDisposeObservable.notifyObservers(this);
  49629. this.onDisposeObservable.clear();
  49630. };
  49631. return SpriteManager;
  49632. }());
  49633. BABYLON.SpriteManager = SpriteManager;
  49634. })(BABYLON || (BABYLON = {}));
  49635. //# sourceMappingURL=babylon.spriteManager.js.map
  49636. var BABYLON;
  49637. (function (BABYLON) {
  49638. var Sprite = /** @class */ (function () {
  49639. function Sprite(name, manager) {
  49640. this.name = name;
  49641. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49642. this.width = 1.0;
  49643. this.height = 1.0;
  49644. this.angle = 0;
  49645. this.cellIndex = 0;
  49646. this.invertU = 0;
  49647. this.invertV = 0;
  49648. this.animations = new Array();
  49649. this.isPickable = false;
  49650. this._animationStarted = false;
  49651. this._loopAnimation = false;
  49652. this._fromIndex = 0;
  49653. this._toIndex = 0;
  49654. this._delay = 0;
  49655. this._direction = 1;
  49656. this._time = 0;
  49657. this._manager = manager;
  49658. this._manager.sprites.push(this);
  49659. this.position = BABYLON.Vector3.Zero();
  49660. }
  49661. Object.defineProperty(Sprite.prototype, "size", {
  49662. get: function () {
  49663. return this.width;
  49664. },
  49665. set: function (value) {
  49666. this.width = value;
  49667. this.height = value;
  49668. },
  49669. enumerable: true,
  49670. configurable: true
  49671. });
  49672. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49673. this._fromIndex = from;
  49674. this._toIndex = to;
  49675. this._loopAnimation = loop;
  49676. this._delay = delay;
  49677. this._animationStarted = true;
  49678. this._direction = from < to ? 1 : -1;
  49679. this.cellIndex = from;
  49680. this._time = 0;
  49681. this._onAnimationEnd = onAnimationEnd;
  49682. };
  49683. Sprite.prototype.stopAnimation = function () {
  49684. this._animationStarted = false;
  49685. };
  49686. Sprite.prototype._animate = function (deltaTime) {
  49687. if (!this._animationStarted)
  49688. return;
  49689. this._time += deltaTime;
  49690. if (this._time > this._delay) {
  49691. this._time = this._time % this._delay;
  49692. this.cellIndex += this._direction;
  49693. if (this.cellIndex > this._toIndex) {
  49694. if (this._loopAnimation) {
  49695. this.cellIndex = this._fromIndex;
  49696. }
  49697. else {
  49698. this.cellIndex = this._toIndex;
  49699. this._animationStarted = false;
  49700. if (this._onAnimationEnd) {
  49701. this._onAnimationEnd();
  49702. }
  49703. if (this.disposeWhenFinishedAnimating) {
  49704. this.dispose();
  49705. }
  49706. }
  49707. }
  49708. }
  49709. };
  49710. Sprite.prototype.dispose = function () {
  49711. for (var i = 0; i < this._manager.sprites.length; i++) {
  49712. if (this._manager.sprites[i] == this) {
  49713. this._manager.sprites.splice(i, 1);
  49714. }
  49715. }
  49716. };
  49717. return Sprite;
  49718. }());
  49719. BABYLON.Sprite = Sprite;
  49720. })(BABYLON || (BABYLON = {}));
  49721. //# sourceMappingURL=babylon.sprite.js.map
  49722. var BABYLON;
  49723. (function (BABYLON) {
  49724. var IntersectionInfo = /** @class */ (function () {
  49725. function IntersectionInfo(bu, bv, distance) {
  49726. this.bu = bu;
  49727. this.bv = bv;
  49728. this.distance = distance;
  49729. this.faceId = 0;
  49730. this.subMeshId = 0;
  49731. }
  49732. return IntersectionInfo;
  49733. }());
  49734. BABYLON.IntersectionInfo = IntersectionInfo;
  49735. var PickingInfo = /** @class */ (function () {
  49736. function PickingInfo() {
  49737. this.hit = false;
  49738. this.distance = 0;
  49739. this.pickedPoint = null;
  49740. this.pickedMesh = null;
  49741. this.bu = 0;
  49742. this.bv = 0;
  49743. this.faceId = -1;
  49744. this.subMeshId = 0;
  49745. this.pickedSprite = null;
  49746. }
  49747. // Methods
  49748. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49749. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49750. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49751. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49752. return null;
  49753. }
  49754. var indices = this.pickedMesh.getIndices();
  49755. if (!indices) {
  49756. return null;
  49757. }
  49758. var result;
  49759. if (useVerticesNormals) {
  49760. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49761. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49762. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49763. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49764. normal0 = normal0.scale(this.bu);
  49765. normal1 = normal1.scale(this.bv);
  49766. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49767. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49768. }
  49769. else {
  49770. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49771. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49772. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49773. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49774. var p1p2 = vertex1.subtract(vertex2);
  49775. var p3p2 = vertex3.subtract(vertex2);
  49776. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49777. }
  49778. if (useWorldCoordinates) {
  49779. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49780. }
  49781. return BABYLON.Vector3.Normalize(result);
  49782. };
  49783. PickingInfo.prototype.getTextureCoordinates = function () {
  49784. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49785. return null;
  49786. }
  49787. var indices = this.pickedMesh.getIndices();
  49788. if (!indices) {
  49789. return null;
  49790. }
  49791. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49792. if (!uvs) {
  49793. return null;
  49794. }
  49795. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49796. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49797. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49798. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49799. uv1 = uv1.scale(this.bu);
  49800. uv2 = uv2.scale(this.bv);
  49801. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49802. };
  49803. return PickingInfo;
  49804. }());
  49805. BABYLON.PickingInfo = PickingInfo;
  49806. })(BABYLON || (BABYLON = {}));
  49807. //# sourceMappingURL=babylon.pickingInfo.js.map
  49808. var BABYLON;
  49809. (function (BABYLON) {
  49810. var Ray = /** @class */ (function () {
  49811. function Ray(origin, direction, length) {
  49812. if (length === void 0) { length = Number.MAX_VALUE; }
  49813. this.origin = origin;
  49814. this.direction = direction;
  49815. this.length = length;
  49816. }
  49817. // Methods
  49818. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49819. var d = 0.0;
  49820. var maxValue = Number.MAX_VALUE;
  49821. var inv;
  49822. var min;
  49823. var max;
  49824. var temp;
  49825. if (Math.abs(this.direction.x) < 0.0000001) {
  49826. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49827. return false;
  49828. }
  49829. }
  49830. else {
  49831. inv = 1.0 / this.direction.x;
  49832. min = (minimum.x - this.origin.x) * inv;
  49833. max = (maximum.x - this.origin.x) * inv;
  49834. if (max === -Infinity) {
  49835. max = Infinity;
  49836. }
  49837. if (min > max) {
  49838. temp = min;
  49839. min = max;
  49840. max = temp;
  49841. }
  49842. d = Math.max(min, d);
  49843. maxValue = Math.min(max, maxValue);
  49844. if (d > maxValue) {
  49845. return false;
  49846. }
  49847. }
  49848. if (Math.abs(this.direction.y) < 0.0000001) {
  49849. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49850. return false;
  49851. }
  49852. }
  49853. else {
  49854. inv = 1.0 / this.direction.y;
  49855. min = (minimum.y - this.origin.y) * inv;
  49856. max = (maximum.y - this.origin.y) * inv;
  49857. if (max === -Infinity) {
  49858. max = Infinity;
  49859. }
  49860. if (min > max) {
  49861. temp = min;
  49862. min = max;
  49863. max = temp;
  49864. }
  49865. d = Math.max(min, d);
  49866. maxValue = Math.min(max, maxValue);
  49867. if (d > maxValue) {
  49868. return false;
  49869. }
  49870. }
  49871. if (Math.abs(this.direction.z) < 0.0000001) {
  49872. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49873. return false;
  49874. }
  49875. }
  49876. else {
  49877. inv = 1.0 / this.direction.z;
  49878. min = (minimum.z - this.origin.z) * inv;
  49879. max = (maximum.z - this.origin.z) * inv;
  49880. if (max === -Infinity) {
  49881. max = Infinity;
  49882. }
  49883. if (min > max) {
  49884. temp = min;
  49885. min = max;
  49886. max = temp;
  49887. }
  49888. d = Math.max(min, d);
  49889. maxValue = Math.min(max, maxValue);
  49890. if (d > maxValue) {
  49891. return false;
  49892. }
  49893. }
  49894. return true;
  49895. };
  49896. Ray.prototype.intersectsBox = function (box) {
  49897. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49898. };
  49899. Ray.prototype.intersectsSphere = function (sphere) {
  49900. var x = sphere.center.x - this.origin.x;
  49901. var y = sphere.center.y - this.origin.y;
  49902. var z = sphere.center.z - this.origin.z;
  49903. var pyth = (x * x) + (y * y) + (z * z);
  49904. var rr = sphere.radius * sphere.radius;
  49905. if (pyth <= rr) {
  49906. return true;
  49907. }
  49908. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49909. if (dot < 0.0) {
  49910. return false;
  49911. }
  49912. var temp = pyth - (dot * dot);
  49913. return temp <= rr;
  49914. };
  49915. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49916. if (!this._edge1) {
  49917. this._edge1 = BABYLON.Vector3.Zero();
  49918. this._edge2 = BABYLON.Vector3.Zero();
  49919. this._pvec = BABYLON.Vector3.Zero();
  49920. this._tvec = BABYLON.Vector3.Zero();
  49921. this._qvec = BABYLON.Vector3.Zero();
  49922. }
  49923. vertex1.subtractToRef(vertex0, this._edge1);
  49924. vertex2.subtractToRef(vertex0, this._edge2);
  49925. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49926. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49927. if (det === 0) {
  49928. return null;
  49929. }
  49930. var invdet = 1 / det;
  49931. this.origin.subtractToRef(vertex0, this._tvec);
  49932. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49933. if (bu < 0 || bu > 1.0) {
  49934. return null;
  49935. }
  49936. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49937. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49938. if (bv < 0 || bu + bv > 1.0) {
  49939. return null;
  49940. }
  49941. //check if the distance is longer than the predefined length.
  49942. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49943. if (distance > this.length) {
  49944. return null;
  49945. }
  49946. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49947. };
  49948. Ray.prototype.intersectsPlane = function (plane) {
  49949. var distance;
  49950. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49951. if (Math.abs(result1) < 9.99999997475243E-07) {
  49952. return null;
  49953. }
  49954. else {
  49955. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49956. distance = (-plane.d - result2) / result1;
  49957. if (distance < 0.0) {
  49958. if (distance < -9.99999997475243E-07) {
  49959. return null;
  49960. }
  49961. else {
  49962. return 0;
  49963. }
  49964. }
  49965. return distance;
  49966. }
  49967. };
  49968. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49969. var tm = BABYLON.Tmp.Matrix[0];
  49970. mesh.getWorldMatrix().invertToRef(tm);
  49971. if (this._tmpRay) {
  49972. Ray.TransformToRef(this, tm, this._tmpRay);
  49973. }
  49974. else {
  49975. this._tmpRay = Ray.Transform(this, tm);
  49976. }
  49977. return mesh.intersects(this._tmpRay, fastCheck);
  49978. };
  49979. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49980. if (results) {
  49981. results.length = 0;
  49982. }
  49983. else {
  49984. results = [];
  49985. }
  49986. for (var i = 0; i < meshes.length; i++) {
  49987. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49988. if (pickInfo.hit) {
  49989. results.push(pickInfo);
  49990. }
  49991. }
  49992. results.sort(this._comparePickingInfo);
  49993. return results;
  49994. };
  49995. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49996. if (pickingInfoA.distance < pickingInfoB.distance) {
  49997. return -1;
  49998. }
  49999. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50000. return 1;
  50001. }
  50002. else {
  50003. return 0;
  50004. }
  50005. };
  50006. /**
  50007. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50008. * @param sega the first point of the segment to test the intersection against
  50009. * @param segb the second point of the segment to test the intersection against
  50010. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50011. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50012. */
  50013. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50014. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50015. var u = segb.subtract(sega);
  50016. var v = rsegb.subtract(this.origin);
  50017. var w = sega.subtract(this.origin);
  50018. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50019. var b = BABYLON.Vector3.Dot(u, v);
  50020. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50021. var d = BABYLON.Vector3.Dot(u, w);
  50022. var e = BABYLON.Vector3.Dot(v, w);
  50023. var D = a * c - b * b; // always >= 0
  50024. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50025. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50026. // compute the line parameters of the two closest points
  50027. if (D < Ray.smallnum) {
  50028. sN = 0.0; // force using point P0 on segment S1
  50029. sD = 1.0; // to prevent possible division by 0.0 later
  50030. tN = e;
  50031. tD = c;
  50032. }
  50033. else {
  50034. sN = (b * e - c * d);
  50035. tN = (a * e - b * d);
  50036. if (sN < 0.0) {
  50037. sN = 0.0;
  50038. tN = e;
  50039. tD = c;
  50040. }
  50041. else if (sN > sD) {
  50042. sN = sD;
  50043. tN = e + b;
  50044. tD = c;
  50045. }
  50046. }
  50047. if (tN < 0.0) {
  50048. tN = 0.0;
  50049. // recompute sc for this edge
  50050. if (-d < 0.0) {
  50051. sN = 0.0;
  50052. }
  50053. else if (-d > a)
  50054. sN = sD;
  50055. else {
  50056. sN = -d;
  50057. sD = a;
  50058. }
  50059. }
  50060. else if (tN > tD) {
  50061. tN = tD;
  50062. // recompute sc for this edge
  50063. if ((-d + b) < 0.0) {
  50064. sN = 0;
  50065. }
  50066. else if ((-d + b) > a) {
  50067. sN = sD;
  50068. }
  50069. else {
  50070. sN = (-d + b);
  50071. sD = a;
  50072. }
  50073. }
  50074. // finally do the division to get sc and tc
  50075. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50076. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50077. // get the difference of the two closest points
  50078. var qtc = v.multiplyByFloats(tc, tc, tc);
  50079. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50080. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50081. if (isIntersected) {
  50082. return qtc.length();
  50083. }
  50084. return -1;
  50085. };
  50086. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50087. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50088. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50089. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50090. this.direction.normalize();
  50091. return this;
  50092. };
  50093. // Statics
  50094. Ray.Zero = function () {
  50095. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50096. };
  50097. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50098. var result = Ray.Zero();
  50099. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50100. };
  50101. /**
  50102. * 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
  50103. * transformed to the given world matrix.
  50104. * @param origin The origin point
  50105. * @param end The end point
  50106. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50107. */
  50108. Ray.CreateNewFromTo = function (origin, end, world) {
  50109. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50110. var direction = end.subtract(origin);
  50111. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50112. direction.normalize();
  50113. return Ray.Transform(new Ray(origin, direction, length), world);
  50114. };
  50115. Ray.Transform = function (ray, matrix) {
  50116. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50117. Ray.TransformToRef(ray, matrix, result);
  50118. return result;
  50119. };
  50120. Ray.TransformToRef = function (ray, matrix, result) {
  50121. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50122. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50123. result.length = ray.length;
  50124. var dir = result.direction;
  50125. var len = dir.length();
  50126. if (!(len === 0 || len === 1)) {
  50127. var num = 1.0 / len;
  50128. dir.x *= num;
  50129. dir.y *= num;
  50130. dir.z *= num;
  50131. result.length *= len;
  50132. }
  50133. };
  50134. Ray.smallnum = 0.00000001;
  50135. Ray.rayl = 10e8;
  50136. return Ray;
  50137. }());
  50138. BABYLON.Ray = Ray;
  50139. })(BABYLON || (BABYLON = {}));
  50140. //# sourceMappingURL=babylon.ray.js.map
  50141. var BABYLON;
  50142. (function (BABYLON) {
  50143. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50144. if (boxMin.x > sphereCenter.x + sphereRadius)
  50145. return false;
  50146. if (sphereCenter.x - sphereRadius > boxMax.x)
  50147. return false;
  50148. if (boxMin.y > sphereCenter.y + sphereRadius)
  50149. return false;
  50150. if (sphereCenter.y - sphereRadius > boxMax.y)
  50151. return false;
  50152. if (boxMin.z > sphereCenter.z + sphereRadius)
  50153. return false;
  50154. if (sphereCenter.z - sphereRadius > boxMax.z)
  50155. return false;
  50156. return true;
  50157. };
  50158. var getLowestRoot = (function () {
  50159. var result = { root: 0, found: false };
  50160. return function (a, b, c, maxR) {
  50161. result.root = 0;
  50162. result.found = false;
  50163. var determinant = b * b - 4.0 * a * c;
  50164. if (determinant < 0)
  50165. return result;
  50166. var sqrtD = Math.sqrt(determinant);
  50167. var r1 = (-b - sqrtD) / (2.0 * a);
  50168. var r2 = (-b + sqrtD) / (2.0 * a);
  50169. if (r1 > r2) {
  50170. var temp = r2;
  50171. r2 = r1;
  50172. r1 = temp;
  50173. }
  50174. if (r1 > 0 && r1 < maxR) {
  50175. result.root = r1;
  50176. result.found = true;
  50177. return result;
  50178. }
  50179. if (r2 > 0 && r2 < maxR) {
  50180. result.root = r2;
  50181. result.found = true;
  50182. return result;
  50183. }
  50184. return result;
  50185. };
  50186. })();
  50187. var Collider = /** @class */ (function () {
  50188. function Collider() {
  50189. this._collisionPoint = BABYLON.Vector3.Zero();
  50190. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50191. this._tempVector = BABYLON.Vector3.Zero();
  50192. this._tempVector2 = BABYLON.Vector3.Zero();
  50193. this._tempVector3 = BABYLON.Vector3.Zero();
  50194. this._tempVector4 = BABYLON.Vector3.Zero();
  50195. this._edge = BABYLON.Vector3.Zero();
  50196. this._baseToVertex = BABYLON.Vector3.Zero();
  50197. this._destinationPoint = BABYLON.Vector3.Zero();
  50198. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50199. this._displacementVector = BABYLON.Vector3.Zero();
  50200. this._radius = BABYLON.Vector3.One();
  50201. this._retry = 0;
  50202. this._basePointWorld = BABYLON.Vector3.Zero();
  50203. this._velocityWorld = BABYLON.Vector3.Zero();
  50204. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50205. this._collisionMask = -1;
  50206. }
  50207. Object.defineProperty(Collider.prototype, "collisionMask", {
  50208. get: function () {
  50209. return this._collisionMask;
  50210. },
  50211. set: function (mask) {
  50212. this._collisionMask = !isNaN(mask) ? mask : -1;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50218. /**
  50219. * Gets the plane normal used to compute the sliding response (in local space)
  50220. */
  50221. get: function () {
  50222. return this._slidePlaneNormal;
  50223. },
  50224. enumerable: true,
  50225. configurable: true
  50226. });
  50227. // Methods
  50228. Collider.prototype._initialize = function (source, dir, e) {
  50229. this._velocity = dir;
  50230. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50231. this._basePoint = source;
  50232. source.multiplyToRef(this._radius, this._basePointWorld);
  50233. dir.multiplyToRef(this._radius, this._velocityWorld);
  50234. this._velocityWorldLength = this._velocityWorld.length();
  50235. this._epsilon = e;
  50236. this.collisionFound = false;
  50237. };
  50238. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50239. pa.subtractToRef(point, this._tempVector);
  50240. pb.subtractToRef(point, this._tempVector2);
  50241. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50242. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50243. if (d < 0)
  50244. return false;
  50245. pc.subtractToRef(point, this._tempVector3);
  50246. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50247. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50248. if (d < 0)
  50249. return false;
  50250. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50251. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50252. return d >= 0;
  50253. };
  50254. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50255. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50256. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50257. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50258. return false;
  50259. }
  50260. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50261. return false;
  50262. return true;
  50263. };
  50264. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50265. var t0;
  50266. var embeddedInPlane = false;
  50267. //defensive programming, actually not needed.
  50268. if (!trianglePlaneArray) {
  50269. trianglePlaneArray = [];
  50270. }
  50271. if (!trianglePlaneArray[faceIndex]) {
  50272. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50273. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50274. }
  50275. var trianglePlane = trianglePlaneArray[faceIndex];
  50276. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50277. return;
  50278. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50279. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50280. if (normalDotVelocity == 0) {
  50281. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50282. return;
  50283. embeddedInPlane = true;
  50284. t0 = 0;
  50285. }
  50286. else {
  50287. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50288. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50289. if (t0 > t1) {
  50290. var temp = t1;
  50291. t1 = t0;
  50292. t0 = temp;
  50293. }
  50294. if (t0 > 1.0 || t1 < 0.0)
  50295. return;
  50296. if (t0 < 0)
  50297. t0 = 0;
  50298. if (t0 > 1.0)
  50299. t0 = 1.0;
  50300. }
  50301. this._collisionPoint.copyFromFloats(0, 0, 0);
  50302. var found = false;
  50303. var t = 1.0;
  50304. if (!embeddedInPlane) {
  50305. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50306. this._velocity.scaleToRef(t0, this._tempVector);
  50307. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50308. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50309. found = true;
  50310. t = t0;
  50311. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50312. }
  50313. }
  50314. if (!found) {
  50315. var velocitySquaredLength = this._velocity.lengthSquared();
  50316. var a = velocitySquaredLength;
  50317. this._basePoint.subtractToRef(p1, this._tempVector);
  50318. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50319. var c = this._tempVector.lengthSquared() - 1.0;
  50320. var lowestRoot = getLowestRoot(a, b, c, t);
  50321. if (lowestRoot.found) {
  50322. t = lowestRoot.root;
  50323. found = true;
  50324. this._collisionPoint.copyFrom(p1);
  50325. }
  50326. this._basePoint.subtractToRef(p2, this._tempVector);
  50327. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50328. c = this._tempVector.lengthSquared() - 1.0;
  50329. lowestRoot = getLowestRoot(a, b, c, t);
  50330. if (lowestRoot.found) {
  50331. t = lowestRoot.root;
  50332. found = true;
  50333. this._collisionPoint.copyFrom(p2);
  50334. }
  50335. this._basePoint.subtractToRef(p3, this._tempVector);
  50336. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50337. c = this._tempVector.lengthSquared() - 1.0;
  50338. lowestRoot = getLowestRoot(a, b, c, t);
  50339. if (lowestRoot.found) {
  50340. t = lowestRoot.root;
  50341. found = true;
  50342. this._collisionPoint.copyFrom(p3);
  50343. }
  50344. p2.subtractToRef(p1, this._edge);
  50345. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50346. var edgeSquaredLength = this._edge.lengthSquared();
  50347. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50348. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50349. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50350. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50351. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50352. lowestRoot = getLowestRoot(a, b, c, t);
  50353. if (lowestRoot.found) {
  50354. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50355. if (f >= 0.0 && f <= 1.0) {
  50356. t = lowestRoot.root;
  50357. found = true;
  50358. this._edge.scaleInPlace(f);
  50359. p1.addToRef(this._edge, this._collisionPoint);
  50360. }
  50361. }
  50362. p3.subtractToRef(p2, this._edge);
  50363. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50364. edgeSquaredLength = this._edge.lengthSquared();
  50365. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50366. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50367. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50368. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50369. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50370. lowestRoot = getLowestRoot(a, b, c, t);
  50371. if (lowestRoot.found) {
  50372. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50373. if (f >= 0.0 && f <= 1.0) {
  50374. t = lowestRoot.root;
  50375. found = true;
  50376. this._edge.scaleInPlace(f);
  50377. p2.addToRef(this._edge, this._collisionPoint);
  50378. }
  50379. }
  50380. p1.subtractToRef(p3, this._edge);
  50381. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50382. edgeSquaredLength = this._edge.lengthSquared();
  50383. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50384. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50385. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50386. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50387. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50388. lowestRoot = getLowestRoot(a, b, c, t);
  50389. if (lowestRoot.found) {
  50390. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50391. if (f >= 0.0 && f <= 1.0) {
  50392. t = lowestRoot.root;
  50393. found = true;
  50394. this._edge.scaleInPlace(f);
  50395. p3.addToRef(this._edge, this._collisionPoint);
  50396. }
  50397. }
  50398. }
  50399. if (found) {
  50400. var distToCollision = t * this._velocity.length();
  50401. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50402. if (!this.intersectionPoint) {
  50403. this.intersectionPoint = this._collisionPoint.clone();
  50404. }
  50405. else {
  50406. this.intersectionPoint.copyFrom(this._collisionPoint);
  50407. }
  50408. this._nearestDistance = distToCollision;
  50409. this.collisionFound = true;
  50410. }
  50411. }
  50412. };
  50413. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50414. for (var i = indexStart; i < indexEnd; i += 3) {
  50415. var p1 = pts[indices[i] - decal];
  50416. var p2 = pts[indices[i + 1] - decal];
  50417. var p3 = pts[indices[i + 2] - decal];
  50418. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50419. }
  50420. };
  50421. Collider.prototype._getResponse = function (pos, vel) {
  50422. pos.addToRef(vel, this._destinationPoint);
  50423. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50424. this._basePoint.addToRef(vel, pos);
  50425. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50426. this._slidePlaneNormal.normalize();
  50427. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50428. pos.addInPlace(this._displacementVector);
  50429. this.intersectionPoint.addInPlace(this._displacementVector);
  50430. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50431. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50432. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50433. };
  50434. return Collider;
  50435. }());
  50436. BABYLON.Collider = Collider;
  50437. })(BABYLON || (BABYLON = {}));
  50438. //# sourceMappingURL=babylon.collider.js.map
  50439. var BABYLON;
  50440. (function (BABYLON) {
  50441. //WebWorker code will be inserted to this variable.
  50442. BABYLON.CollisionWorker = "";
  50443. var WorkerTaskType;
  50444. (function (WorkerTaskType) {
  50445. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50446. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50447. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50448. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50449. var WorkerReplyType;
  50450. (function (WorkerReplyType) {
  50451. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50452. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50453. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50454. var CollisionCoordinatorWorker = /** @class */ (function () {
  50455. function CollisionCoordinatorWorker() {
  50456. var _this = this;
  50457. this._scaledPosition = BABYLON.Vector3.Zero();
  50458. this._scaledVelocity = BABYLON.Vector3.Zero();
  50459. this.onMeshUpdated = function (transformNode) {
  50460. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50461. };
  50462. this.onGeometryUpdated = function (geometry) {
  50463. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50464. };
  50465. this._afterRender = function () {
  50466. if (!_this._init)
  50467. return;
  50468. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50469. return;
  50470. }
  50471. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50472. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50473. if (_this._runningUpdated > 4) {
  50474. return;
  50475. }
  50476. ++_this._runningUpdated;
  50477. var payload = {
  50478. updatedMeshes: _this._addUpdateMeshesList,
  50479. updatedGeometries: _this._addUpdateGeometriesList,
  50480. removedGeometries: _this._toRemoveGeometryArray,
  50481. removedMeshes: _this._toRemoveMeshesArray
  50482. };
  50483. var message = {
  50484. payload: payload,
  50485. taskType: WorkerTaskType.UPDATE
  50486. };
  50487. var serializable = [];
  50488. for (var id in payload.updatedGeometries) {
  50489. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50490. //prepare transferables
  50491. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50492. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50493. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50494. }
  50495. }
  50496. _this._worker.postMessage(message, serializable);
  50497. _this._addUpdateMeshesList = {};
  50498. _this._addUpdateGeometriesList = {};
  50499. _this._toRemoveGeometryArray = [];
  50500. _this._toRemoveMeshesArray = [];
  50501. };
  50502. this._onMessageFromWorker = function (e) {
  50503. var returnData = e.data;
  50504. if (returnData.error != WorkerReplyType.SUCCESS) {
  50505. //TODO what errors can be returned from the worker?
  50506. BABYLON.Tools.Warn("error returned from worker!");
  50507. return;
  50508. }
  50509. switch (returnData.taskType) {
  50510. case WorkerTaskType.INIT:
  50511. _this._init = true;
  50512. //Update the worked with ALL of the scene's current state
  50513. _this._scene.meshes.forEach(function (mesh) {
  50514. _this.onMeshAdded(mesh);
  50515. });
  50516. _this._scene.getGeometries().forEach(function (geometry) {
  50517. _this.onGeometryAdded(geometry);
  50518. });
  50519. break;
  50520. case WorkerTaskType.UPDATE:
  50521. _this._runningUpdated--;
  50522. break;
  50523. case WorkerTaskType.COLLIDE:
  50524. var returnPayload = returnData.payload;
  50525. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50526. return;
  50527. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50528. if (callback) {
  50529. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50530. if (mesh) {
  50531. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50532. }
  50533. }
  50534. //cleanup
  50535. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50536. break;
  50537. }
  50538. };
  50539. this._collisionsCallbackArray = [];
  50540. this._init = false;
  50541. this._runningUpdated = 0;
  50542. this._addUpdateMeshesList = {};
  50543. this._addUpdateGeometriesList = {};
  50544. this._toRemoveGeometryArray = [];
  50545. this._toRemoveMeshesArray = [];
  50546. }
  50547. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50548. if (!this._init)
  50549. return;
  50550. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50551. return;
  50552. position.divideToRef(collider._radius, this._scaledPosition);
  50553. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50554. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50555. var payload = {
  50556. collider: {
  50557. position: this._scaledPosition.asArray(),
  50558. velocity: this._scaledVelocity.asArray(),
  50559. radius: collider._radius.asArray()
  50560. },
  50561. collisionId: collisionIndex,
  50562. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50563. maximumRetry: maximumRetry
  50564. };
  50565. var message = {
  50566. payload: payload,
  50567. taskType: WorkerTaskType.COLLIDE
  50568. };
  50569. this._worker.postMessage(message);
  50570. };
  50571. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50572. this._scene = scene;
  50573. this._scene.registerAfterRender(this._afterRender);
  50574. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50575. this._worker = new Worker(workerUrl);
  50576. this._worker.onmessage = this._onMessageFromWorker;
  50577. var message = {
  50578. payload: {},
  50579. taskType: WorkerTaskType.INIT
  50580. };
  50581. this._worker.postMessage(message);
  50582. };
  50583. CollisionCoordinatorWorker.prototype.destroy = function () {
  50584. this._scene.unregisterAfterRender(this._afterRender);
  50585. this._worker.terminate();
  50586. };
  50587. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50588. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50589. this.onMeshUpdated(mesh);
  50590. };
  50591. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50592. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50593. };
  50594. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50595. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50596. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50597. this.onGeometryUpdated(geometry);
  50598. };
  50599. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50600. this._toRemoveGeometryArray.push(geometry.id);
  50601. };
  50602. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50603. var submeshes = [];
  50604. if (mesh.subMeshes) {
  50605. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50606. var boundingInfo = sm.getBoundingInfo();
  50607. return {
  50608. position: idx,
  50609. verticesStart: sm.verticesStart,
  50610. verticesCount: sm.verticesCount,
  50611. indexStart: sm.indexStart,
  50612. indexCount: sm.indexCount,
  50613. hasMaterial: !!sm.getMaterial(),
  50614. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50615. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50616. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50617. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50618. };
  50619. });
  50620. }
  50621. var geometryId = null;
  50622. if (mesh instanceof BABYLON.Mesh) {
  50623. var geometry = mesh.geometry;
  50624. geometryId = geometry ? geometry.id : null;
  50625. }
  50626. else if (mesh instanceof BABYLON.InstancedMesh) {
  50627. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50628. geometryId = geometry ? geometry.id : null;
  50629. }
  50630. var boundingInfo = mesh.getBoundingInfo();
  50631. return {
  50632. uniqueId: mesh.uniqueId,
  50633. id: mesh.id,
  50634. name: mesh.name,
  50635. geometryId: geometryId,
  50636. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50637. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50638. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50639. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50640. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50641. subMeshes: submeshes,
  50642. checkCollisions: mesh.checkCollisions
  50643. };
  50644. };
  50645. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50646. return {
  50647. id: geometry.id,
  50648. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50649. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50650. indices: new Uint32Array(geometry.getIndices() || []),
  50651. };
  50652. };
  50653. return CollisionCoordinatorWorker;
  50654. }());
  50655. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50656. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50657. function CollisionCoordinatorLegacy() {
  50658. this._scaledPosition = BABYLON.Vector3.Zero();
  50659. this._scaledVelocity = BABYLON.Vector3.Zero();
  50660. this._finalPosition = BABYLON.Vector3.Zero();
  50661. }
  50662. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50663. position.divideToRef(collider._radius, this._scaledPosition);
  50664. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50665. collider.collidedMesh = null;
  50666. collider._retry = 0;
  50667. collider._initialVelocity = this._scaledVelocity;
  50668. collider._initialPosition = this._scaledPosition;
  50669. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50670. this._finalPosition.multiplyInPlace(collider._radius);
  50671. //run the callback
  50672. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50673. };
  50674. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50675. this._scene = scene;
  50676. };
  50677. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50678. //Legacy need no destruction method.
  50679. };
  50680. //No update in legacy mode
  50681. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50682. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50683. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50684. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50685. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50686. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50687. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50688. if (excludedMesh === void 0) { excludedMesh = null; }
  50689. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50690. if (collider._retry >= maximumRetry) {
  50691. finalPosition.copyFrom(position);
  50692. return;
  50693. }
  50694. // Check if this is a mesh else camera or -1
  50695. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50696. collider._initialize(position, velocity, closeDistance);
  50697. // Check all meshes
  50698. for (var index = 0; index < this._scene.meshes.length; index++) {
  50699. var mesh = this._scene.meshes[index];
  50700. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50701. mesh._checkCollision(collider);
  50702. }
  50703. }
  50704. if (!collider.collisionFound) {
  50705. position.addToRef(velocity, finalPosition);
  50706. return;
  50707. }
  50708. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50709. collider._getResponse(position, velocity);
  50710. }
  50711. if (velocity.length() <= closeDistance) {
  50712. finalPosition.copyFrom(position);
  50713. return;
  50714. }
  50715. collider._retry++;
  50716. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50717. };
  50718. return CollisionCoordinatorLegacy;
  50719. }());
  50720. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50721. })(BABYLON || (BABYLON = {}));
  50722. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50723. var BABYLON;
  50724. (function (BABYLON) {
  50725. /**
  50726. * A particle represents one of the element emitted by a particle system.
  50727. * This is mainly define by its coordinates, direction, velocity and age.
  50728. */
  50729. var Particle = /** @class */ (function () {
  50730. /**
  50731. * Creates a new instance of @see Particle
  50732. * @param particleSystem the particle system the particle belongs to
  50733. */
  50734. function Particle(
  50735. /**
  50736. * particleSystem the particle system the particle belongs to.
  50737. */
  50738. particleSystem) {
  50739. this.particleSystem = particleSystem;
  50740. /**
  50741. * The world position of the particle in the scene.
  50742. */
  50743. this.position = BABYLON.Vector3.Zero();
  50744. /**
  50745. * The world direction of the particle in the scene.
  50746. */
  50747. this.direction = BABYLON.Vector3.Zero();
  50748. /**
  50749. * The color of the particle.
  50750. */
  50751. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50752. /**
  50753. * The color change of the particle per step.
  50754. */
  50755. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50756. /**
  50757. * Defines how long will the life of the particle be.
  50758. */
  50759. this.lifeTime = 1.0;
  50760. /**
  50761. * The current age of the particle.
  50762. */
  50763. this.age = 0;
  50764. /**
  50765. * The current size of the particle.
  50766. */
  50767. this.size = 0;
  50768. /**
  50769. * The current angle of the particle.
  50770. */
  50771. this.angle = 0;
  50772. /**
  50773. * Defines how fast is the angle changing.
  50774. */
  50775. this.angularSpeed = 0;
  50776. /**
  50777. * Defines the cell index used by the particle to be rendered from a sprite.
  50778. */
  50779. this.cellIndex = 0;
  50780. this._currentFrameCounter = 0;
  50781. if (!this.particleSystem.isAnimationSheetEnabled) {
  50782. return;
  50783. }
  50784. this.updateCellInfoFromSystem();
  50785. }
  50786. Particle.prototype.updateCellInfoFromSystem = function () {
  50787. this.cellIndex = this.particleSystem.startSpriteCellID;
  50788. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50789. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50790. }
  50791. else {
  50792. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50793. }
  50794. };
  50795. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50796. // (ageOffset / scaledUpdateSpeed) / available cells
  50797. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50798. this._currentFrameCounter += scaledUpdateSpeed;
  50799. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50800. this._currentFrameCounter = 0;
  50801. this.cellIndex++;
  50802. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50803. this.cellIndex = this.particleSystem.endSpriteCellID;
  50804. }
  50805. }
  50806. };
  50807. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50808. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50809. this.cellIndex++;
  50810. this._currentFrameCounter = 0;
  50811. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50812. if (this.particleSystem.spriteCellLoop) {
  50813. this.cellIndex = this.particleSystem.startSpriteCellID;
  50814. }
  50815. else {
  50816. this.cellIndex = this.particleSystem.endSpriteCellID;
  50817. }
  50818. }
  50819. }
  50820. else {
  50821. this._currentFrameCounter++;
  50822. }
  50823. };
  50824. /**
  50825. * Copy the properties of particle to another one.
  50826. * @param other the particle to copy the information to.
  50827. */
  50828. Particle.prototype.copyTo = function (other) {
  50829. other.position.copyFrom(this.position);
  50830. other.direction.copyFrom(this.direction);
  50831. other.color.copyFrom(this.color);
  50832. other.colorStep.copyFrom(this.colorStep);
  50833. other.lifeTime = this.lifeTime;
  50834. other.age = this.age;
  50835. other.size = this.size;
  50836. other.angle = this.angle;
  50837. other.angularSpeed = this.angularSpeed;
  50838. other.particleSystem = this.particleSystem;
  50839. other.cellIndex = this.cellIndex;
  50840. };
  50841. return Particle;
  50842. }());
  50843. BABYLON.Particle = Particle;
  50844. })(BABYLON || (BABYLON = {}));
  50845. //# sourceMappingURL=babylon.particle.js.map
  50846. var BABYLON;
  50847. (function (BABYLON) {
  50848. /**
  50849. * This represents a particle system in Babylon.
  50850. * 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.
  50851. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50852. * @example https://doc.babylonjs.com/babylon101/particles
  50853. */
  50854. var ParticleSystem = /** @class */ (function () {
  50855. /**
  50856. * Instantiates a particle system.
  50857. * 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.
  50858. * @param name The name of the particle system
  50859. * @param capacity The max number of particles alive at the same time
  50860. * @param scene The scene the particle system belongs to
  50861. * @param customEffect a custom effect used to change the way particles are rendered by default
  50862. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50863. * @param epsilon Offset used to render the particles
  50864. */
  50865. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50866. if (customEffect === void 0) { customEffect = null; }
  50867. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50868. if (epsilon === void 0) { epsilon = 0.01; }
  50869. var _this = this;
  50870. /**
  50871. * List of animations used by the particle system.
  50872. */
  50873. this.animations = [];
  50874. /**
  50875. * The rendering group used by the Particle system to chose when to render.
  50876. */
  50877. this.renderingGroupId = 0;
  50878. /**
  50879. * The emitter represents the Mesh or position we are attaching the particle system to.
  50880. */
  50881. this.emitter = null;
  50882. /**
  50883. * The maximum number of particles to emit per frame
  50884. */
  50885. this.emitRate = 10;
  50886. /**
  50887. * If you want to launch only a few particles at once, that can be done, as well.
  50888. */
  50889. this.manualEmitCount = -1;
  50890. /**
  50891. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50892. */
  50893. this.updateSpeed = 0.01;
  50894. /**
  50895. * The amount of time the particle system is running (depends of the overall update speed).
  50896. */
  50897. this.targetStopDuration = 0;
  50898. /**
  50899. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50900. */
  50901. this.disposeOnStop = false;
  50902. /**
  50903. * Minimum power of emitting particles.
  50904. */
  50905. this.minEmitPower = 1;
  50906. /**
  50907. * Maximum power of emitting particles.
  50908. */
  50909. this.maxEmitPower = 1;
  50910. /**
  50911. * Minimum life time of emitting particles.
  50912. */
  50913. this.minLifeTime = 1;
  50914. /**
  50915. * Maximum life time of emitting particles.
  50916. */
  50917. this.maxLifeTime = 1;
  50918. /**
  50919. * Minimum Size of emitting particles.
  50920. */
  50921. this.minSize = 1;
  50922. /**
  50923. * Maximum Size of emitting particles.
  50924. */
  50925. this.maxSize = 1;
  50926. /**
  50927. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50928. */
  50929. this.minAngularSpeed = 0;
  50930. /**
  50931. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50932. */
  50933. this.maxAngularSpeed = 0;
  50934. /**
  50935. * The layer mask we are rendering the particles through.
  50936. */
  50937. this.layerMask = 0x0FFFFFFF;
  50938. /**
  50939. * This can help using your own shader to render the particle system.
  50940. * The according effect will be created
  50941. */
  50942. this.customShader = null;
  50943. /**
  50944. * By default particle system starts as soon as they are created. This prevents the
  50945. * automatic start to happen and let you decide when to start emitting particles.
  50946. */
  50947. this.preventAutoStart = false;
  50948. /**
  50949. * Callback triggered when the particle animation is ending.
  50950. */
  50951. this.onAnimationEnd = null;
  50952. /**
  50953. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50954. */
  50955. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50956. /**
  50957. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50958. * to override the particles.
  50959. */
  50960. this.forceDepthWrite = false;
  50961. /**
  50962. * You can use gravity if you want to give an orientation to your particles.
  50963. */
  50964. this.gravity = BABYLON.Vector3.Zero();
  50965. /**
  50966. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50967. */
  50968. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50969. /**
  50970. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50971. */
  50972. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50973. /**
  50974. * Color the particle will have at the end of its lifetime.
  50975. */
  50976. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50977. /**
  50978. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50979. */
  50980. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50981. /**
  50982. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50983. */
  50984. this.spriteCellLoop = true;
  50985. /**
  50986. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50987. */
  50988. this.spriteCellChangeSpeed = 0;
  50989. /**
  50990. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50991. */
  50992. this.startSpriteCellID = 0;
  50993. /**
  50994. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50995. */
  50996. this.endSpriteCellID = 0;
  50997. /**
  50998. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50999. */
  51000. this.spriteCellWidth = 0;
  51001. /**
  51002. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51003. */
  51004. this.spriteCellHeight = 0;
  51005. /**
  51006. * An event triggered when the system is disposed.
  51007. */
  51008. this.onDisposeObservable = new BABYLON.Observable();
  51009. this._particles = new Array();
  51010. this._stockParticles = new Array();
  51011. this._newPartsExcess = 0;
  51012. this._vertexBuffers = {};
  51013. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51014. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51015. this._scaledDirection = BABYLON.Vector3.Zero();
  51016. this._scaledGravity = BABYLON.Vector3.Zero();
  51017. this._currentRenderId = -1;
  51018. this._started = false;
  51019. this._stopped = false;
  51020. this._actualFrame = 0;
  51021. this._vertexBufferSize = 11;
  51022. // start of sub system methods
  51023. /**
  51024. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51025. * Its lifetime will start back at 0.
  51026. */
  51027. this.recycleParticle = function (particle) {
  51028. var lastParticle = _this._particles.pop();
  51029. if (lastParticle !== particle) {
  51030. lastParticle.copyTo(particle);
  51031. }
  51032. _this._stockParticles.push(lastParticle);
  51033. };
  51034. this._createParticle = function () {
  51035. var particle;
  51036. if (_this._stockParticles.length !== 0) {
  51037. particle = _this._stockParticles.pop();
  51038. particle.age = 0;
  51039. particle.cellIndex = _this.startSpriteCellID;
  51040. }
  51041. else {
  51042. particle = new BABYLON.Particle(_this);
  51043. }
  51044. return particle;
  51045. };
  51046. this._emitFromParticle = function (particle) {
  51047. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51048. return;
  51049. }
  51050. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51051. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51052. subSystem._rootParticleSystem = _this;
  51053. _this.activeSubSystems.push(subSystem);
  51054. subSystem.start();
  51055. };
  51056. this._appendParticleVertexes = null;
  51057. this.id = name;
  51058. this.name = name;
  51059. this._capacity = capacity;
  51060. this._epsilon = epsilon;
  51061. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51062. if (isAnimationSheetEnabled) {
  51063. this._vertexBufferSize = 12;
  51064. }
  51065. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51066. this._customEffect = customEffect;
  51067. scene.particleSystems.push(this);
  51068. this._createIndexBuffer();
  51069. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51070. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51071. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51072. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51073. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51074. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51075. if (this._isAnimationSheetEnabled) {
  51076. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51077. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51078. }
  51079. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51080. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51081. this._vertexBuffers["options"] = options;
  51082. // Default emitter type
  51083. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51084. this.updateFunction = function (particles) {
  51085. for (var index = 0; index < particles.length; index++) {
  51086. var particle = particles[index];
  51087. particle.age += _this._scaledUpdateSpeed;
  51088. if (particle.age >= particle.lifeTime) {
  51089. _this._emitFromParticle(particle);
  51090. _this.recycleParticle(particle);
  51091. index--;
  51092. continue;
  51093. }
  51094. else {
  51095. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51096. particle.color.addInPlace(_this._scaledColorStep);
  51097. if (particle.color.a < 0)
  51098. particle.color.a = 0;
  51099. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51100. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51101. particle.position.addInPlace(_this._scaledDirection);
  51102. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51103. particle.direction.addInPlace(_this._scaledGravity);
  51104. if (_this._isAnimationSheetEnabled) {
  51105. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51106. }
  51107. }
  51108. }
  51109. };
  51110. }
  51111. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51112. /**
  51113. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51114. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51115. */
  51116. get: function () {
  51117. if (this.particleEmitterType.direction1) {
  51118. return this.particleEmitterType.direction1;
  51119. }
  51120. return BABYLON.Vector3.Zero();
  51121. },
  51122. set: function (value) {
  51123. if (this.particleEmitterType.direction1) {
  51124. this.particleEmitterType.direction1 = value;
  51125. }
  51126. },
  51127. enumerable: true,
  51128. configurable: true
  51129. });
  51130. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51131. /**
  51132. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51133. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51134. */
  51135. get: function () {
  51136. if (this.particleEmitterType.direction2) {
  51137. return this.particleEmitterType.direction2;
  51138. }
  51139. return BABYLON.Vector3.Zero();
  51140. },
  51141. set: function (value) {
  51142. if (this.particleEmitterType.direction2) {
  51143. this.particleEmitterType.direction2 = value;
  51144. }
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51150. /**
  51151. * 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.
  51152. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51153. */
  51154. get: function () {
  51155. if (this.particleEmitterType.minEmitBox) {
  51156. return this.particleEmitterType.minEmitBox;
  51157. }
  51158. return BABYLON.Vector3.Zero();
  51159. },
  51160. set: function (value) {
  51161. if (this.particleEmitterType.minEmitBox) {
  51162. this.particleEmitterType.minEmitBox = value;
  51163. }
  51164. },
  51165. enumerable: true,
  51166. configurable: true
  51167. });
  51168. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51169. /**
  51170. * 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.
  51171. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51172. */
  51173. get: function () {
  51174. if (this.particleEmitterType.maxEmitBox) {
  51175. return this.particleEmitterType.maxEmitBox;
  51176. }
  51177. return BABYLON.Vector3.Zero();
  51178. },
  51179. set: function (value) {
  51180. if (this.particleEmitterType.maxEmitBox) {
  51181. this.particleEmitterType.maxEmitBox = value;
  51182. }
  51183. },
  51184. enumerable: true,
  51185. configurable: true
  51186. });
  51187. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51188. /**
  51189. * Sets a callback that will be triggered when the system is disposed.
  51190. */
  51191. set: function (callback) {
  51192. if (this._onDisposeObserver) {
  51193. this.onDisposeObservable.remove(this._onDisposeObserver);
  51194. }
  51195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51196. },
  51197. enumerable: true,
  51198. configurable: true
  51199. });
  51200. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51201. /**
  51202. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51203. */
  51204. get: function () {
  51205. return this._isAnimationSheetEnabled;
  51206. },
  51207. enumerable: true,
  51208. configurable: true
  51209. });
  51210. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51211. //end of Sub-emitter
  51212. /**
  51213. * Gets the current list of active particles
  51214. */
  51215. get: function () {
  51216. return this._particles;
  51217. },
  51218. enumerable: true,
  51219. configurable: true
  51220. });
  51221. /**
  51222. * Returns the string "ParticleSystem"
  51223. * @returns a string containing the class name
  51224. */
  51225. ParticleSystem.prototype.getClassName = function () {
  51226. return "ParticleSystem";
  51227. };
  51228. ParticleSystem.prototype._createIndexBuffer = function () {
  51229. var indices = [];
  51230. var index = 0;
  51231. for (var count = 0; count < this._capacity; count++) {
  51232. indices.push(index);
  51233. indices.push(index + 1);
  51234. indices.push(index + 2);
  51235. indices.push(index);
  51236. indices.push(index + 2);
  51237. indices.push(index + 3);
  51238. index += 4;
  51239. }
  51240. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51241. };
  51242. /**
  51243. * Gets the maximum number of particles active at the same time.
  51244. * @returns The max number of active particles.
  51245. */
  51246. ParticleSystem.prototype.getCapacity = function () {
  51247. return this._capacity;
  51248. };
  51249. /**
  51250. * Gets Wether there are still active particles in the system.
  51251. * @returns True if it is alive, otherwise false.
  51252. */
  51253. ParticleSystem.prototype.isAlive = function () {
  51254. return this._alive;
  51255. };
  51256. /**
  51257. * Gets Wether the system has been started.
  51258. * @returns True if it has been started, otherwise false.
  51259. */
  51260. ParticleSystem.prototype.isStarted = function () {
  51261. return this._started;
  51262. };
  51263. /**
  51264. * Starts the particle system and begins to emit.
  51265. */
  51266. ParticleSystem.prototype.start = function () {
  51267. this._started = true;
  51268. this._stopped = false;
  51269. this._actualFrame = 0;
  51270. if (this.subEmitters && this.subEmitters.length != 0) {
  51271. this.activeSubSystems = new Array();
  51272. }
  51273. };
  51274. /**
  51275. * Stops the particle system.
  51276. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51277. */
  51278. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51279. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51280. this._stopped = true;
  51281. if (stopSubEmitters) {
  51282. this._stopSubEmitters();
  51283. }
  51284. };
  51285. // animation sheet
  51286. /**
  51287. * Remove all active particles
  51288. */
  51289. ParticleSystem.prototype.reset = function () {
  51290. this._stockParticles = [];
  51291. this._particles = [];
  51292. };
  51293. /**
  51294. * @ignore (for internal use only)
  51295. */
  51296. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51297. var offset = index * this._vertexBufferSize;
  51298. this._vertexData[offset] = particle.position.x;
  51299. this._vertexData[offset + 1] = particle.position.y;
  51300. this._vertexData[offset + 2] = particle.position.z;
  51301. this._vertexData[offset + 3] = particle.color.r;
  51302. this._vertexData[offset + 4] = particle.color.g;
  51303. this._vertexData[offset + 5] = particle.color.b;
  51304. this._vertexData[offset + 6] = particle.color.a;
  51305. this._vertexData[offset + 7] = particle.angle;
  51306. this._vertexData[offset + 8] = particle.size;
  51307. this._vertexData[offset + 9] = offsetX;
  51308. this._vertexData[offset + 10] = offsetY;
  51309. };
  51310. /**
  51311. * @ignore (for internal use only)
  51312. */
  51313. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51314. if (offsetX === 0)
  51315. offsetX = this._epsilon;
  51316. else if (offsetX === 1)
  51317. offsetX = 1 - this._epsilon;
  51318. if (offsetY === 0)
  51319. offsetY = this._epsilon;
  51320. else if (offsetY === 1)
  51321. offsetY = 1 - this._epsilon;
  51322. var offset = index * this._vertexBufferSize;
  51323. this._vertexData[offset] = particle.position.x;
  51324. this._vertexData[offset + 1] = particle.position.y;
  51325. this._vertexData[offset + 2] = particle.position.z;
  51326. this._vertexData[offset + 3] = particle.color.r;
  51327. this._vertexData[offset + 4] = particle.color.g;
  51328. this._vertexData[offset + 5] = particle.color.b;
  51329. this._vertexData[offset + 6] = particle.color.a;
  51330. this._vertexData[offset + 7] = particle.angle;
  51331. this._vertexData[offset + 8] = particle.size;
  51332. this._vertexData[offset + 9] = offsetX;
  51333. this._vertexData[offset + 10] = offsetY;
  51334. this._vertexData[offset + 11] = particle.cellIndex;
  51335. };
  51336. ParticleSystem.prototype._stopSubEmitters = function () {
  51337. if (!this.activeSubSystems) {
  51338. return;
  51339. }
  51340. this.activeSubSystems.forEach(function (subSystem) {
  51341. subSystem.stop(true);
  51342. });
  51343. this.activeSubSystems = new Array();
  51344. };
  51345. ParticleSystem.prototype._removeFromRoot = function () {
  51346. if (!this._rootParticleSystem) {
  51347. return;
  51348. }
  51349. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51350. if (index !== -1) {
  51351. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51352. }
  51353. };
  51354. // end of sub system methods
  51355. ParticleSystem.prototype._update = function (newParticles) {
  51356. // Update current
  51357. this._alive = this._particles.length > 0;
  51358. this.updateFunction(this._particles);
  51359. // Add new ones
  51360. var worldMatrix;
  51361. if (this.emitter.position) {
  51362. var emitterMesh = this.emitter;
  51363. worldMatrix = emitterMesh.getWorldMatrix();
  51364. }
  51365. else {
  51366. var emitterPosition = this.emitter;
  51367. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51368. }
  51369. var particle;
  51370. for (var index = 0; index < newParticles; index++) {
  51371. if (this._particles.length === this._capacity) {
  51372. break;
  51373. }
  51374. particle = this._createParticle();
  51375. this._particles.push(particle);
  51376. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51377. if (this.startPositionFunction) {
  51378. this.startPositionFunction(worldMatrix, particle.position, particle);
  51379. }
  51380. else {
  51381. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51382. }
  51383. if (this.startDirectionFunction) {
  51384. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51385. }
  51386. else {
  51387. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51388. }
  51389. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51390. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51391. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51392. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51393. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51394. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51395. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51396. }
  51397. };
  51398. ParticleSystem.prototype._getEffect = function () {
  51399. if (this._customEffect) {
  51400. return this._customEffect;
  51401. }
  51402. ;
  51403. var defines = [];
  51404. if (this._scene.clipPlane) {
  51405. defines.push("#define CLIPPLANE");
  51406. }
  51407. if (this._isAnimationSheetEnabled) {
  51408. defines.push("#define ANIMATESHEET");
  51409. }
  51410. // Effect
  51411. var join = defines.join("\n");
  51412. if (this._cachedDefines !== join) {
  51413. this._cachedDefines = join;
  51414. var attributesNamesOrOptions;
  51415. var effectCreationOption;
  51416. if (this._isAnimationSheetEnabled) {
  51417. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51418. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51419. }
  51420. else {
  51421. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51422. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51423. }
  51424. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51425. }
  51426. return this._effect;
  51427. };
  51428. /**
  51429. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51430. */
  51431. ParticleSystem.prototype.animate = function () {
  51432. if (!this._started)
  51433. return;
  51434. var effect = this._getEffect();
  51435. // Check
  51436. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51437. return;
  51438. if (this._currentRenderId === this._scene.getRenderId()) {
  51439. return;
  51440. }
  51441. this._currentRenderId = this._scene.getRenderId();
  51442. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51443. // determine the number of particles we need to create
  51444. var newParticles;
  51445. if (this.manualEmitCount > -1) {
  51446. newParticles = this.manualEmitCount;
  51447. this._newPartsExcess = 0;
  51448. this.manualEmitCount = 0;
  51449. }
  51450. else {
  51451. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51452. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51453. }
  51454. if (this._newPartsExcess > 1.0) {
  51455. newParticles += this._newPartsExcess >> 0;
  51456. this._newPartsExcess -= this._newPartsExcess >> 0;
  51457. }
  51458. this._alive = false;
  51459. if (!this._stopped) {
  51460. this._actualFrame += this._scaledUpdateSpeed;
  51461. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51462. this.stop();
  51463. }
  51464. else {
  51465. newParticles = 0;
  51466. }
  51467. this._update(newParticles);
  51468. // Stopped?
  51469. if (this._stopped) {
  51470. if (!this._alive) {
  51471. this._started = false;
  51472. if (this.onAnimationEnd) {
  51473. this.onAnimationEnd();
  51474. }
  51475. if (this.disposeOnStop) {
  51476. this._scene._toBeDisposed.push(this);
  51477. }
  51478. }
  51479. }
  51480. // Animation sheet
  51481. if (this._isAnimationSheetEnabled) {
  51482. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51483. }
  51484. else {
  51485. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51486. }
  51487. // Update VBO
  51488. var offset = 0;
  51489. for (var index = 0; index < this._particles.length; index++) {
  51490. var particle = this._particles[index];
  51491. this._appendParticleVertexes(offset, particle);
  51492. offset += 4;
  51493. }
  51494. if (this._vertexBuffer) {
  51495. this._vertexBuffer.update(this._vertexData);
  51496. }
  51497. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51498. this.stop();
  51499. }
  51500. };
  51501. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51502. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51503. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51504. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51505. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51506. };
  51507. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51508. this._appendParticleVertex(offset++, particle, 0, 0);
  51509. this._appendParticleVertex(offset++, particle, 1, 0);
  51510. this._appendParticleVertex(offset++, particle, 1, 1);
  51511. this._appendParticleVertex(offset++, particle, 0, 1);
  51512. };
  51513. /**
  51514. * Rebuilds the particle system.
  51515. */
  51516. ParticleSystem.prototype.rebuild = function () {
  51517. this._createIndexBuffer();
  51518. if (this._vertexBuffer) {
  51519. this._vertexBuffer._rebuild();
  51520. }
  51521. };
  51522. /**
  51523. * Renders the particle system in its current state.
  51524. * @returns the current number of particles
  51525. */
  51526. ParticleSystem.prototype.render = function () {
  51527. var effect = this._getEffect();
  51528. // Check
  51529. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51530. return 0;
  51531. }
  51532. var engine = this._scene.getEngine();
  51533. // Render
  51534. engine.enableEffect(effect);
  51535. engine.setState(false);
  51536. var viewMatrix = this._scene.getViewMatrix();
  51537. effect.setTexture("diffuseSampler", this.particleTexture);
  51538. effect.setMatrix("view", viewMatrix);
  51539. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51540. if (this._isAnimationSheetEnabled) {
  51541. var baseSize = this.particleTexture.getBaseSize();
  51542. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51543. }
  51544. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51545. if (this._scene.clipPlane) {
  51546. var clipPlane = this._scene.clipPlane;
  51547. var invView = viewMatrix.clone();
  51548. invView.invert();
  51549. effect.setMatrix("invView", invView);
  51550. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51551. }
  51552. // VBOs
  51553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51554. // Draw order
  51555. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51556. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51557. }
  51558. else {
  51559. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51560. }
  51561. if (this.forceDepthWrite) {
  51562. engine.setDepthWrite(true);
  51563. }
  51564. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51566. return this._particles.length;
  51567. };
  51568. /**
  51569. * Disposes the particle system and free the associated resources
  51570. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51571. */
  51572. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51573. if (disposeTexture === void 0) { disposeTexture = true; }
  51574. if (this._vertexBuffer) {
  51575. this._vertexBuffer.dispose();
  51576. this._vertexBuffer = null;
  51577. }
  51578. if (this._indexBuffer) {
  51579. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51580. this._indexBuffer = null;
  51581. }
  51582. if (disposeTexture && this.particleTexture) {
  51583. this.particleTexture.dispose();
  51584. this.particleTexture = null;
  51585. }
  51586. this._removeFromRoot();
  51587. // Remove from scene
  51588. var index = this._scene.particleSystems.indexOf(this);
  51589. if (index > -1) {
  51590. this._scene.particleSystems.splice(index, 1);
  51591. }
  51592. // Callback
  51593. this.onDisposeObservable.notifyObservers(this);
  51594. this.onDisposeObservable.clear();
  51595. };
  51596. /**
  51597. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51598. * @param radius The radius of the sphere to emit from
  51599. * @returns the emitter
  51600. */
  51601. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51602. if (radius === void 0) { radius = 1; }
  51603. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51604. this.particleEmitterType = particleEmitter;
  51605. return particleEmitter;
  51606. };
  51607. /**
  51608. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51609. * @param radius The radius of the sphere to emit from
  51610. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51611. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51612. * @returns the emitter
  51613. */
  51614. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51615. if (radius === void 0) { radius = 1; }
  51616. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51617. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51618. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51619. this.particleEmitterType = particleEmitter;
  51620. return particleEmitter;
  51621. };
  51622. /**
  51623. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51624. * @param radius The radius of the cone to emit from
  51625. * @param angle The base angle of the cone
  51626. * @returns the emitter
  51627. */
  51628. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51629. if (radius === void 0) { radius = 1; }
  51630. if (angle === void 0) { angle = Math.PI / 4; }
  51631. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51632. this.particleEmitterType = particleEmitter;
  51633. return particleEmitter;
  51634. };
  51635. // 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.
  51636. /**
  51637. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51638. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51639. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51640. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51641. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51642. * @returns the emitter
  51643. */
  51644. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51645. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51646. this.direction1 = direction1;
  51647. this.direction2 = direction2;
  51648. this.minEmitBox = minEmitBox;
  51649. this.maxEmitBox = maxEmitBox;
  51650. this.particleEmitterType = particleEmitter;
  51651. return particleEmitter;
  51652. };
  51653. // Clone
  51654. /**
  51655. * Clones the particle system.
  51656. * @param name The name of the cloned object
  51657. * @param newEmitter The new emitter to use
  51658. * @returns the cloned particle system
  51659. */
  51660. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51661. var custom = null;
  51662. var program = null;
  51663. if (this.customShader != null) {
  51664. program = this.customShader;
  51665. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51666. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51667. }
  51668. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51669. result.customShader = program;
  51670. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51671. if (newEmitter === undefined) {
  51672. newEmitter = this.emitter;
  51673. }
  51674. result.emitter = newEmitter;
  51675. if (this.particleTexture) {
  51676. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51677. }
  51678. if (!this.preventAutoStart) {
  51679. result.start();
  51680. }
  51681. return result;
  51682. };
  51683. /**
  51684. * Serializes the particle system to a JSON object.
  51685. * @returns the JSON object
  51686. */
  51687. ParticleSystem.prototype.serialize = function () {
  51688. var serializationObject = {};
  51689. serializationObject.name = this.name;
  51690. serializationObject.id = this.id;
  51691. // Emitter
  51692. if (this.emitter.position) {
  51693. var emitterMesh = this.emitter;
  51694. serializationObject.emitterId = emitterMesh.id;
  51695. }
  51696. else {
  51697. var emitterPosition = this.emitter;
  51698. serializationObject.emitter = emitterPosition.asArray();
  51699. }
  51700. serializationObject.capacity = this.getCapacity();
  51701. if (this.particleTexture) {
  51702. serializationObject.textureName = this.particleTexture.name;
  51703. }
  51704. // Animations
  51705. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51706. // Particle system
  51707. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51708. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51709. serializationObject.minSize = this.minSize;
  51710. serializationObject.maxSize = this.maxSize;
  51711. serializationObject.minEmitPower = this.minEmitPower;
  51712. serializationObject.maxEmitPower = this.maxEmitPower;
  51713. serializationObject.minLifeTime = this.minLifeTime;
  51714. serializationObject.maxLifeTime = this.maxLifeTime;
  51715. serializationObject.emitRate = this.emitRate;
  51716. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51717. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51718. serializationObject.gravity = this.gravity.asArray();
  51719. serializationObject.direction1 = this.direction1.asArray();
  51720. serializationObject.direction2 = this.direction2.asArray();
  51721. serializationObject.color1 = this.color1.asArray();
  51722. serializationObject.color2 = this.color2.asArray();
  51723. serializationObject.colorDead = this.colorDead.asArray();
  51724. serializationObject.updateSpeed = this.updateSpeed;
  51725. serializationObject.targetStopDuration = this.targetStopDuration;
  51726. serializationObject.textureMask = this.textureMask.asArray();
  51727. serializationObject.blendMode = this.blendMode;
  51728. serializationObject.customShader = this.customShader;
  51729. serializationObject.preventAutoStart = this.preventAutoStart;
  51730. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51731. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51732. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51733. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51734. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51735. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51736. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51737. // Emitter
  51738. if (this.particleEmitterType) {
  51739. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51740. }
  51741. return serializationObject;
  51742. };
  51743. /**
  51744. * Parses a JSON object to create a particle system.
  51745. * @param parsedParticleSystem The JSON object to parse
  51746. * @param scene The scene to create the particle system in
  51747. * @param rootUrl The root url to use to load external dependencies like texture
  51748. * @returns the Parsed particle system
  51749. */
  51750. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51751. var name = parsedParticleSystem.name;
  51752. var custom = null;
  51753. var program = null;
  51754. if (parsedParticleSystem.customShader) {
  51755. program = parsedParticleSystem.customShader;
  51756. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51757. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51758. }
  51759. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51760. particleSystem.customShader = program;
  51761. if (parsedParticleSystem.id) {
  51762. particleSystem.id = parsedParticleSystem.id;
  51763. }
  51764. // Auto start
  51765. if (parsedParticleSystem.preventAutoStart) {
  51766. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51767. }
  51768. // Texture
  51769. if (parsedParticleSystem.textureName) {
  51770. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51771. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51772. }
  51773. // Emitter
  51774. if (parsedParticleSystem.emitterId) {
  51775. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51776. }
  51777. else {
  51778. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51779. }
  51780. // Animations
  51781. if (parsedParticleSystem.animations) {
  51782. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51783. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51784. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51785. }
  51786. }
  51787. if (parsedParticleSystem.autoAnimate) {
  51788. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51789. }
  51790. // Particle system
  51791. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51792. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51793. particleSystem.minSize = parsedParticleSystem.minSize;
  51794. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51795. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51796. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51797. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51798. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51799. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51800. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51801. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51802. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51803. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51804. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51805. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51806. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51807. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51808. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51809. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51810. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51811. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51812. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51813. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51814. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51815. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51816. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51817. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51818. if (!particleSystem.preventAutoStart) {
  51819. particleSystem.start();
  51820. }
  51821. return particleSystem;
  51822. };
  51823. /**
  51824. * Source color is added to the destination color without alpha affecting the result.
  51825. */
  51826. ParticleSystem.BLENDMODE_ONEONE = 0;
  51827. /**
  51828. * Blend current color and particle color using particle’s alpha.
  51829. */
  51830. ParticleSystem.BLENDMODE_STANDARD = 1;
  51831. return ParticleSystem;
  51832. }());
  51833. BABYLON.ParticleSystem = ParticleSystem;
  51834. })(BABYLON || (BABYLON = {}));
  51835. //# sourceMappingURL=babylon.particleSystem.js.map
  51836. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51837. var BABYLON;
  51838. (function (BABYLON) {
  51839. /**
  51840. * Particle emitter emitting particles from the inside of a box.
  51841. * It emits the particles randomly between 2 given directions.
  51842. */
  51843. var BoxParticleEmitter = /** @class */ (function () {
  51844. /**
  51845. * Creates a new instance of @see BoxParticleEmitter
  51846. */
  51847. function BoxParticleEmitter() {
  51848. /**
  51849. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51850. */
  51851. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51852. /**
  51853. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51854. */
  51855. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51856. /**
  51857. * 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.
  51858. */
  51859. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51860. /**
  51861. * 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.
  51862. */
  51863. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51864. }
  51865. /**
  51866. * Called by the particle System when the direction is computed for the created particle.
  51867. * @param emitPower is the power of the particle (speed)
  51868. * @param worldMatrix is the world matrix of the particle system
  51869. * @param directionToUpdate is the direction vector to update with the result
  51870. * @param particle is the particle we are computed the direction for
  51871. */
  51872. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51873. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51874. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51875. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51876. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51877. };
  51878. /**
  51879. * Called by the particle System when the position is computed for the created particle.
  51880. * @param worldMatrix is the world matrix of the particle system
  51881. * @param positionToUpdate is the position vector to update with the result
  51882. * @param particle is the particle we are computed the position for
  51883. */
  51884. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51885. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51886. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51887. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51889. };
  51890. /**
  51891. * Clones the current emitter and returns a copy of it
  51892. * @returns the new emitter
  51893. */
  51894. BoxParticleEmitter.prototype.clone = function () {
  51895. var newOne = new BoxParticleEmitter();
  51896. BABYLON.Tools.DeepCopy(this, newOne);
  51897. return newOne;
  51898. };
  51899. /**
  51900. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51901. * @param effect defines the update shader
  51902. */
  51903. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51904. effect.setVector3("direction1", this.direction1);
  51905. effect.setVector3("direction2", this.direction2);
  51906. effect.setVector3("minEmitBox", this.minEmitBox);
  51907. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51908. };
  51909. /**
  51910. * Returns a string to use to update the GPU particles update shader
  51911. * @returns a string containng the defines string
  51912. */
  51913. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51914. return "#define BOXEMITTER";
  51915. };
  51916. /**
  51917. * Returns the string "BoxEmitter"
  51918. * @returns a string containing the class name
  51919. */
  51920. BoxParticleEmitter.prototype.getClassName = function () {
  51921. return "BoxEmitter";
  51922. };
  51923. /**
  51924. * Serializes the particle system to a JSON object.
  51925. * @returns the JSON object
  51926. */
  51927. BoxParticleEmitter.prototype.serialize = function () {
  51928. var serializationObject = {};
  51929. serializationObject.type = this.getClassName();
  51930. serializationObject.direction1 = this.direction1.asArray();
  51931. ;
  51932. serializationObject.direction2 = this.direction2.asArray();
  51933. ;
  51934. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51935. ;
  51936. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51937. ;
  51938. return serializationObject;
  51939. };
  51940. /**
  51941. * Parse properties from a JSON object
  51942. * @param serializationObject defines the JSON object
  51943. */
  51944. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51945. this.direction1.copyFrom(serializationObject.direction1);
  51946. this.direction2.copyFrom(serializationObject.direction2);
  51947. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51948. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51949. };
  51950. return BoxParticleEmitter;
  51951. }());
  51952. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. /**
  51958. * Particle emitter emitting particles from the inside of a cone.
  51959. * It emits the particles alongside the cone volume from the base to the particle.
  51960. * The emission direction might be randomized.
  51961. */
  51962. var ConeParticleEmitter = /** @class */ (function () {
  51963. /**
  51964. * Creates a new instance of @see ConeParticleEmitter
  51965. * @param radius the radius of the emission cone (1 by default)
  51966. * @param angles the cone base angle (PI by default)
  51967. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51968. */
  51969. function ConeParticleEmitter(radius,
  51970. /**
  51971. * The radius of the emission cone.
  51972. */
  51973. angle,
  51974. /**
  51975. * The cone base angle.
  51976. */
  51977. directionRandomizer) {
  51978. if (radius === void 0) { radius = 1; }
  51979. if (angle === void 0) { angle = Math.PI; }
  51980. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51981. this.angle = angle;
  51982. this.directionRandomizer = directionRandomizer;
  51983. this.radius = radius;
  51984. }
  51985. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51986. /**
  51987. * Gets the radius of the emission cone.
  51988. */
  51989. get: function () {
  51990. return this._radius;
  51991. },
  51992. /**
  51993. * Sets the radius of the emission cone.
  51994. */
  51995. set: function (value) {
  51996. this._radius = value;
  51997. if (this.angle !== 0) {
  51998. this._height = value / Math.tan(this.angle / 2);
  51999. }
  52000. else {
  52001. this._height = 1;
  52002. }
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. /**
  52008. * Called by the particle System when the direction is computed for the created particle.
  52009. * @param emitPower is the power of the particle (speed)
  52010. * @param worldMatrix is the world matrix of the particle system
  52011. * @param directionToUpdate is the direction vector to update with the result
  52012. * @param particle is the particle we are computed the direction for
  52013. */
  52014. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52015. if (this.angle === 0) {
  52016. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52017. }
  52018. else {
  52019. // measure the direction Vector from the emitter to the particle.
  52020. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52021. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52022. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52023. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52024. direction.x += randX;
  52025. direction.y += randY;
  52026. direction.z += randZ;
  52027. direction.normalize();
  52028. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52029. }
  52030. };
  52031. /**
  52032. * Called by the particle System when the position is computed for the created particle.
  52033. * @param worldMatrix is the world matrix of the particle system
  52034. * @param positionToUpdate is the position vector to update with the result
  52035. * @param particle is the particle we are computed the position for
  52036. */
  52037. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52038. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52039. var h = BABYLON.Scalar.RandomRange(0, 1);
  52040. // Better distribution in a cone at normal angles.
  52041. h = 1 - h * h;
  52042. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52043. radius = radius * h / this._height;
  52044. var randX = radius * Math.sin(s);
  52045. var randZ = radius * Math.cos(s);
  52046. var randY = h * this._height;
  52047. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52048. };
  52049. /**
  52050. * Clones the current emitter and returns a copy of it
  52051. * @returns the new emitter
  52052. */
  52053. ConeParticleEmitter.prototype.clone = function () {
  52054. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52055. BABYLON.Tools.DeepCopy(this, newOne);
  52056. return newOne;
  52057. };
  52058. /**
  52059. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52060. * @param effect defines the update shader
  52061. */
  52062. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52063. effect.setFloat("radius", this.radius);
  52064. effect.setFloat("angle", this.angle);
  52065. effect.setFloat("height", this._height);
  52066. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52067. };
  52068. /**
  52069. * Returns a string to use to update the GPU particles update shader
  52070. * @returns a string containng the defines string
  52071. */
  52072. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52073. return "#define CONEEMITTER";
  52074. };
  52075. /**
  52076. * Returns the string "BoxEmitter"
  52077. * @returns a string containing the class name
  52078. */
  52079. ConeParticleEmitter.prototype.getClassName = function () {
  52080. return "ConeEmitter";
  52081. };
  52082. /**
  52083. * Serializes the particle system to a JSON object.
  52084. * @returns the JSON object
  52085. */
  52086. ConeParticleEmitter.prototype.serialize = function () {
  52087. var serializationObject = {};
  52088. serializationObject.type = this.getClassName();
  52089. serializationObject.radius = this.radius;
  52090. serializationObject.angle = this.angle;
  52091. serializationObject.directionRandomizer = this.directionRandomizer;
  52092. return serializationObject;
  52093. };
  52094. /**
  52095. * Parse properties from a JSON object
  52096. * @param serializationObject defines the JSON object
  52097. */
  52098. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52099. this.radius = serializationObject.radius;
  52100. this.angle = serializationObject.angle;
  52101. this.directionRandomizer = serializationObject.directionRandomizer;
  52102. };
  52103. return ConeParticleEmitter;
  52104. }());
  52105. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52106. })(BABYLON || (BABYLON = {}));
  52107. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52108. var BABYLON;
  52109. (function (BABYLON) {
  52110. /**
  52111. * Particle emitter emitting particles from the inside of a sphere.
  52112. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52113. */
  52114. var SphereParticleEmitter = /** @class */ (function () {
  52115. /**
  52116. * Creates a new instance of @see SphereParticleEmitter
  52117. * @param radius the radius of the emission sphere (1 by default)
  52118. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52119. */
  52120. function SphereParticleEmitter(
  52121. /**
  52122. * The radius of the emission sphere.
  52123. */
  52124. radius,
  52125. /**
  52126. * How much to randomize the particle direction [0-1].
  52127. */
  52128. directionRandomizer) {
  52129. if (radius === void 0) { radius = 1; }
  52130. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52131. this.radius = radius;
  52132. this.directionRandomizer = directionRandomizer;
  52133. }
  52134. /**
  52135. * Called by the particle System when the direction is computed for the created particle.
  52136. * @param emitPower is the power of the particle (speed)
  52137. * @param worldMatrix is the world matrix of the particle system
  52138. * @param directionToUpdate is the direction vector to update with the result
  52139. * @param particle is the particle we are computed the direction for
  52140. */
  52141. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52142. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52143. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52144. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52145. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52146. direction.x += randX;
  52147. direction.y += randY;
  52148. direction.z += randZ;
  52149. direction.normalize();
  52150. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52151. };
  52152. /**
  52153. * Called by the particle System when the position is computed for the created particle.
  52154. * @param worldMatrix is the world matrix of the particle system
  52155. * @param positionToUpdate is the position vector to update with the result
  52156. * @param particle is the particle we are computed the position for
  52157. */
  52158. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52159. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52160. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52161. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52162. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52163. var randY = randRadius * Math.cos(theta);
  52164. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52166. };
  52167. /**
  52168. * Clones the current emitter and returns a copy of it
  52169. * @returns the new emitter
  52170. */
  52171. SphereParticleEmitter.prototype.clone = function () {
  52172. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52173. BABYLON.Tools.DeepCopy(this, newOne);
  52174. return newOne;
  52175. };
  52176. /**
  52177. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52178. * @param effect defines the update shader
  52179. */
  52180. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52181. effect.setFloat("radius", this.radius);
  52182. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52183. };
  52184. /**
  52185. * Returns a string to use to update the GPU particles update shader
  52186. * @returns a string containng the defines string
  52187. */
  52188. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52189. return "#define SPHEREEMITTER";
  52190. };
  52191. /**
  52192. * Returns the string "SphereParticleEmitter"
  52193. * @returns a string containing the class name
  52194. */
  52195. SphereParticleEmitter.prototype.getClassName = function () {
  52196. return "SphereParticleEmitter";
  52197. };
  52198. /**
  52199. * Serializes the particle system to a JSON object.
  52200. * @returns the JSON object
  52201. */
  52202. SphereParticleEmitter.prototype.serialize = function () {
  52203. var serializationObject = {};
  52204. serializationObject.type = this.getClassName();
  52205. serializationObject.radius = this.radius;
  52206. serializationObject.directionRandomizer = this.directionRandomizer;
  52207. return serializationObject;
  52208. };
  52209. /**
  52210. * Parse properties from a JSON object
  52211. * @param serializationObject defines the JSON object
  52212. */
  52213. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52214. this.radius = serializationObject.radius;
  52215. this.directionRandomizer = serializationObject.directionRandomizer;
  52216. };
  52217. return SphereParticleEmitter;
  52218. }());
  52219. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52220. /**
  52221. * Particle emitter emitting particles from the inside of a sphere.
  52222. * It emits the particles randomly between two vectors.
  52223. */
  52224. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52225. __extends(SphereDirectedParticleEmitter, _super);
  52226. /**
  52227. * Creates a new instance of @see SphereDirectedParticleEmitter
  52228. * @param radius the radius of the emission sphere (1 by default)
  52229. * @param direction1 the min limit of the emission direction (up vector by default)
  52230. * @param direction2 the max limit of the emission direction (up vector by default)
  52231. */
  52232. function SphereDirectedParticleEmitter(radius,
  52233. /**
  52234. * The min limit of the emission direction.
  52235. */
  52236. direction1,
  52237. /**
  52238. * The max limit of the emission direction.
  52239. */
  52240. direction2) {
  52241. if (radius === void 0) { radius = 1; }
  52242. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52243. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52244. var _this = _super.call(this, radius) || this;
  52245. _this.direction1 = direction1;
  52246. _this.direction2 = direction2;
  52247. return _this;
  52248. }
  52249. /**
  52250. * Called by the particle System when the direction is computed for the created particle.
  52251. * @param emitPower is the power of the particle (speed)
  52252. * @param worldMatrix is the world matrix of the particle system
  52253. * @param directionToUpdate is the direction vector to update with the result
  52254. * @param particle is the particle we are computed the direction for
  52255. */
  52256. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52257. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52258. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52259. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52260. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52261. };
  52262. /**
  52263. * Clones the current emitter and returns a copy of it
  52264. * @returns the new emitter
  52265. */
  52266. SphereDirectedParticleEmitter.prototype.clone = function () {
  52267. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52268. BABYLON.Tools.DeepCopy(this, newOne);
  52269. return newOne;
  52270. };
  52271. /**
  52272. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52273. * @param effect defines the update shader
  52274. */
  52275. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52276. effect.setFloat("radius", this.radius);
  52277. effect.setVector3("direction1", this.direction1);
  52278. effect.setVector3("direction2", this.direction2);
  52279. };
  52280. /**
  52281. * Returns a string to use to update the GPU particles update shader
  52282. * @returns a string containng the defines string
  52283. */
  52284. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52285. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52286. };
  52287. /**
  52288. * Returns the string "SphereDirectedParticleEmitter"
  52289. * @returns a string containing the class name
  52290. */
  52291. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52292. return "SphereDirectedParticleEmitter";
  52293. };
  52294. /**
  52295. * Serializes the particle system to a JSON object.
  52296. * @returns the JSON object
  52297. */
  52298. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52299. var serializationObject = _super.prototype.serialize.call(this);
  52300. ;
  52301. serializationObject.direction1 = this.direction1.asArray();
  52302. ;
  52303. serializationObject.direction2 = this.direction2.asArray();
  52304. ;
  52305. return serializationObject;
  52306. };
  52307. /**
  52308. * Parse properties from a JSON object
  52309. * @param serializationObject defines the JSON object
  52310. */
  52311. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52312. _super.prototype.parse.call(this, serializationObject);
  52313. this.direction1.copyFrom(serializationObject.direction1);
  52314. this.direction2.copyFrom(serializationObject.direction2);
  52315. };
  52316. return SphereDirectedParticleEmitter;
  52317. }(SphereParticleEmitter));
  52318. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52319. })(BABYLON || (BABYLON = {}));
  52320. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52321. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52322. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52323. s = arguments[i];
  52324. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52325. t[p] = s[p];
  52326. }
  52327. return t;
  52328. };
  52329. var BABYLON;
  52330. (function (BABYLON) {
  52331. /**
  52332. * This represents a GPU particle system in Babylon
  52333. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52334. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52335. */
  52336. var GPUParticleSystem = /** @class */ (function () {
  52337. /**
  52338. * Instantiates a GPU particle system.
  52339. * 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.
  52340. * @param name The name of the particle system
  52341. * @param capacity The max number of particles alive at the same time
  52342. * @param scene The scene the particle system belongs to
  52343. */
  52344. function GPUParticleSystem(name, options, scene) {
  52345. /**
  52346. * The emitter represents the Mesh or position we are attaching the particle system to.
  52347. */
  52348. this.emitter = null;
  52349. /**
  52350. * The rendering group used by the Particle system to chose when to render.
  52351. */
  52352. this.renderingGroupId = 0;
  52353. /**
  52354. * The layer mask we are rendering the particles through.
  52355. */
  52356. this.layerMask = 0x0FFFFFFF;
  52357. this._targetIndex = 0;
  52358. this._currentRenderId = -1;
  52359. this._started = false;
  52360. this._stopped = false;
  52361. this._timeDelta = 0;
  52362. this._attributesStrideSize = 14;
  52363. this._actualFrame = 0;
  52364. /**
  52365. * List of animations used by the particle system.
  52366. */
  52367. this.animations = [];
  52368. /**
  52369. * An event triggered when the system is disposed.
  52370. */
  52371. this.onDisposeObservable = new BABYLON.Observable();
  52372. /**
  52373. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52374. */
  52375. this.updateSpeed = 0.01;
  52376. /**
  52377. * The amount of time the particle system is running (depends of the overall update speed).
  52378. */
  52379. this.targetStopDuration = 0;
  52380. /**
  52381. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52382. */
  52383. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52384. /**
  52385. * Minimum life time of emitting particles.
  52386. */
  52387. this.minLifeTime = 1;
  52388. /**
  52389. * Maximum life time of emitting particles.
  52390. */
  52391. this.maxLifeTime = 1;
  52392. /**
  52393. * Minimum Size of emitting particles.
  52394. */
  52395. this.minSize = 1;
  52396. /**
  52397. * Maximum Size of emitting particles.
  52398. */
  52399. this.maxSize = 1;
  52400. /**
  52401. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52402. */
  52403. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52404. /**
  52405. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52406. */
  52407. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52408. /**
  52409. * Color the particle will have at the end of its lifetime.
  52410. */
  52411. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52412. /**
  52413. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52414. */
  52415. this.emitRate = 100;
  52416. /**
  52417. * You can use gravity if you want to give an orientation to your particles.
  52418. */
  52419. this.gravity = BABYLON.Vector3.Zero();
  52420. /**
  52421. * Minimum power of emitting particles.
  52422. */
  52423. this.minEmitPower = 1;
  52424. /**
  52425. * Maximum power of emitting particles.
  52426. */
  52427. this.maxEmitPower = 1;
  52428. /**
  52429. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52430. * to override the particles.
  52431. */
  52432. this.forceDepthWrite = false;
  52433. this.id = name;
  52434. this.name = name;
  52435. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52436. this._engine = this._scene.getEngine();
  52437. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52438. this._capacity = fullOptions.capacity;
  52439. this._activeCount = fullOptions.capacity;
  52440. this._currentActiveCount = 0;
  52441. this._scene.particleSystems.push(this);
  52442. this._updateEffectOptions = {
  52443. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52444. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52445. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52446. uniformBuffersNames: [],
  52447. samplers: ["randomSampler"],
  52448. defines: "",
  52449. fallbacks: null,
  52450. onCompiled: null,
  52451. onError: null,
  52452. indexParameters: null,
  52453. maxSimultaneousLights: 0,
  52454. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52455. };
  52456. // Random data
  52457. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52458. var d = [];
  52459. for (var i = 0; i < maxTextureSize; ++i) {
  52460. d.push(Math.random());
  52461. d.push(Math.random());
  52462. d.push(Math.random());
  52463. d.push(Math.random());
  52464. }
  52465. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52466. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52467. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52468. this._randomTextureSize = maxTextureSize;
  52469. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52470. }
  52471. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52472. /**
  52473. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52474. */
  52475. get: function () {
  52476. if (!BABYLON.Engine.LastCreatedEngine) {
  52477. return false;
  52478. }
  52479. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52485. /**
  52486. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52487. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52488. */
  52489. get: function () {
  52490. if (this.particleEmitterType.direction1) {
  52491. return this.particleEmitterType.direction1;
  52492. }
  52493. return BABYLON.Vector3.Zero();
  52494. },
  52495. set: function (value) {
  52496. if (this.particleEmitterType.direction1) {
  52497. this.particleEmitterType.direction1 = value;
  52498. }
  52499. },
  52500. enumerable: true,
  52501. configurable: true
  52502. });
  52503. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52504. /**
  52505. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52506. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52507. */
  52508. get: function () {
  52509. if (this.particleEmitterType.direction2) {
  52510. return this.particleEmitterType.direction2;
  52511. }
  52512. return BABYLON.Vector3.Zero();
  52513. },
  52514. set: function (value) {
  52515. if (this.particleEmitterType.direction2) {
  52516. this.particleEmitterType.direction2 = value;
  52517. }
  52518. },
  52519. enumerable: true,
  52520. configurable: true
  52521. });
  52522. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52523. /**
  52524. * 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.
  52525. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52526. */
  52527. get: function () {
  52528. if (this.particleEmitterType.minEmitBox) {
  52529. return this.particleEmitterType.minEmitBox;
  52530. }
  52531. return BABYLON.Vector3.Zero();
  52532. },
  52533. set: function (value) {
  52534. if (this.particleEmitterType.minEmitBox) {
  52535. this.particleEmitterType.minEmitBox = value;
  52536. }
  52537. },
  52538. enumerable: true,
  52539. configurable: true
  52540. });
  52541. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52542. /**
  52543. * 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.
  52544. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52545. */
  52546. get: function () {
  52547. if (this.particleEmitterType.maxEmitBox) {
  52548. return this.particleEmitterType.maxEmitBox;
  52549. }
  52550. return BABYLON.Vector3.Zero();
  52551. },
  52552. set: function (value) {
  52553. if (this.particleEmitterType.maxEmitBox) {
  52554. this.particleEmitterType.maxEmitBox = value;
  52555. }
  52556. },
  52557. enumerable: true,
  52558. configurable: true
  52559. });
  52560. /**
  52561. * Gets the maximum number of particles active at the same time.
  52562. * @returns The max number of active particles.
  52563. */
  52564. GPUParticleSystem.prototype.getCapacity = function () {
  52565. return this._capacity;
  52566. };
  52567. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52568. /**
  52569. * Gets or set the number of active particles
  52570. */
  52571. get: function () {
  52572. return this._activeCount;
  52573. },
  52574. set: function (value) {
  52575. this._activeCount = Math.min(value, this._capacity);
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. /**
  52581. * Gets Wether the system has been started.
  52582. * @returns True if it has been started, otherwise false.
  52583. */
  52584. GPUParticleSystem.prototype.isStarted = function () {
  52585. return this._started;
  52586. };
  52587. /**
  52588. * Starts the particle system and begins to emit.
  52589. */
  52590. GPUParticleSystem.prototype.start = function () {
  52591. this._started = true;
  52592. this._stopped = false;
  52593. };
  52594. /**
  52595. * Stops the particle system.
  52596. */
  52597. GPUParticleSystem.prototype.stop = function () {
  52598. this._stopped = true;
  52599. };
  52600. /**
  52601. * Remove all active particles
  52602. */
  52603. GPUParticleSystem.prototype.reset = function () {
  52604. this._releaseBuffers();
  52605. this._releaseVAOs();
  52606. this._currentActiveCount = 0;
  52607. this._targetIndex = 0;
  52608. };
  52609. /**
  52610. * Returns the string "GPUParticleSystem"
  52611. * @returns a string containing the class name
  52612. */
  52613. GPUParticleSystem.prototype.getClassName = function () {
  52614. return "GPUParticleSystem";
  52615. };
  52616. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52617. var updateVertexBuffers = {};
  52618. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52619. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52620. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52621. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52622. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52623. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52624. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52625. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52626. this._engine.bindArrayBuffer(null);
  52627. return vao;
  52628. };
  52629. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52630. var renderVertexBuffers = {};
  52631. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52632. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52633. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52634. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52635. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52636. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52637. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52638. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52639. this._engine.bindArrayBuffer(null);
  52640. return vao;
  52641. };
  52642. GPUParticleSystem.prototype._initialize = function (force) {
  52643. if (force === void 0) { force = false; }
  52644. if (this._buffer0 && !force) {
  52645. return;
  52646. }
  52647. var engine = this._scene.getEngine();
  52648. var data = new Array();
  52649. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52650. // position
  52651. data.push(0.0);
  52652. data.push(0.0);
  52653. data.push(0.0);
  52654. // Age and life
  52655. data.push(0.0); // create the particle as a dead one to create a new one at start
  52656. data.push(0.0);
  52657. // Seed
  52658. data.push(Math.random());
  52659. // Size
  52660. data.push(0.0);
  52661. // color
  52662. data.push(0.0);
  52663. data.push(0.0);
  52664. data.push(0.0);
  52665. data.push(0.0);
  52666. // direction
  52667. data.push(0.0);
  52668. data.push(0.0);
  52669. data.push(0.0);
  52670. }
  52671. // Sprite data
  52672. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52673. -0.5, 0.5, 0, 1,
  52674. -0.5, -0.5, 0, 0,
  52675. 0.5, -0.5, 1, 0]);
  52676. // Buffers
  52677. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52678. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52679. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52680. // Update VAO
  52681. this._updateVAO = [];
  52682. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52683. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52684. // Render VAO
  52685. this._renderVAO = [];
  52686. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52687. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52688. // Links
  52689. this._sourceBuffer = this._buffer0;
  52690. this._targetBuffer = this._buffer1;
  52691. };
  52692. /** @ignore */
  52693. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52694. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52695. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52696. return;
  52697. }
  52698. this._updateEffectOptions.defines = defines;
  52699. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52700. };
  52701. /** @ignore */
  52702. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52703. var defines = "";
  52704. if (this._scene.clipPlane) {
  52705. defines = "\n#define CLIPPLANE";
  52706. }
  52707. if (this._renderEffect && this._renderEffect.defines === defines) {
  52708. return;
  52709. }
  52710. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52711. };
  52712. /**
  52713. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52714. */
  52715. GPUParticleSystem.prototype.animate = function () {
  52716. if (!this._stopped) {
  52717. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52718. this._actualFrame += this._timeDelta;
  52719. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52720. this.stop();
  52721. }
  52722. };
  52723. /**
  52724. * Renders the particle system in its current state.
  52725. * @returns the current number of particles
  52726. */
  52727. GPUParticleSystem.prototype.render = function () {
  52728. if (!this._started) {
  52729. return 0;
  52730. }
  52731. this._recreateUpdateEffect();
  52732. this._recreateRenderEffect();
  52733. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52734. return 0;
  52735. }
  52736. if (this._currentRenderId === this._scene.getRenderId()) {
  52737. return 0;
  52738. }
  52739. this._currentRenderId = this._scene.getRenderId();
  52740. // Get everything ready to render
  52741. this._initialize();
  52742. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52743. // Enable update effect
  52744. this._engine.enableEffect(this._updateEffect);
  52745. this._engine.setState(false);
  52746. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52747. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52748. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52749. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52750. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52751. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52752. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52753. this._updateEffect.setDirectColor4("color1", this.color1);
  52754. this._updateEffect.setDirectColor4("color2", this.color2);
  52755. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52756. this._updateEffect.setVector3("gravity", this.gravity);
  52757. if (this.particleEmitterType) {
  52758. this.particleEmitterType.applyToShader(this._updateEffect);
  52759. }
  52760. var emitterWM;
  52761. if (this.emitter.position) {
  52762. var emitterMesh = this.emitter;
  52763. emitterWM = emitterMesh.getWorldMatrix();
  52764. }
  52765. else {
  52766. var emitterPosition = this.emitter;
  52767. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52768. }
  52769. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52770. // Bind source VAO
  52771. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52772. // Update
  52773. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52774. this._engine.setRasterizerState(false);
  52775. this._engine.beginTransformFeedback();
  52776. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52777. this._engine.endTransformFeedback();
  52778. this._engine.setRasterizerState(true);
  52779. this._engine.bindTransformFeedbackBuffer(null);
  52780. // Enable render effect
  52781. this._engine.enableEffect(this._renderEffect);
  52782. var viewMatrix = this._scene.getViewMatrix();
  52783. this._renderEffect.setMatrix("view", viewMatrix);
  52784. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52785. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52786. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52787. if (this._scene.clipPlane) {
  52788. var clipPlane = this._scene.clipPlane;
  52789. var invView = viewMatrix.clone();
  52790. invView.invert();
  52791. this._renderEffect.setMatrix("invView", invView);
  52792. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52793. }
  52794. // Draw order
  52795. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52796. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52797. }
  52798. else {
  52799. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52800. }
  52801. if (this.forceDepthWrite) {
  52802. this._engine.setDepthWrite(true);
  52803. }
  52804. // Bind source VAO
  52805. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52806. // Render
  52807. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52808. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52809. // Switch VAOs
  52810. this._targetIndex++;
  52811. if (this._targetIndex === 2) {
  52812. this._targetIndex = 0;
  52813. }
  52814. // Switch buffers
  52815. var tmpBuffer = this._sourceBuffer;
  52816. this._sourceBuffer = this._targetBuffer;
  52817. this._targetBuffer = tmpBuffer;
  52818. return this._currentActiveCount;
  52819. };
  52820. /**
  52821. * Rebuilds the particle system
  52822. */
  52823. GPUParticleSystem.prototype.rebuild = function () {
  52824. this._initialize(true);
  52825. };
  52826. GPUParticleSystem.prototype._releaseBuffers = function () {
  52827. if (this._buffer0) {
  52828. this._buffer0.dispose();
  52829. this._buffer0 = null;
  52830. }
  52831. if (this._buffer1) {
  52832. this._buffer1.dispose();
  52833. this._buffer1 = null;
  52834. }
  52835. if (this._spriteBuffer) {
  52836. this._spriteBuffer.dispose();
  52837. this._spriteBuffer = null;
  52838. }
  52839. };
  52840. GPUParticleSystem.prototype._releaseVAOs = function () {
  52841. if (!this._updateVAO) {
  52842. return;
  52843. }
  52844. for (var index = 0; index < this._updateVAO.length; index++) {
  52845. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52846. }
  52847. this._updateVAO = [];
  52848. for (var index = 0; index < this._renderVAO.length; index++) {
  52849. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52850. }
  52851. this._renderVAO = [];
  52852. };
  52853. /**
  52854. * Disposes the particle system and free the associated resources
  52855. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52856. */
  52857. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52858. if (disposeTexture === void 0) { disposeTexture = true; }
  52859. var index = this._scene.particleSystems.indexOf(this);
  52860. if (index > -1) {
  52861. this._scene.particleSystems.splice(index, 1);
  52862. }
  52863. this._releaseBuffers();
  52864. this._releaseVAOs();
  52865. if (this._randomTexture) {
  52866. this._randomTexture.dispose();
  52867. this._randomTexture = null;
  52868. }
  52869. if (disposeTexture && this.particleTexture) {
  52870. this.particleTexture.dispose();
  52871. this.particleTexture = null;
  52872. }
  52873. // Callback
  52874. this.onDisposeObservable.notifyObservers(this);
  52875. this.onDisposeObservable.clear();
  52876. };
  52877. /**
  52878. * Clones the particle system.
  52879. * @param name The name of the cloned object
  52880. * @param newEmitter The new emitter to use
  52881. * @returns the cloned particle system
  52882. */
  52883. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52884. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52885. BABYLON.Tools.DeepCopy(this, result);
  52886. if (newEmitter === undefined) {
  52887. newEmitter = this.emitter;
  52888. }
  52889. result.emitter = newEmitter;
  52890. if (this.particleTexture) {
  52891. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52892. }
  52893. return result;
  52894. };
  52895. /**
  52896. * Serializes the particle system to a JSON object.
  52897. * @returns the JSON object
  52898. */
  52899. GPUParticleSystem.prototype.serialize = function () {
  52900. var serializationObject = {};
  52901. serializationObject.name = this.name;
  52902. serializationObject.id = this.id;
  52903. // Emitter
  52904. if (this.emitter.position) {
  52905. var emitterMesh = this.emitter;
  52906. serializationObject.emitterId = emitterMesh.id;
  52907. }
  52908. else {
  52909. var emitterPosition = this.emitter;
  52910. serializationObject.emitter = emitterPosition.asArray();
  52911. }
  52912. serializationObject.capacity = this.getCapacity();
  52913. if (this.particleTexture) {
  52914. serializationObject.textureName = this.particleTexture.name;
  52915. }
  52916. // Animations
  52917. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52918. // Particle system
  52919. serializationObject.activeParticleCount = this.activeParticleCount;
  52920. serializationObject.randomTextureSize = this._randomTextureSize;
  52921. serializationObject.minSize = this.minSize;
  52922. serializationObject.maxSize = this.maxSize;
  52923. serializationObject.minEmitPower = this.minEmitPower;
  52924. serializationObject.maxEmitPower = this.maxEmitPower;
  52925. serializationObject.minLifeTime = this.minLifeTime;
  52926. serializationObject.maxLifeTime = this.maxLifeTime;
  52927. serializationObject.emitRate = this.emitRate;
  52928. serializationObject.gravity = this.gravity.asArray();
  52929. serializationObject.color1 = this.color1.asArray();
  52930. serializationObject.color2 = this.color2.asArray();
  52931. serializationObject.colorDead = this.colorDead.asArray();
  52932. serializationObject.updateSpeed = this.updateSpeed;
  52933. serializationObject.targetStopDuration = this.targetStopDuration;
  52934. serializationObject.blendMode = this.blendMode;
  52935. // Emitter
  52936. if (this.particleEmitterType) {
  52937. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52938. }
  52939. return serializationObject;
  52940. };
  52941. /**
  52942. * Parses a JSON object to create a GPU particle system.
  52943. * @param parsedParticleSystem The JSON object to parse
  52944. * @param scene The scene to create the particle system in
  52945. * @param rootUrl The root url to use to load external dependencies like texture
  52946. * @returns the parsed GPU particle system
  52947. */
  52948. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52949. var name = parsedParticleSystem.name;
  52950. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52951. if (parsedParticleSystem.id) {
  52952. particleSystem.id = parsedParticleSystem.id;
  52953. }
  52954. // Texture
  52955. if (parsedParticleSystem.textureName) {
  52956. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52957. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52958. }
  52959. // Emitter
  52960. if (parsedParticleSystem.emitterId) {
  52961. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52962. }
  52963. else {
  52964. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52965. }
  52966. // Animations
  52967. if (parsedParticleSystem.animations) {
  52968. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52969. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52970. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52971. }
  52972. }
  52973. // Particle system
  52974. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52975. particleSystem.minSize = parsedParticleSystem.minSize;
  52976. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52977. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52978. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52979. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52980. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52981. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52982. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52983. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52984. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52985. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52986. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52987. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52988. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52989. // Emitter
  52990. if (parsedParticleSystem.particleEmitterType) {
  52991. var emitterType = void 0;
  52992. switch (parsedParticleSystem.particleEmitterType.type) {
  52993. case "SphereEmitter":
  52994. emitterType = new BABYLON.SphereParticleEmitter();
  52995. break;
  52996. case "SphereDirectedParticleEmitter":
  52997. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52998. break;
  52999. case "ConeEmitter":
  53000. emitterType = new BABYLON.ConeParticleEmitter();
  53001. break;
  53002. case "BoxEmitter":
  53003. default:
  53004. emitterType = new BABYLON.BoxParticleEmitter();
  53005. break;
  53006. }
  53007. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53008. particleSystem.particleEmitterType = emitterType;
  53009. }
  53010. return particleSystem;
  53011. };
  53012. return GPUParticleSystem;
  53013. }());
  53014. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53015. })(BABYLON || (BABYLON = {}));
  53016. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53017. var BABYLON;
  53018. (function (BABYLON) {
  53019. /**
  53020. * Represents one particle of a solid particle system.
  53021. * @see SolidParticleSystem
  53022. */
  53023. var SolidParticle = /** @class */ (function () {
  53024. /**
  53025. * Creates a Solid Particle object.
  53026. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53027. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53028. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53029. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53030. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53031. * @param shapeId (integer) is the model shape identifier in the SPS.
  53032. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53033. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53034. */
  53035. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53036. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53037. /**
  53038. * particle global index
  53039. */
  53040. this.idx = 0;
  53041. /**
  53042. * The color of the particle
  53043. */
  53044. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53045. /**
  53046. * The world space position of the particle.
  53047. */
  53048. this.position = BABYLON.Vector3.Zero();
  53049. /**
  53050. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53051. */
  53052. this.rotation = BABYLON.Vector3.Zero();
  53053. /**
  53054. * The scaling of the particle.
  53055. */
  53056. this.scaling = BABYLON.Vector3.One();
  53057. /**
  53058. * The uvs of the particle.
  53059. */
  53060. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53061. /**
  53062. * The current speed of the particle.
  53063. */
  53064. this.velocity = BABYLON.Vector3.Zero();
  53065. /**
  53066. * The pivot point in the particle local space.
  53067. */
  53068. this.pivot = BABYLON.Vector3.Zero();
  53069. /**
  53070. * Must the particle be translated from its pivot point in its local space ?
  53071. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53072. * Default : false
  53073. */
  53074. this.translateFromPivot = false;
  53075. /**
  53076. * Is the particle active or not ?
  53077. */
  53078. this.alive = true;
  53079. /**
  53080. * Is the particle visible or not ?
  53081. */
  53082. this.isVisible = true;
  53083. /**
  53084. * Index of this particle in the global "positions" array (Internal use)
  53085. */
  53086. this._pos = 0;
  53087. /**
  53088. * Index of this particle in the global "indices" array (Internal use)
  53089. */
  53090. this._ind = 0;
  53091. /**
  53092. * ModelShape id of this particle
  53093. */
  53094. this.shapeId = 0;
  53095. /**
  53096. * Index of the particle in its shape id (Internal use)
  53097. */
  53098. this.idxInShape = 0;
  53099. /**
  53100. * Still set as invisible in order to skip useless computations (Internal use)
  53101. */
  53102. this._stillInvisible = false;
  53103. /**
  53104. * Last computed particle rotation matrix
  53105. */
  53106. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53107. /**
  53108. * Parent particle Id, if any.
  53109. * Default null.
  53110. */
  53111. this.parentId = null;
  53112. /**
  53113. * Internal global position in the SPS.
  53114. */
  53115. this._globalPosition = BABYLON.Vector3.Zero();
  53116. this.idx = particleIndex;
  53117. this._pos = positionIndex;
  53118. this._ind = indiceIndex;
  53119. this._model = model;
  53120. this.shapeId = shapeId;
  53121. this.idxInShape = idxInShape;
  53122. this._sps = sps;
  53123. if (modelBoundingInfo) {
  53124. this._modelBoundingInfo = modelBoundingInfo;
  53125. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53126. }
  53127. }
  53128. Object.defineProperty(SolidParticle.prototype, "scale", {
  53129. /**
  53130. * Legacy support, changed scale to scaling
  53131. */
  53132. get: function () {
  53133. return this.scaling;
  53134. },
  53135. /**
  53136. * Legacy support, changed scale to scaling
  53137. */
  53138. set: function (scale) {
  53139. this.scaling = scale;
  53140. },
  53141. enumerable: true,
  53142. configurable: true
  53143. });
  53144. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53145. /**
  53146. * Legacy support, changed quaternion to rotationQuaternion
  53147. */
  53148. get: function () {
  53149. return this.rotationQuaternion;
  53150. },
  53151. /**
  53152. * Legacy support, changed quaternion to rotationQuaternion
  53153. */
  53154. set: function (q) {
  53155. this.rotationQuaternion = q;
  53156. },
  53157. enumerable: true,
  53158. configurable: true
  53159. });
  53160. /**
  53161. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53162. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53163. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53164. * @returns true if it intersects
  53165. */
  53166. SolidParticle.prototype.intersectsMesh = function (target) {
  53167. if (!this._boundingInfo || !target._boundingInfo) {
  53168. return false;
  53169. }
  53170. if (this._sps._bSphereOnly) {
  53171. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53172. }
  53173. return this._boundingInfo.intersects(target._boundingInfo, false);
  53174. };
  53175. return SolidParticle;
  53176. }());
  53177. BABYLON.SolidParticle = SolidParticle;
  53178. /**
  53179. * Represents the shape of the model used by one particle of a solid particle system.
  53180. * SPS internal tool, don't use it manually.
  53181. * @see SolidParticleSystem
  53182. */
  53183. var ModelShape = /** @class */ (function () {
  53184. /**
  53185. * 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.
  53186. * SPS internal tool, don't use it manually.
  53187. * @ignore
  53188. */
  53189. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53190. /**
  53191. * length of the shape in the model indices array (internal use)
  53192. */
  53193. this._indicesLength = 0;
  53194. this.shapeID = id;
  53195. this._shape = shape;
  53196. this._indicesLength = indicesLength;
  53197. this._shapeUV = shapeUV;
  53198. this._positionFunction = posFunction;
  53199. this._vertexFunction = vtxFunction;
  53200. }
  53201. return ModelShape;
  53202. }());
  53203. BABYLON.ModelShape = ModelShape;
  53204. /**
  53205. * Represents a Depth Sorted Particle in the solid particle system.
  53206. * @see SolidParticleSystem
  53207. */
  53208. var DepthSortedParticle = /** @class */ (function () {
  53209. function DepthSortedParticle() {
  53210. /**
  53211. * Index of the particle in the "indices" array
  53212. */
  53213. this.ind = 0;
  53214. /**
  53215. * Length of the particle shape in the "indices" array
  53216. */
  53217. this.indicesLength = 0;
  53218. /**
  53219. * Squared distance from the particle to the camera
  53220. */
  53221. this.sqDistance = 0.0;
  53222. }
  53223. return DepthSortedParticle;
  53224. }());
  53225. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53226. })(BABYLON || (BABYLON = {}));
  53227. //# sourceMappingURL=babylon.solidParticle.js.map
  53228. var BABYLON;
  53229. (function (BABYLON) {
  53230. /**
  53231. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53232. *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.
  53233. * The SPS is also a particle system. It provides some methods to manage the particles.
  53234. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53235. *
  53236. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53237. */
  53238. var SolidParticleSystem = /** @class */ (function () {
  53239. /**
  53240. * Creates a SPS (Solid Particle System) object.
  53241. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53242. * @param scene (Scene) is the scene in which the SPS is added.
  53243. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53244. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53245. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53246. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53247. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53248. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53249. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53250. */
  53251. function SolidParticleSystem(name, scene, options) {
  53252. /**
  53253. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53254. * Example : var p = SPS.particles[i];
  53255. */
  53256. this.particles = new Array();
  53257. /**
  53258. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53259. */
  53260. this.nbParticles = 0;
  53261. /**
  53262. * If the particles must ever face the camera (default false). Useful for planar particles.
  53263. */
  53264. this.billboard = false;
  53265. /**
  53266. * Recompute normals when adding a shape
  53267. */
  53268. this.recomputeNormals = true;
  53269. /**
  53270. * This a counter ofr your own usage. It's not set by any SPS functions.
  53271. */
  53272. this.counter = 0;
  53273. /**
  53274. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53275. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53276. */
  53277. this.vars = {};
  53278. /**
  53279. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53280. */
  53281. this._bSphereOnly = false;
  53282. /**
  53283. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53284. */
  53285. this._bSphereRadiusFactor = 1.0;
  53286. this._positions = new Array();
  53287. this._indices = new Array();
  53288. this._normals = new Array();
  53289. this._colors = new Array();
  53290. this._uvs = new Array();
  53291. this._index = 0; // indices index
  53292. this._updatable = true;
  53293. this._pickable = false;
  53294. this._isVisibilityBoxLocked = false;
  53295. this._alwaysVisible = false;
  53296. this._depthSort = false;
  53297. this._shapeCounter = 0;
  53298. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53299. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53300. this._computeParticleColor = true;
  53301. this._computeParticleTexture = true;
  53302. this._computeParticleRotation = true;
  53303. this._computeParticleVertex = false;
  53304. this._computeBoundingBox = false;
  53305. this._depthSortParticles = true;
  53306. this._cam_axisZ = BABYLON.Vector3.Zero();
  53307. this._cam_axisY = BABYLON.Vector3.Zero();
  53308. this._cam_axisX = BABYLON.Vector3.Zero();
  53309. this._axisZ = BABYLON.Axis.Z;
  53310. this._camDir = BABYLON.Vector3.Zero();
  53311. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53312. this._rotMatrix = new BABYLON.Matrix();
  53313. this._invertMatrix = new BABYLON.Matrix();
  53314. this._rotated = BABYLON.Vector3.Zero();
  53315. this._quaternion = new BABYLON.Quaternion();
  53316. this._vertex = BABYLON.Vector3.Zero();
  53317. this._normal = BABYLON.Vector3.Zero();
  53318. this._yaw = 0.0;
  53319. this._pitch = 0.0;
  53320. this._roll = 0.0;
  53321. this._halfroll = 0.0;
  53322. this._halfpitch = 0.0;
  53323. this._halfyaw = 0.0;
  53324. this._sinRoll = 0.0;
  53325. this._cosRoll = 0.0;
  53326. this._sinPitch = 0.0;
  53327. this._cosPitch = 0.0;
  53328. this._sinYaw = 0.0;
  53329. this._cosYaw = 0.0;
  53330. this._mustUnrotateFixedNormals = false;
  53331. this._minimum = BABYLON.Vector3.Zero();
  53332. this._maximum = BABYLON.Vector3.Zero();
  53333. this._minBbox = BABYLON.Vector3.Zero();
  53334. this._maxBbox = BABYLON.Vector3.Zero();
  53335. this._particlesIntersect = false;
  53336. this._depthSortFunction = function (p1, p2) {
  53337. return (p2.sqDistance - p1.sqDistance);
  53338. };
  53339. this._needs32Bits = false;
  53340. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53341. this._scaledPivot = BABYLON.Vector3.Zero();
  53342. this._particleHasParent = false;
  53343. this.name = name;
  53344. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53345. this._camera = scene.activeCamera;
  53346. this._pickable = options ? options.isPickable : false;
  53347. this._depthSort = options ? options.enableDepthSort : false;
  53348. this._particlesIntersect = options ? options.particleIntersection : false;
  53349. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53350. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53351. if (options && options.updatable) {
  53352. this._updatable = options.updatable;
  53353. }
  53354. else {
  53355. this._updatable = true;
  53356. }
  53357. if (this._pickable) {
  53358. this.pickedParticles = [];
  53359. }
  53360. if (this._depthSort) {
  53361. this.depthSortedParticles = [];
  53362. }
  53363. }
  53364. /**
  53365. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53366. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53367. * @returns the created mesh
  53368. */
  53369. SolidParticleSystem.prototype.buildMesh = function () {
  53370. if (this.nbParticles === 0) {
  53371. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53372. this.addShape(triangle, 1);
  53373. triangle.dispose();
  53374. }
  53375. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53376. this._positions32 = new Float32Array(this._positions);
  53377. this._uvs32 = new Float32Array(this._uvs);
  53378. this._colors32 = new Float32Array(this._colors);
  53379. if (this.recomputeNormals) {
  53380. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53381. }
  53382. this._normals32 = new Float32Array(this._normals);
  53383. this._fixedNormal32 = new Float32Array(this._normals);
  53384. if (this._mustUnrotateFixedNormals) {
  53385. this._unrotateFixedNormals();
  53386. }
  53387. var vertexData = new BABYLON.VertexData();
  53388. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53389. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53390. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53391. if (this._uvs32) {
  53392. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53393. ;
  53394. }
  53395. if (this._colors32) {
  53396. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53397. }
  53398. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53399. vertexData.applyToMesh(mesh, this._updatable);
  53400. this.mesh = mesh;
  53401. this.mesh.isPickable = this._pickable;
  53402. // free memory
  53403. if (!this._depthSort) {
  53404. this._indices = null;
  53405. }
  53406. this._positions = null;
  53407. this._normals = null;
  53408. this._uvs = null;
  53409. this._colors = null;
  53410. if (!this._updatable) {
  53411. this.particles.length = 0;
  53412. }
  53413. return mesh;
  53414. };
  53415. /**
  53416. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53417. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53418. * Thus the particles generated from `digest()` have their property `position` set yet.
  53419. * @param mesh ( Mesh ) is the mesh to be digested
  53420. * @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
  53421. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53422. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53423. * @returns the current SPS
  53424. */
  53425. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53426. var size = (options && options.facetNb) || 1;
  53427. var number = (options && options.number) || 0;
  53428. var delta = (options && options.delta) || 0;
  53429. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53430. var meshInd = mesh.getIndices();
  53431. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53432. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53433. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53434. var f = 0; // facet counter
  53435. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53436. // compute size from number
  53437. if (number) {
  53438. number = (number > totalFacets) ? totalFacets : number;
  53439. size = Math.round(totalFacets / number);
  53440. delta = 0;
  53441. }
  53442. else {
  53443. size = (size > totalFacets) ? totalFacets : size;
  53444. }
  53445. var facetPos = []; // submesh positions
  53446. var facetInd = []; // submesh indices
  53447. var facetUV = []; // submesh UV
  53448. var facetCol = []; // submesh colors
  53449. var barycenter = BABYLON.Vector3.Zero();
  53450. var sizeO = size;
  53451. while (f < totalFacets) {
  53452. size = sizeO + Math.floor((1 + delta) * Math.random());
  53453. if (f > totalFacets - size) {
  53454. size = totalFacets - f;
  53455. }
  53456. // reset temp arrays
  53457. facetPos.length = 0;
  53458. facetInd.length = 0;
  53459. facetUV.length = 0;
  53460. facetCol.length = 0;
  53461. // iterate over "size" facets
  53462. var fi = 0;
  53463. for (var j = f * 3; j < (f + size) * 3; j++) {
  53464. facetInd.push(fi);
  53465. var i = meshInd[j];
  53466. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53467. if (meshUV) {
  53468. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53469. }
  53470. if (meshCol) {
  53471. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53472. }
  53473. fi++;
  53474. }
  53475. // create a model shape for each single particle
  53476. var idx = this.nbParticles;
  53477. var shape = this._posToShape(facetPos);
  53478. var shapeUV = this._uvsToShapeUV(facetUV);
  53479. // compute the barycenter of the shape
  53480. var v;
  53481. for (v = 0; v < shape.length; v++) {
  53482. barycenter.addInPlace(shape[v]);
  53483. }
  53484. barycenter.scaleInPlace(1 / shape.length);
  53485. // shift the shape from its barycenter to the origin
  53486. for (v = 0; v < shape.length; v++) {
  53487. shape[v].subtractInPlace(barycenter);
  53488. }
  53489. var bInfo;
  53490. if (this._particlesIntersect) {
  53491. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53492. }
  53493. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53494. // add the particle in the SPS
  53495. var currentPos = this._positions.length;
  53496. var currentInd = this._indices.length;
  53497. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53498. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53499. // initialize the particle position
  53500. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53501. this._index += shape.length;
  53502. idx++;
  53503. this.nbParticles++;
  53504. this._shapeCounter++;
  53505. f += size;
  53506. }
  53507. return this;
  53508. };
  53509. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53510. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53511. var index = 0;
  53512. var idx = 0;
  53513. for (var p = 0; p < this.particles.length; p++) {
  53514. this._particle = this.particles[p];
  53515. this._shape = this._particle._model._shape;
  53516. if (this._particle.rotationQuaternion) {
  53517. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53518. }
  53519. else {
  53520. this._yaw = this._particle.rotation.y;
  53521. this._pitch = this._particle.rotation.x;
  53522. this._roll = this._particle.rotation.z;
  53523. this._quaternionRotationYPR();
  53524. }
  53525. this._quaternionToRotationMatrix();
  53526. this._rotMatrix.invertToRef(this._invertMatrix);
  53527. for (var pt = 0; pt < this._shape.length; pt++) {
  53528. idx = index + pt * 3;
  53529. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53530. this._fixedNormal32[idx] = this._normal.x;
  53531. this._fixedNormal32[idx + 1] = this._normal.y;
  53532. this._fixedNormal32[idx + 2] = this._normal.z;
  53533. }
  53534. index = idx + 3;
  53535. }
  53536. };
  53537. //reset copy
  53538. SolidParticleSystem.prototype._resetCopy = function () {
  53539. this._copy.position.x = 0;
  53540. this._copy.position.y = 0;
  53541. this._copy.position.z = 0;
  53542. this._copy.rotation.x = 0;
  53543. this._copy.rotation.y = 0;
  53544. this._copy.rotation.z = 0;
  53545. this._copy.rotationQuaternion = null;
  53546. this._copy.scaling.x = 1.0;
  53547. this._copy.scaling.y = 1.0;
  53548. this._copy.scaling.z = 1.0;
  53549. this._copy.uvs.x = 0;
  53550. this._copy.uvs.y = 0;
  53551. this._copy.uvs.z = 1.0;
  53552. this._copy.uvs.w = 1.0;
  53553. this._copy.color = null;
  53554. this._copy.translateFromPivot = false;
  53555. };
  53556. // _meshBuilder : inserts the shape model in the global SPS mesh
  53557. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53558. var i;
  53559. var u = 0;
  53560. var c = 0;
  53561. var n = 0;
  53562. this._resetCopy();
  53563. if (options && options.positionFunction) {
  53564. options.positionFunction(this._copy, idx, idxInShape);
  53565. this._mustUnrotateFixedNormals = true;
  53566. }
  53567. if (this._copy.rotationQuaternion) {
  53568. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53569. }
  53570. else {
  53571. this._yaw = this._copy.rotation.y;
  53572. this._pitch = this._copy.rotation.x;
  53573. this._roll = this._copy.rotation.z;
  53574. this._quaternionRotationYPR();
  53575. }
  53576. this._quaternionToRotationMatrix();
  53577. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53578. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53579. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53580. if (this._copy.translateFromPivot) {
  53581. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53582. }
  53583. else {
  53584. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53585. }
  53586. for (i = 0; i < shape.length; i++) {
  53587. this._vertex.x = shape[i].x;
  53588. this._vertex.y = shape[i].y;
  53589. this._vertex.z = shape[i].z;
  53590. if (options && options.vertexFunction) {
  53591. options.vertexFunction(this._copy, this._vertex, i);
  53592. }
  53593. this._vertex.x *= this._copy.scaling.x;
  53594. this._vertex.y *= this._copy.scaling.y;
  53595. this._vertex.z *= this._copy.scaling.z;
  53596. this._vertex.x -= this._scaledPivot.x;
  53597. this._vertex.y -= this._scaledPivot.y;
  53598. this._vertex.z -= this._scaledPivot.z;
  53599. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53600. this._rotated.addInPlace(this._pivotBackTranslation);
  53601. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53602. if (meshUV) {
  53603. 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);
  53604. u += 2;
  53605. }
  53606. if (this._copy.color) {
  53607. this._color = this._copy.color;
  53608. }
  53609. else if (meshCol && meshCol[c] !== undefined) {
  53610. this._color.r = meshCol[c];
  53611. this._color.g = meshCol[c + 1];
  53612. this._color.b = meshCol[c + 2];
  53613. this._color.a = meshCol[c + 3];
  53614. }
  53615. else {
  53616. this._color.r = 1.0;
  53617. this._color.g = 1.0;
  53618. this._color.b = 1.0;
  53619. this._color.a = 1.0;
  53620. }
  53621. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53622. c += 4;
  53623. if (!this.recomputeNormals && meshNor) {
  53624. this._normal.x = meshNor[n];
  53625. this._normal.y = meshNor[n + 1];
  53626. this._normal.z = meshNor[n + 2];
  53627. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53628. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53629. n += 3;
  53630. }
  53631. }
  53632. for (i = 0; i < meshInd.length; i++) {
  53633. var current_ind = p + meshInd[i];
  53634. indices.push(current_ind);
  53635. if (current_ind > 65535) {
  53636. this._needs32Bits = true;
  53637. }
  53638. }
  53639. if (this._pickable) {
  53640. var nbfaces = meshInd.length / 3;
  53641. for (i = 0; i < nbfaces; i++) {
  53642. this.pickedParticles.push({ idx: idx, faceId: i });
  53643. }
  53644. }
  53645. if (this._depthSort) {
  53646. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53647. }
  53648. return this._copy;
  53649. };
  53650. // returns a shape array from positions array
  53651. SolidParticleSystem.prototype._posToShape = function (positions) {
  53652. var shape = [];
  53653. for (var i = 0; i < positions.length; i += 3) {
  53654. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53655. }
  53656. return shape;
  53657. };
  53658. // returns a shapeUV array from a Vector4 uvs
  53659. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53660. var shapeUV = [];
  53661. if (uvs) {
  53662. for (var i = 0; i < uvs.length; i++)
  53663. shapeUV.push(uvs[i]);
  53664. }
  53665. return shapeUV;
  53666. };
  53667. // adds a new particle object in the particles array
  53668. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53669. if (bInfo === void 0) { bInfo = null; }
  53670. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53671. this.particles.push(sp);
  53672. return sp;
  53673. };
  53674. /**
  53675. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53676. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53677. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53678. * @param nb (positive integer) the number of particles to be created from this model
  53679. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53680. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53681. * @returns the number of shapes in the system
  53682. */
  53683. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53684. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53685. var meshInd = mesh.getIndices();
  53686. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53687. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53688. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53689. var bbInfo;
  53690. if (this._particlesIntersect) {
  53691. bbInfo = mesh.getBoundingInfo();
  53692. }
  53693. var shape = this._posToShape(meshPos);
  53694. var shapeUV = this._uvsToShapeUV(meshUV);
  53695. var posfunc = options ? options.positionFunction : null;
  53696. var vtxfunc = options ? options.vertexFunction : null;
  53697. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53698. // particles
  53699. var sp;
  53700. var currentCopy;
  53701. var idx = this.nbParticles;
  53702. for (var i = 0; i < nb; i++) {
  53703. var currentPos = this._positions.length;
  53704. var currentInd = this._indices.length;
  53705. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53706. if (this._updatable) {
  53707. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53708. sp.position.copyFrom(currentCopy.position);
  53709. sp.rotation.copyFrom(currentCopy.rotation);
  53710. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53711. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53712. }
  53713. if (currentCopy.color && sp.color) {
  53714. sp.color.copyFrom(currentCopy.color);
  53715. }
  53716. sp.scaling.copyFrom(currentCopy.scaling);
  53717. sp.uvs.copyFrom(currentCopy.uvs);
  53718. }
  53719. this._index += shape.length;
  53720. idx++;
  53721. }
  53722. this.nbParticles += nb;
  53723. this._shapeCounter++;
  53724. return this._shapeCounter - 1;
  53725. };
  53726. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53727. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53728. this._resetCopy();
  53729. if (particle._model._positionFunction) {
  53730. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53731. }
  53732. if (this._copy.rotationQuaternion) {
  53733. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53734. }
  53735. else {
  53736. this._yaw = this._copy.rotation.y;
  53737. this._pitch = this._copy.rotation.x;
  53738. this._roll = this._copy.rotation.z;
  53739. this._quaternionRotationYPR();
  53740. }
  53741. this._quaternionToRotationMatrix();
  53742. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53743. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53744. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53745. if (this._copy.translateFromPivot) {
  53746. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53747. }
  53748. else {
  53749. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53750. }
  53751. this._shape = particle._model._shape;
  53752. for (var pt = 0; pt < this._shape.length; pt++) {
  53753. this._vertex.x = this._shape[pt].x;
  53754. this._vertex.y = this._shape[pt].y;
  53755. this._vertex.z = this._shape[pt].z;
  53756. if (particle._model._vertexFunction) {
  53757. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53758. }
  53759. this._vertex.x *= this._copy.scaling.x;
  53760. this._vertex.y *= this._copy.scaling.y;
  53761. this._vertex.z *= this._copy.scaling.z;
  53762. this._vertex.x -= this._scaledPivot.x;
  53763. this._vertex.y -= this._scaledPivot.y;
  53764. this._vertex.z -= this._scaledPivot.z;
  53765. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53766. this._rotated.addInPlace(this._pivotBackTranslation);
  53767. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53768. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53769. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53770. }
  53771. particle.position.x = 0.0;
  53772. particle.position.y = 0.0;
  53773. particle.position.z = 0.0;
  53774. particle.rotation.x = 0.0;
  53775. particle.rotation.y = 0.0;
  53776. particle.rotation.z = 0.0;
  53777. particle.rotationQuaternion = null;
  53778. particle.scaling.x = 1.0;
  53779. particle.scaling.y = 1.0;
  53780. particle.scaling.z = 1.0;
  53781. particle.uvs.x = 0.0;
  53782. particle.uvs.y = 0.0;
  53783. particle.uvs.z = 1.0;
  53784. particle.uvs.w = 1.0;
  53785. particle.pivot.x = 0.0;
  53786. particle.pivot.y = 0.0;
  53787. particle.pivot.z = 0.0;
  53788. particle.translateFromPivot = false;
  53789. particle.parentId = null;
  53790. };
  53791. /**
  53792. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53793. * @returns the SPS.
  53794. */
  53795. SolidParticleSystem.prototype.rebuildMesh = function () {
  53796. for (var p = 0; p < this.particles.length; p++) {
  53797. this._rebuildParticle(this.particles[p]);
  53798. }
  53799. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53800. return this;
  53801. };
  53802. /**
  53803. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53804. * This method calls `updateParticle()` for each particle of the SPS.
  53805. * For an animated SPS, it is usually called within the render loop.
  53806. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53807. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53808. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53809. * @returns the SPS.
  53810. */
  53811. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53812. if (start === void 0) { start = 0; }
  53813. if (end === void 0) { end = this.nbParticles - 1; }
  53814. if (update === void 0) { update = true; }
  53815. if (!this._updatable) {
  53816. return this;
  53817. }
  53818. // custom beforeUpdate
  53819. this.beforeUpdateParticles(start, end, update);
  53820. this._cam_axisX.x = 1.0;
  53821. this._cam_axisX.y = 0.0;
  53822. this._cam_axisX.z = 0.0;
  53823. this._cam_axisY.x = 0.0;
  53824. this._cam_axisY.y = 1.0;
  53825. this._cam_axisY.z = 0.0;
  53826. this._cam_axisZ.x = 0.0;
  53827. this._cam_axisZ.y = 0.0;
  53828. this._cam_axisZ.z = 1.0;
  53829. // cases when the World Matrix is to be computed first
  53830. if (this.billboard || this._depthSort) {
  53831. this.mesh.computeWorldMatrix(true);
  53832. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53833. }
  53834. // if the particles will always face the camera
  53835. if (this.billboard) {
  53836. // compute the camera position and un-rotate it by the current mesh rotation
  53837. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53838. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53839. this._cam_axisZ.normalize();
  53840. // same for camera up vector extracted from the cam view matrix
  53841. var view = this._camera.getViewMatrix(true);
  53842. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53843. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53844. this._cam_axisY.normalize();
  53845. this._cam_axisX.normalize();
  53846. }
  53847. // if depthSort, compute the camera global position in the mesh local system
  53848. if (this._depthSort) {
  53849. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53850. }
  53851. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53852. var idx = 0; // current position index in the global array positions32
  53853. var index = 0; // position start index in the global array positions32 of the current particle
  53854. var colidx = 0; // current color index in the global array colors32
  53855. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53856. var uvidx = 0; // current uv index in the global array uvs32
  53857. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53858. var pt = 0; // current index in the particle model shape
  53859. if (this.mesh.isFacetDataEnabled) {
  53860. this._computeBoundingBox = true;
  53861. }
  53862. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53863. if (this._computeBoundingBox) {
  53864. if (start == 0 && end == this.nbParticles - 1) {
  53865. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53866. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53867. }
  53868. else {
  53869. if (this.mesh._boundingInfo) {
  53870. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53871. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53872. }
  53873. }
  53874. }
  53875. // particle loop
  53876. index = this.particles[start]._pos;
  53877. var vpos = (index / 3) | 0;
  53878. colorIndex = vpos * 4;
  53879. uvIndex = vpos * 2;
  53880. for (var p = start; p <= end; p++) {
  53881. this._particle = this.particles[p];
  53882. this._shape = this._particle._model._shape;
  53883. this._shapeUV = this._particle._model._shapeUV;
  53884. // call to custom user function to update the particle properties
  53885. this.updateParticle(this._particle);
  53886. // camera-particle distance for depth sorting
  53887. if (this._depthSort && this._depthSortParticles) {
  53888. var dsp = this.depthSortedParticles[p];
  53889. dsp.ind = this._particle._ind;
  53890. dsp.indicesLength = this._particle._model._indicesLength;
  53891. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53892. }
  53893. // skip the computations for inactive or already invisible particles
  53894. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53895. // increment indexes for the next particle
  53896. pt = this._shape.length;
  53897. index += pt * 3;
  53898. colorIndex += pt * 4;
  53899. uvIndex += pt * 2;
  53900. continue;
  53901. }
  53902. if (this._particle.isVisible) {
  53903. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53904. this._particleHasParent = (this._particle.parentId !== null);
  53905. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53906. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53907. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53908. // particle rotation matrix
  53909. if (this.billboard) {
  53910. this._particle.rotation.x = 0.0;
  53911. this._particle.rotation.y = 0.0;
  53912. }
  53913. if (this._computeParticleRotation || this.billboard) {
  53914. if (this._particle.rotationQuaternion) {
  53915. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53916. }
  53917. else {
  53918. this._yaw = this._particle.rotation.y;
  53919. this._pitch = this._particle.rotation.x;
  53920. this._roll = this._particle.rotation.z;
  53921. this._quaternionRotationYPR();
  53922. }
  53923. this._quaternionToRotationMatrix();
  53924. }
  53925. if (this._particleHasParent) {
  53926. this._parent = this.particles[this._particle.parentId];
  53927. 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];
  53928. 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];
  53929. 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];
  53930. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53931. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53932. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53933. if (this._computeParticleRotation || this.billboard) {
  53934. 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];
  53935. 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];
  53936. 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];
  53937. 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];
  53938. 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];
  53939. 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];
  53940. 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];
  53941. 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];
  53942. 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];
  53943. }
  53944. }
  53945. else {
  53946. this._particle._globalPosition.x = this._particle.position.x;
  53947. this._particle._globalPosition.y = this._particle.position.y;
  53948. this._particle._globalPosition.z = this._particle.position.z;
  53949. if (this._computeParticleRotation || this.billboard) {
  53950. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53951. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53952. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53953. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53954. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53955. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53956. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53957. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53958. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53959. }
  53960. }
  53961. if (this._particle.translateFromPivot) {
  53962. this._pivotBackTranslation.x = 0.0;
  53963. this._pivotBackTranslation.y = 0.0;
  53964. this._pivotBackTranslation.z = 0.0;
  53965. }
  53966. else {
  53967. this._pivotBackTranslation.x = this._scaledPivot.x;
  53968. this._pivotBackTranslation.y = this._scaledPivot.y;
  53969. this._pivotBackTranslation.z = this._scaledPivot.z;
  53970. }
  53971. // particle vertex loop
  53972. for (pt = 0; pt < this._shape.length; pt++) {
  53973. idx = index + pt * 3;
  53974. colidx = colorIndex + pt * 4;
  53975. uvidx = uvIndex + pt * 2;
  53976. this._vertex.x = this._shape[pt].x;
  53977. this._vertex.y = this._shape[pt].y;
  53978. this._vertex.z = this._shape[pt].z;
  53979. if (this._computeParticleVertex) {
  53980. this.updateParticleVertex(this._particle, this._vertex, pt);
  53981. }
  53982. // positions
  53983. this._vertex.x *= this._particle.scaling.x;
  53984. this._vertex.y *= this._particle.scaling.y;
  53985. this._vertex.z *= this._particle.scaling.z;
  53986. this._vertex.x -= this._scaledPivot.x;
  53987. this._vertex.y -= this._scaledPivot.y;
  53988. this._vertex.z -= this._scaledPivot.z;
  53989. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53990. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53991. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53992. this._rotated.x += this._pivotBackTranslation.x;
  53993. this._rotated.y += this._pivotBackTranslation.y;
  53994. this._rotated.z += this._pivotBackTranslation.z;
  53995. 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;
  53996. 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;
  53997. 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;
  53998. if (this._computeBoundingBox) {
  53999. if (this._positions32[idx] < this._minimum.x) {
  54000. this._minimum.x = this._positions32[idx];
  54001. }
  54002. if (this._positions32[idx] > this._maximum.x) {
  54003. this._maximum.x = this._positions32[idx];
  54004. }
  54005. if (this._positions32[idx + 1] < this._minimum.y) {
  54006. this._minimum.y = this._positions32[idx + 1];
  54007. }
  54008. if (this._positions32[idx + 1] > this._maximum.y) {
  54009. this._maximum.y = this._positions32[idx + 1];
  54010. }
  54011. if (this._positions32[idx + 2] < this._minimum.z) {
  54012. this._minimum.z = this._positions32[idx + 2];
  54013. }
  54014. if (this._positions32[idx + 2] > this._maximum.z) {
  54015. this._maximum.z = this._positions32[idx + 2];
  54016. }
  54017. }
  54018. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54019. if (!this._computeParticleVertex) {
  54020. this._normal.x = this._fixedNormal32[idx];
  54021. this._normal.y = this._fixedNormal32[idx + 1];
  54022. this._normal.z = this._fixedNormal32[idx + 2];
  54023. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54024. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54025. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54026. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54027. 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;
  54028. 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;
  54029. }
  54030. if (this._computeParticleColor && this._particle.color) {
  54031. this._colors32[colidx] = this._particle.color.r;
  54032. this._colors32[colidx + 1] = this._particle.color.g;
  54033. this._colors32[colidx + 2] = this._particle.color.b;
  54034. this._colors32[colidx + 3] = this._particle.color.a;
  54035. }
  54036. if (this._computeParticleTexture) {
  54037. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54038. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54039. }
  54040. }
  54041. }
  54042. else {
  54043. this._particle._stillInvisible = true; // mark the particle as invisible
  54044. for (pt = 0; pt < this._shape.length; pt++) {
  54045. idx = index + pt * 3;
  54046. colidx = colorIndex + pt * 4;
  54047. uvidx = uvIndex + pt * 2;
  54048. this._positions32[idx] = 0.0;
  54049. this._positions32[idx + 1] = 0.0;
  54050. this._positions32[idx + 2] = 0.0;
  54051. this._normals32[idx] = 0.0;
  54052. this._normals32[idx + 1] = 0.0;
  54053. this._normals32[idx + 2] = 0.0;
  54054. if (this._computeParticleColor && this._particle.color) {
  54055. this._colors32[colidx] = this._particle.color.r;
  54056. this._colors32[colidx + 1] = this._particle.color.g;
  54057. this._colors32[colidx + 2] = this._particle.color.b;
  54058. this._colors32[colidx + 3] = this._particle.color.a;
  54059. }
  54060. if (this._computeParticleTexture) {
  54061. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54062. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54063. }
  54064. }
  54065. }
  54066. // if the particle intersections must be computed : update the bbInfo
  54067. if (this._particlesIntersect) {
  54068. var bInfo = this._particle._boundingInfo;
  54069. var bBox = bInfo.boundingBox;
  54070. var bSphere = bInfo.boundingSphere;
  54071. if (!this._bSphereOnly) {
  54072. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54073. for (var b = 0; b < bBox.vectors.length; b++) {
  54074. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54075. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54076. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54077. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54078. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54079. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54080. 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;
  54081. 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;
  54082. 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;
  54083. }
  54084. bBox._update(this.mesh._worldMatrix);
  54085. }
  54086. // place and scale the particle bouding sphere in the SPS local system, then update it
  54087. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54088. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54089. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54090. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54091. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54092. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54093. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54094. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54095. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54096. 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));
  54097. bSphere._update(this.mesh._worldMatrix);
  54098. }
  54099. // increment indexes for the next particle
  54100. index = idx + 3;
  54101. colorIndex = colidx + 4;
  54102. uvIndex = uvidx + 2;
  54103. }
  54104. // if the VBO must be updated
  54105. if (update) {
  54106. if (this._computeParticleColor) {
  54107. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54108. }
  54109. if (this._computeParticleTexture) {
  54110. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54111. }
  54112. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54113. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54114. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54115. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54116. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54117. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54118. for (var i = 0; i < this._normals32.length; i++) {
  54119. this._fixedNormal32[i] = this._normals32[i];
  54120. }
  54121. }
  54122. if (!this.mesh.areNormalsFrozen) {
  54123. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54124. }
  54125. }
  54126. if (this._depthSort && this._depthSortParticles) {
  54127. this.depthSortedParticles.sort(this._depthSortFunction);
  54128. var dspl = this.depthSortedParticles.length;
  54129. var sorted = 0;
  54130. var lind = 0;
  54131. var sind = 0;
  54132. var sid = 0;
  54133. for (sorted = 0; sorted < dspl; sorted++) {
  54134. lind = this.depthSortedParticles[sorted].indicesLength;
  54135. sind = this.depthSortedParticles[sorted].ind;
  54136. for (var i = 0; i < lind; i++) {
  54137. this._indices32[sid] = this._indices[sind + i];
  54138. sid++;
  54139. }
  54140. }
  54141. this.mesh.updateIndices(this._indices32);
  54142. }
  54143. }
  54144. if (this._computeBoundingBox) {
  54145. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54146. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54147. }
  54148. this.afterUpdateParticles(start, end, update);
  54149. return this;
  54150. };
  54151. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54152. this._halfroll = this._roll * 0.5;
  54153. this._halfpitch = this._pitch * 0.5;
  54154. this._halfyaw = this._yaw * 0.5;
  54155. this._sinRoll = Math.sin(this._halfroll);
  54156. this._cosRoll = Math.cos(this._halfroll);
  54157. this._sinPitch = Math.sin(this._halfpitch);
  54158. this._cosPitch = Math.cos(this._halfpitch);
  54159. this._sinYaw = Math.sin(this._halfyaw);
  54160. this._cosYaw = Math.cos(this._halfyaw);
  54161. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54162. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54163. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54164. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54165. };
  54166. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54167. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54168. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54169. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54170. this._rotMatrix.m[3] = 0;
  54171. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54172. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54173. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54174. this._rotMatrix.m[7] = 0;
  54175. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54176. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54177. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54178. this._rotMatrix.m[11] = 0;
  54179. this._rotMatrix.m[12] = 0;
  54180. this._rotMatrix.m[13] = 0;
  54181. this._rotMatrix.m[14] = 0;
  54182. this._rotMatrix.m[15] = 1.0;
  54183. };
  54184. /**
  54185. * Disposes the SPS.
  54186. */
  54187. SolidParticleSystem.prototype.dispose = function () {
  54188. this.mesh.dispose();
  54189. this.vars = null;
  54190. // drop references to internal big arrays for the GC
  54191. this._positions = null;
  54192. this._indices = null;
  54193. this._normals = null;
  54194. this._uvs = null;
  54195. this._colors = null;
  54196. this._indices32 = null;
  54197. this._positions32 = null;
  54198. this._normals32 = null;
  54199. this._fixedNormal32 = null;
  54200. this._uvs32 = null;
  54201. this._colors32 = null;
  54202. this.pickedParticles = null;
  54203. };
  54204. /**
  54205. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54206. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54207. * @returns the SPS.
  54208. */
  54209. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54210. if (!this._isVisibilityBoxLocked) {
  54211. this.mesh.refreshBoundingInfo();
  54212. }
  54213. return this;
  54214. };
  54215. /**
  54216. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54217. * @param size the size (float) of the visibility box
  54218. * note : this doesn't lock the SPS mesh bounding box.
  54219. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54220. */
  54221. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54222. var vis = size / 2;
  54223. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54224. };
  54225. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54226. /**
  54227. * Gets whether the SPS as always visible or not
  54228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54229. */
  54230. get: function () {
  54231. return this._alwaysVisible;
  54232. },
  54233. /**
  54234. * Sets the SPS as always visible or not
  54235. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54236. */
  54237. set: function (val) {
  54238. this._alwaysVisible = val;
  54239. this.mesh.alwaysSelectAsActiveMesh = val;
  54240. },
  54241. enumerable: true,
  54242. configurable: true
  54243. });
  54244. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54245. /**
  54246. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54247. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54248. */
  54249. get: function () {
  54250. return this._isVisibilityBoxLocked;
  54251. },
  54252. /**
  54253. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54254. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54255. */
  54256. set: function (val) {
  54257. this._isVisibilityBoxLocked = val;
  54258. var boundingInfo = this.mesh.getBoundingInfo();
  54259. boundingInfo.isLocked = val;
  54260. },
  54261. enumerable: true,
  54262. configurable: true
  54263. });
  54264. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54265. /**
  54266. * Gets if `setParticles()` computes the particle rotations or not.
  54267. * Default value : true. The SPS is faster when it's set to false.
  54268. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54269. */
  54270. get: function () {
  54271. return this._computeParticleRotation;
  54272. },
  54273. /**
  54274. * Tells to `setParticles()` to compute the particle rotations or not.
  54275. * Default value : true. The SPS is faster when it's set to false.
  54276. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54277. */
  54278. set: function (val) {
  54279. this._computeParticleRotation = val;
  54280. },
  54281. enumerable: true,
  54282. configurable: true
  54283. });
  54284. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54285. /**
  54286. * Gets if `setParticles()` computes the particle colors or not.
  54287. * Default value : true. The SPS is faster when it's set to false.
  54288. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54289. */
  54290. get: function () {
  54291. return this._computeParticleColor;
  54292. },
  54293. /**
  54294. * Tells to `setParticles()` to compute the particle colors or not.
  54295. * Default value : true. The SPS is faster when it's set to false.
  54296. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54297. */
  54298. set: function (val) {
  54299. this._computeParticleColor = val;
  54300. },
  54301. enumerable: true,
  54302. configurable: true
  54303. });
  54304. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54305. /**
  54306. * Gets if `setParticles()` computes the particle textures or not.
  54307. * Default value : true. The SPS is faster when it's set to false.
  54308. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54309. */
  54310. get: function () {
  54311. return this._computeParticleTexture;
  54312. },
  54313. set: function (val) {
  54314. this._computeParticleTexture = val;
  54315. },
  54316. enumerable: true,
  54317. configurable: true
  54318. });
  54319. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54320. /**
  54321. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54322. * Default value : false. The SPS is faster when it's set to false.
  54323. * Note : the particle custom vertex positions aren't stored values.
  54324. */
  54325. get: function () {
  54326. return this._computeParticleVertex;
  54327. },
  54328. /**
  54329. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54330. * Default value : false. The SPS is faster when it's set to false.
  54331. * Note : the particle custom vertex positions aren't stored values.
  54332. */
  54333. set: function (val) {
  54334. this._computeParticleVertex = val;
  54335. },
  54336. enumerable: true,
  54337. configurable: true
  54338. });
  54339. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54340. /**
  54341. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54342. */
  54343. get: function () {
  54344. return this._computeBoundingBox;
  54345. },
  54346. /**
  54347. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54348. */
  54349. set: function (val) {
  54350. this._computeBoundingBox = val;
  54351. },
  54352. enumerable: true,
  54353. configurable: true
  54354. });
  54355. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54356. /**
  54357. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54358. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54359. * Default : `true`
  54360. */
  54361. get: function () {
  54362. return this._depthSortParticles;
  54363. },
  54364. /**
  54365. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54366. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54367. * Default : `true`
  54368. */
  54369. set: function (val) {
  54370. this._depthSortParticles = val;
  54371. },
  54372. enumerable: true,
  54373. configurable: true
  54374. });
  54375. // =======================================================================
  54376. // Particle behavior logic
  54377. // these following methods may be overwritten by the user to fit his needs
  54378. /**
  54379. * This function does nothing. It may be overwritten to set all the particle first values.
  54380. * The SPS doesn't call this function, you may have to call it by your own.
  54381. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54382. */
  54383. SolidParticleSystem.prototype.initParticles = function () {
  54384. };
  54385. /**
  54386. * This function does nothing. It may be overwritten to recycle a particle.
  54387. * The SPS doesn't call this function, you may have to call it by your own.
  54388. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54389. * @param particle The particle to recycle
  54390. * @returns the recycled particle
  54391. */
  54392. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54393. return particle;
  54394. };
  54395. /**
  54396. * Updates a particle : this function should be overwritten by the user.
  54397. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54398. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54399. * @example : just set a particle position or velocity and recycle conditions
  54400. * @param particle The particle to update
  54401. * @returns the updated particle
  54402. */
  54403. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54404. return particle;
  54405. };
  54406. /**
  54407. * Updates a vertex of a particle : it can be overwritten by the user.
  54408. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54409. * @param particle the current particle
  54410. * @param vertex the current index of the current particle
  54411. * @param pt the index of the current vertex in the particle shape
  54412. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54413. * @example : just set a vertex particle position
  54414. * @returns the updated vertex
  54415. */
  54416. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54417. return vertex;
  54418. };
  54419. /**
  54420. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54421. * This does nothing and may be overwritten by the user.
  54422. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54423. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54424. * @param update the boolean update value actually passed to setParticles()
  54425. */
  54426. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54427. };
  54428. /**
  54429. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54430. * This will be passed three parameters.
  54431. * This does nothing and may be overwritten by the user.
  54432. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54433. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54434. * @param update the boolean update value actually passed to setParticles()
  54435. */
  54436. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54437. };
  54438. return SolidParticleSystem;
  54439. }());
  54440. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54441. })(BABYLON || (BABYLON = {}));
  54442. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54443. var BABYLON;
  54444. (function (BABYLON) {
  54445. var ShaderMaterial = /** @class */ (function (_super) {
  54446. __extends(ShaderMaterial, _super);
  54447. function ShaderMaterial(name, scene, shaderPath, options) {
  54448. var _this = _super.call(this, name, scene) || this;
  54449. _this._textures = {};
  54450. _this._textureArrays = {};
  54451. _this._floats = {};
  54452. _this._ints = {};
  54453. _this._floatsArrays = {};
  54454. _this._colors3 = {};
  54455. _this._colors3Arrays = {};
  54456. _this._colors4 = {};
  54457. _this._vectors2 = {};
  54458. _this._vectors3 = {};
  54459. _this._vectors4 = {};
  54460. _this._matrices = {};
  54461. _this._matrices3x3 = {};
  54462. _this._matrices2x2 = {};
  54463. _this._vectors2Arrays = {};
  54464. _this._vectors3Arrays = {};
  54465. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54466. _this._shaderPath = shaderPath;
  54467. options.needAlphaBlending = options.needAlphaBlending || false;
  54468. options.needAlphaTesting = options.needAlphaTesting || false;
  54469. options.attributes = options.attributes || ["position", "normal", "uv"];
  54470. options.uniforms = options.uniforms || ["worldViewProjection"];
  54471. options.uniformBuffers = options.uniformBuffers || [];
  54472. options.samplers = options.samplers || [];
  54473. options.defines = options.defines || [];
  54474. _this._options = options;
  54475. return _this;
  54476. }
  54477. ShaderMaterial.prototype.getClassName = function () {
  54478. return "ShaderMaterial";
  54479. };
  54480. ShaderMaterial.prototype.needAlphaBlending = function () {
  54481. return this._options.needAlphaBlending;
  54482. };
  54483. ShaderMaterial.prototype.needAlphaTesting = function () {
  54484. return this._options.needAlphaTesting;
  54485. };
  54486. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54487. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54488. this._options.uniforms.push(uniformName);
  54489. }
  54490. };
  54491. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54492. if (this._options.samplers.indexOf(name) === -1) {
  54493. this._options.samplers.push(name);
  54494. }
  54495. this._textures[name] = texture;
  54496. return this;
  54497. };
  54498. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54499. if (this._options.samplers.indexOf(name) === -1) {
  54500. this._options.samplers.push(name);
  54501. }
  54502. this._checkUniform(name);
  54503. this._textureArrays[name] = textures;
  54504. return this;
  54505. };
  54506. ShaderMaterial.prototype.setFloat = function (name, value) {
  54507. this._checkUniform(name);
  54508. this._floats[name] = value;
  54509. return this;
  54510. };
  54511. ShaderMaterial.prototype.setInt = function (name, value) {
  54512. this._checkUniform(name);
  54513. this._ints[name] = value;
  54514. return this;
  54515. };
  54516. ShaderMaterial.prototype.setFloats = function (name, value) {
  54517. this._checkUniform(name);
  54518. this._floatsArrays[name] = value;
  54519. return this;
  54520. };
  54521. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54522. this._checkUniform(name);
  54523. this._colors3[name] = value;
  54524. return this;
  54525. };
  54526. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54527. this._checkUniform(name);
  54528. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54529. color.toArray(arr, arr.length);
  54530. return arr;
  54531. }, []);
  54532. return this;
  54533. };
  54534. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54535. this._checkUniform(name);
  54536. this._colors4[name] = value;
  54537. return this;
  54538. };
  54539. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54540. this._checkUniform(name);
  54541. this._vectors2[name] = value;
  54542. return this;
  54543. };
  54544. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54545. this._checkUniform(name);
  54546. this._vectors3[name] = value;
  54547. return this;
  54548. };
  54549. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54550. this._checkUniform(name);
  54551. this._vectors4[name] = value;
  54552. return this;
  54553. };
  54554. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54555. this._checkUniform(name);
  54556. this._matrices[name] = value;
  54557. return this;
  54558. };
  54559. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54560. this._checkUniform(name);
  54561. this._matrices3x3[name] = value;
  54562. return this;
  54563. };
  54564. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54565. this._checkUniform(name);
  54566. this._matrices2x2[name] = value;
  54567. return this;
  54568. };
  54569. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54570. this._checkUniform(name);
  54571. this._vectors2Arrays[name] = value;
  54572. return this;
  54573. };
  54574. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54575. this._checkUniform(name);
  54576. this._vectors3Arrays[name] = value;
  54577. return this;
  54578. };
  54579. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54580. if (!mesh) {
  54581. return true;
  54582. }
  54583. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54584. return false;
  54585. }
  54586. return false;
  54587. };
  54588. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54589. var scene = this.getScene();
  54590. var engine = scene.getEngine();
  54591. if (!this.checkReadyOnEveryCall) {
  54592. if (this._renderId === scene.getRenderId()) {
  54593. if (this._checkCache(scene, mesh, useInstances)) {
  54594. return true;
  54595. }
  54596. }
  54597. }
  54598. // Instances
  54599. var defines = [];
  54600. var attribs = [];
  54601. var fallbacks = new BABYLON.EffectFallbacks();
  54602. if (useInstances) {
  54603. defines.push("#define INSTANCES");
  54604. }
  54605. for (var index = 0; index < this._options.defines.length; index++) {
  54606. defines.push(this._options.defines[index]);
  54607. }
  54608. for (var index = 0; index < this._options.attributes.length; index++) {
  54609. attribs.push(this._options.attributes[index]);
  54610. }
  54611. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54612. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54613. defines.push("#define VERTEXCOLOR");
  54614. }
  54615. // Bones
  54616. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54619. if (mesh.numBoneInfluencers > 4) {
  54620. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54621. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54622. }
  54623. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54624. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54625. fallbacks.addCPUSkinningFallback(0, mesh);
  54626. if (this._options.uniforms.indexOf("mBones") === -1) {
  54627. this._options.uniforms.push("mBones");
  54628. }
  54629. }
  54630. else {
  54631. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54632. }
  54633. // Textures
  54634. for (var name in this._textures) {
  54635. if (!this._textures[name].isReady()) {
  54636. return false;
  54637. }
  54638. }
  54639. // Alpha test
  54640. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54641. defines.push("#define ALPHATEST");
  54642. }
  54643. var previousEffect = this._effect;
  54644. var join = defines.join("\n");
  54645. this._effect = engine.createEffect(this._shaderPath, {
  54646. attributes: attribs,
  54647. uniformsNames: this._options.uniforms,
  54648. uniformBuffersNames: this._options.uniformBuffers,
  54649. samplers: this._options.samplers,
  54650. defines: join,
  54651. fallbacks: fallbacks,
  54652. onCompiled: this.onCompiled,
  54653. onError: this.onError
  54654. }, engine);
  54655. if (!this._effect.isReady()) {
  54656. return false;
  54657. }
  54658. if (previousEffect !== this._effect) {
  54659. scene.resetCachedMaterial();
  54660. }
  54661. this._renderId = scene.getRenderId();
  54662. return true;
  54663. };
  54664. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54665. var scene = this.getScene();
  54666. if (!this._effect) {
  54667. return;
  54668. }
  54669. if (this._options.uniforms.indexOf("world") !== -1) {
  54670. this._effect.setMatrix("world", world);
  54671. }
  54672. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54673. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54674. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54675. }
  54676. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54677. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54678. }
  54679. };
  54680. ShaderMaterial.prototype.bind = function (world, mesh) {
  54681. // Std values
  54682. this.bindOnlyWorldMatrix(world);
  54683. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54684. if (this._options.uniforms.indexOf("view") !== -1) {
  54685. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54686. }
  54687. if (this._options.uniforms.indexOf("projection") !== -1) {
  54688. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54689. }
  54690. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54691. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54692. }
  54693. // Bones
  54694. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54695. var name;
  54696. // Texture
  54697. for (name in this._textures) {
  54698. this._effect.setTexture(name, this._textures[name]);
  54699. }
  54700. // Texture arrays
  54701. for (name in this._textureArrays) {
  54702. this._effect.setTextureArray(name, this._textureArrays[name]);
  54703. }
  54704. // Int
  54705. for (name in this._ints) {
  54706. this._effect.setInt(name, this._ints[name]);
  54707. }
  54708. // Float
  54709. for (name in this._floats) {
  54710. this._effect.setFloat(name, this._floats[name]);
  54711. }
  54712. // Floats
  54713. for (name in this._floatsArrays) {
  54714. this._effect.setArray(name, this._floatsArrays[name]);
  54715. }
  54716. // Color3
  54717. for (name in this._colors3) {
  54718. this._effect.setColor3(name, this._colors3[name]);
  54719. }
  54720. for (name in this._colors3Arrays) {
  54721. this._effect.setArray3(name, this._colors3Arrays[name]);
  54722. }
  54723. // Color4
  54724. for (name in this._colors4) {
  54725. var color = this._colors4[name];
  54726. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54727. }
  54728. // Vector2
  54729. for (name in this._vectors2) {
  54730. this._effect.setVector2(name, this._vectors2[name]);
  54731. }
  54732. // Vector3
  54733. for (name in this._vectors3) {
  54734. this._effect.setVector3(name, this._vectors3[name]);
  54735. }
  54736. // Vector4
  54737. for (name in this._vectors4) {
  54738. this._effect.setVector4(name, this._vectors4[name]);
  54739. }
  54740. // Matrix
  54741. for (name in this._matrices) {
  54742. this._effect.setMatrix(name, this._matrices[name]);
  54743. }
  54744. // Matrix 3x3
  54745. for (name in this._matrices3x3) {
  54746. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54747. }
  54748. // Matrix 2x2
  54749. for (name in this._matrices2x2) {
  54750. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54751. }
  54752. // Vector2Array
  54753. for (name in this._vectors2Arrays) {
  54754. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54755. }
  54756. // Vector3Array
  54757. for (name in this._vectors3Arrays) {
  54758. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54759. }
  54760. }
  54761. this._afterBind(mesh);
  54762. };
  54763. ShaderMaterial.prototype.getActiveTextures = function () {
  54764. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54765. for (var name in this._textures) {
  54766. activeTextures.push(this._textures[name]);
  54767. }
  54768. for (var name in this._textureArrays) {
  54769. var array = this._textureArrays[name];
  54770. for (var index = 0; index < array.length; index++) {
  54771. activeTextures.push(array[index]);
  54772. }
  54773. }
  54774. return activeTextures;
  54775. };
  54776. ShaderMaterial.prototype.hasTexture = function (texture) {
  54777. if (_super.prototype.hasTexture.call(this, texture)) {
  54778. return true;
  54779. }
  54780. for (var name in this._textures) {
  54781. if (this._textures[name] === texture) {
  54782. return true;
  54783. }
  54784. }
  54785. for (var name in this._textureArrays) {
  54786. var array = this._textureArrays[name];
  54787. for (var index = 0; index < array.length; index++) {
  54788. if (array[index] === texture) {
  54789. return true;
  54790. }
  54791. }
  54792. }
  54793. return false;
  54794. };
  54795. ShaderMaterial.prototype.clone = function (name) {
  54796. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54797. return newShaderMaterial;
  54798. };
  54799. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54800. if (forceDisposeTextures) {
  54801. var name;
  54802. for (name in this._textures) {
  54803. this._textures[name].dispose();
  54804. }
  54805. for (name in this._textureArrays) {
  54806. var array = this._textureArrays[name];
  54807. for (var index = 0; index < array.length; index++) {
  54808. array[index].dispose();
  54809. }
  54810. }
  54811. }
  54812. this._textures = {};
  54813. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54814. };
  54815. ShaderMaterial.prototype.serialize = function () {
  54816. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54817. serializationObject.customType = "BABYLON.ShaderMaterial";
  54818. serializationObject.options = this._options;
  54819. serializationObject.shaderPath = this._shaderPath;
  54820. var name;
  54821. // Texture
  54822. serializationObject.textures = {};
  54823. for (name in this._textures) {
  54824. serializationObject.textures[name] = this._textures[name].serialize();
  54825. }
  54826. // Texture arrays
  54827. serializationObject.textureArrays = {};
  54828. for (name in this._textureArrays) {
  54829. serializationObject.textureArrays[name] = [];
  54830. var array = this._textureArrays[name];
  54831. for (var index = 0; index < array.length; index++) {
  54832. serializationObject.textureArrays[name].push(array[index].serialize());
  54833. }
  54834. }
  54835. // Float
  54836. serializationObject.floats = {};
  54837. for (name in this._floats) {
  54838. serializationObject.floats[name] = this._floats[name];
  54839. }
  54840. // Float s
  54841. serializationObject.FloatArrays = {};
  54842. for (name in this._floatsArrays) {
  54843. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54844. }
  54845. // Color3
  54846. serializationObject.colors3 = {};
  54847. for (name in this._colors3) {
  54848. serializationObject.colors3[name] = this._colors3[name].asArray();
  54849. }
  54850. // Color3 array
  54851. serializationObject.colors3Arrays = {};
  54852. for (name in this._colors3Arrays) {
  54853. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54854. }
  54855. // Color4
  54856. serializationObject.colors4 = {};
  54857. for (name in this._colors4) {
  54858. serializationObject.colors4[name] = this._colors4[name].asArray();
  54859. }
  54860. // Vector2
  54861. serializationObject.vectors2 = {};
  54862. for (name in this._vectors2) {
  54863. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54864. }
  54865. // Vector3
  54866. serializationObject.vectors3 = {};
  54867. for (name in this._vectors3) {
  54868. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54869. }
  54870. // Vector4
  54871. serializationObject.vectors4 = {};
  54872. for (name in this._vectors4) {
  54873. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54874. }
  54875. // Matrix
  54876. serializationObject.matrices = {};
  54877. for (name in this._matrices) {
  54878. serializationObject.matrices[name] = this._matrices[name].asArray();
  54879. }
  54880. // Matrix 3x3
  54881. serializationObject.matrices3x3 = {};
  54882. for (name in this._matrices3x3) {
  54883. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54884. }
  54885. // Matrix 2x2
  54886. serializationObject.matrices2x2 = {};
  54887. for (name in this._matrices2x2) {
  54888. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54889. }
  54890. // Vector2Array
  54891. serializationObject.vectors2Arrays = {};
  54892. for (name in this._vectors2Arrays) {
  54893. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54894. }
  54895. // Vector3Array
  54896. serializationObject.vectors3Arrays = {};
  54897. for (name in this._vectors3Arrays) {
  54898. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54899. }
  54900. return serializationObject;
  54901. };
  54902. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54903. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54904. var name;
  54905. // Texture
  54906. for (name in source.textures) {
  54907. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54908. }
  54909. // Texture arrays
  54910. for (name in source.textureArrays) {
  54911. var array = source.textureArrays[name];
  54912. var textureArray = new Array();
  54913. for (var index = 0; index < array.length; index++) {
  54914. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54915. }
  54916. material.setTextureArray(name, textureArray);
  54917. }
  54918. // Float
  54919. for (name in source.floats) {
  54920. material.setFloat(name, source.floats[name]);
  54921. }
  54922. // Float s
  54923. for (name in source.floatsArrays) {
  54924. material.setFloats(name, source.floatsArrays[name]);
  54925. }
  54926. // Color3
  54927. for (name in source.colors3) {
  54928. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54929. }
  54930. // Color3 arrays
  54931. for (name in source.colors3Arrays) {
  54932. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54933. if (i % 3 === 0) {
  54934. arr.push([num]);
  54935. }
  54936. else {
  54937. arr[arr.length - 1].push(num);
  54938. }
  54939. return arr;
  54940. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54941. material.setColor3Array(name, colors);
  54942. }
  54943. // Color4
  54944. for (name in source.colors4) {
  54945. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54946. }
  54947. // Vector2
  54948. for (name in source.vectors2) {
  54949. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54950. }
  54951. // Vector3
  54952. for (name in source.vectors3) {
  54953. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54954. }
  54955. // Vector4
  54956. for (name in source.vectors4) {
  54957. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54958. }
  54959. // Matrix
  54960. for (name in source.matrices) {
  54961. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54962. }
  54963. // Matrix 3x3
  54964. for (name in source.matrices3x3) {
  54965. material.setMatrix3x3(name, source.matrices3x3[name]);
  54966. }
  54967. // Matrix 2x2
  54968. for (name in source.matrices2x2) {
  54969. material.setMatrix2x2(name, source.matrices2x2[name]);
  54970. }
  54971. // Vector2Array
  54972. for (name in source.vectors2Arrays) {
  54973. material.setArray2(name, source.vectors2Arrays[name]);
  54974. }
  54975. // Vector3Array
  54976. for (name in source.vectors3Arrays) {
  54977. material.setArray3(name, source.vectors3Arrays[name]);
  54978. }
  54979. return material;
  54980. };
  54981. return ShaderMaterial;
  54982. }(BABYLON.Material));
  54983. BABYLON.ShaderMaterial = ShaderMaterial;
  54984. })(BABYLON || (BABYLON = {}));
  54985. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54986. var BABYLON;
  54987. (function (BABYLON) {
  54988. var GroundMesh = /** @class */ (function (_super) {
  54989. __extends(GroundMesh, _super);
  54990. function GroundMesh(name, scene) {
  54991. var _this = _super.call(this, name, scene) || this;
  54992. _this.generateOctree = false;
  54993. return _this;
  54994. }
  54995. GroundMesh.prototype.getClassName = function () {
  54996. return "GroundMesh";
  54997. };
  54998. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54999. get: function () {
  55000. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55006. get: function () {
  55007. return this._subdivisionsX;
  55008. },
  55009. enumerable: true,
  55010. configurable: true
  55011. });
  55012. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55013. get: function () {
  55014. return this._subdivisionsY;
  55015. },
  55016. enumerable: true,
  55017. configurable: true
  55018. });
  55019. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55020. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55021. this._subdivisionsX = chunksCount;
  55022. this._subdivisionsY = chunksCount;
  55023. this.subdivide(chunksCount);
  55024. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55025. };
  55026. /**
  55027. * Returns a height (y) value in the Worl system :
  55028. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55029. * Returns the ground y position if (x, z) are outside the ground surface.
  55030. */
  55031. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55032. var world = this.getWorldMatrix();
  55033. var invMat = BABYLON.Tmp.Matrix[5];
  55034. world.invertToRef(invMat);
  55035. var tmpVect = BABYLON.Tmp.Vector3[8];
  55036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55037. x = tmpVect.x;
  55038. z = tmpVect.z;
  55039. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55040. return this.position.y;
  55041. }
  55042. if (!this._heightQuads || this._heightQuads.length == 0) {
  55043. this._initHeightQuads();
  55044. this._computeHeightQuads();
  55045. }
  55046. var facet = this._getFacetAt(x, z);
  55047. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55048. // return y in the World system
  55049. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55050. return tmpVect.y;
  55051. };
  55052. /**
  55053. * Returns a normalized vector (Vector3) orthogonal to the ground
  55054. * at the ground coordinates (x, z) expressed in the World system.
  55055. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55056. */
  55057. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55058. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55059. this.getNormalAtCoordinatesToRef(x, z, normal);
  55060. return normal;
  55061. };
  55062. /**
  55063. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55064. * at the ground coordinates (x, z) expressed in the World system.
  55065. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55066. * Returns the GroundMesh.
  55067. */
  55068. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55069. var world = this.getWorldMatrix();
  55070. var tmpMat = BABYLON.Tmp.Matrix[5];
  55071. world.invertToRef(tmpMat);
  55072. var tmpVect = BABYLON.Tmp.Vector3[8];
  55073. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55074. x = tmpVect.x;
  55075. z = tmpVect.z;
  55076. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55077. return this;
  55078. }
  55079. if (!this._heightQuads || this._heightQuads.length == 0) {
  55080. this._initHeightQuads();
  55081. this._computeHeightQuads();
  55082. }
  55083. var facet = this._getFacetAt(x, z);
  55084. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55085. return this;
  55086. };
  55087. /**
  55088. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55089. * if the ground has been updated.
  55090. * This can be used in the render loop.
  55091. * Returns the GroundMesh.
  55092. */
  55093. GroundMesh.prototype.updateCoordinateHeights = function () {
  55094. if (!this._heightQuads || this._heightQuads.length == 0) {
  55095. this._initHeightQuads();
  55096. }
  55097. this._computeHeightQuads();
  55098. return this;
  55099. };
  55100. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55101. GroundMesh.prototype._getFacetAt = function (x, z) {
  55102. // retrieve col and row from x, z coordinates in the ground local system
  55103. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55104. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55105. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55106. var facet;
  55107. if (z < quad.slope.x * x + quad.slope.y) {
  55108. facet = quad.facet1;
  55109. }
  55110. else {
  55111. facet = quad.facet2;
  55112. }
  55113. return facet;
  55114. };
  55115. // Creates and populates the heightMap array with "facet" elements :
  55116. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55117. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55118. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55119. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55120. // Returns the GroundMesh.
  55121. GroundMesh.prototype._initHeightQuads = function () {
  55122. var subdivisionsX = this._subdivisionsX;
  55123. var subdivisionsY = this._subdivisionsY;
  55124. this._heightQuads = new Array();
  55125. for (var row = 0; row < subdivisionsY; row++) {
  55126. for (var col = 0; col < subdivisionsX; col++) {
  55127. 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) };
  55128. this._heightQuads[row * subdivisionsX + col] = quad;
  55129. }
  55130. }
  55131. return this;
  55132. };
  55133. // Compute each quad element values and update the the heightMap array :
  55134. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55135. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55136. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55137. // Returns the GroundMesh.
  55138. GroundMesh.prototype._computeHeightQuads = function () {
  55139. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55140. if (!positions) {
  55141. return this;
  55142. }
  55143. var v1 = BABYLON.Tmp.Vector3[3];
  55144. var v2 = BABYLON.Tmp.Vector3[2];
  55145. var v3 = BABYLON.Tmp.Vector3[1];
  55146. var v4 = BABYLON.Tmp.Vector3[0];
  55147. var v1v2 = BABYLON.Tmp.Vector3[4];
  55148. var v1v3 = BABYLON.Tmp.Vector3[5];
  55149. var v1v4 = BABYLON.Tmp.Vector3[6];
  55150. var norm1 = BABYLON.Tmp.Vector3[7];
  55151. var norm2 = BABYLON.Tmp.Vector3[8];
  55152. var i = 0;
  55153. var j = 0;
  55154. var k = 0;
  55155. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55156. var h = 0;
  55157. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55158. var d2 = 0;
  55159. var subdivisionsX = this._subdivisionsX;
  55160. var subdivisionsY = this._subdivisionsY;
  55161. for (var row = 0; row < subdivisionsY; row++) {
  55162. for (var col = 0; col < subdivisionsX; col++) {
  55163. i = col * 3;
  55164. j = row * (subdivisionsX + 1) * 3;
  55165. k = (row + 1) * (subdivisionsX + 1) * 3;
  55166. v1.x = positions[j + i];
  55167. v1.y = positions[j + i + 1];
  55168. v1.z = positions[j + i + 2];
  55169. v2.x = positions[j + i + 3];
  55170. v2.y = positions[j + i + 4];
  55171. v2.z = positions[j + i + 5];
  55172. v3.x = positions[k + i];
  55173. v3.y = positions[k + i + 1];
  55174. v3.z = positions[k + i + 2];
  55175. v4.x = positions[k + i + 3];
  55176. v4.y = positions[k + i + 4];
  55177. v4.z = positions[k + i + 5];
  55178. // 2D slope V1V4
  55179. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55180. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55181. // facet equations :
  55182. // we compute each facet normal vector
  55183. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55184. // we compute the value d by applying the equation to v1 which belongs to the plane
  55185. // then we store the facet equation in a Vector4
  55186. v2.subtractToRef(v1, v1v2);
  55187. v3.subtractToRef(v1, v1v3);
  55188. v4.subtractToRef(v1, v1v4);
  55189. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55190. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55191. norm1.normalize();
  55192. norm2.normalize();
  55193. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55194. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55195. var quad = this._heightQuads[row * subdivisionsX + col];
  55196. quad.slope.copyFromFloats(cd, h);
  55197. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55198. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55199. }
  55200. }
  55201. return this;
  55202. };
  55203. GroundMesh.prototype.serialize = function (serializationObject) {
  55204. _super.prototype.serialize.call(this, serializationObject);
  55205. serializationObject.subdivisionsX = this._subdivisionsX;
  55206. serializationObject.subdivisionsY = this._subdivisionsY;
  55207. serializationObject.minX = this._minX;
  55208. serializationObject.maxX = this._maxX;
  55209. serializationObject.minZ = this._minZ;
  55210. serializationObject.maxZ = this._maxZ;
  55211. serializationObject.width = this._width;
  55212. serializationObject.height = this._height;
  55213. };
  55214. GroundMesh.Parse = function (parsedMesh, scene) {
  55215. var result = new GroundMesh(parsedMesh.name, scene);
  55216. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55217. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55218. result._minX = parsedMesh.minX;
  55219. result._maxX = parsedMesh.maxX;
  55220. result._minZ = parsedMesh.minZ;
  55221. result._maxZ = parsedMesh.maxZ;
  55222. result._width = parsedMesh.width;
  55223. result._height = parsedMesh.height;
  55224. return result;
  55225. };
  55226. return GroundMesh;
  55227. }(BABYLON.Mesh));
  55228. BABYLON.GroundMesh = GroundMesh;
  55229. })(BABYLON || (BABYLON = {}));
  55230. //# sourceMappingURL=babylon.groundMesh.js.map
  55231. var BABYLON;
  55232. (function (BABYLON) {
  55233. /**
  55234. * Creates an instance based on a source mesh.
  55235. */
  55236. var InstancedMesh = /** @class */ (function (_super) {
  55237. __extends(InstancedMesh, _super);
  55238. function InstancedMesh(name, source) {
  55239. var _this = _super.call(this, name, source.getScene()) || this;
  55240. source.instances.push(_this);
  55241. _this._sourceMesh = source;
  55242. _this.position.copyFrom(source.position);
  55243. _this.rotation.copyFrom(source.rotation);
  55244. _this.scaling.copyFrom(source.scaling);
  55245. if (source.rotationQuaternion) {
  55246. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55247. }
  55248. _this.infiniteDistance = source.infiniteDistance;
  55249. _this.setPivotMatrix(source.getPivotMatrix());
  55250. _this.refreshBoundingInfo();
  55251. _this._syncSubMeshes();
  55252. return _this;
  55253. }
  55254. /**
  55255. * Returns the string "InstancedMesh".
  55256. */
  55257. InstancedMesh.prototype.getClassName = function () {
  55258. return "InstancedMesh";
  55259. };
  55260. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55261. // Methods
  55262. get: function () {
  55263. return this._sourceMesh.receiveShadows;
  55264. },
  55265. enumerable: true,
  55266. configurable: true
  55267. });
  55268. Object.defineProperty(InstancedMesh.prototype, "material", {
  55269. get: function () {
  55270. return this._sourceMesh.material;
  55271. },
  55272. enumerable: true,
  55273. configurable: true
  55274. });
  55275. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55276. get: function () {
  55277. return this._sourceMesh.visibility;
  55278. },
  55279. enumerable: true,
  55280. configurable: true
  55281. });
  55282. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55283. get: function () {
  55284. return this._sourceMesh.skeleton;
  55285. },
  55286. enumerable: true,
  55287. configurable: true
  55288. });
  55289. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55290. get: function () {
  55291. return this._sourceMesh.renderingGroupId;
  55292. },
  55293. set: function (value) {
  55294. //no-op with warning
  55295. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55296. },
  55297. enumerable: true,
  55298. configurable: true
  55299. });
  55300. /**
  55301. * Returns the total number of vertices (integer).
  55302. */
  55303. InstancedMesh.prototype.getTotalVertices = function () {
  55304. return this._sourceMesh.getTotalVertices();
  55305. };
  55306. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55307. get: function () {
  55308. return this._sourceMesh;
  55309. },
  55310. enumerable: true,
  55311. configurable: true
  55312. });
  55313. /**
  55314. * Is this node ready to be used/rendered
  55315. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55316. * @return {boolean} is it ready
  55317. */
  55318. InstancedMesh.prototype.isReady = function (completeCheck) {
  55319. if (completeCheck === void 0) { completeCheck = false; }
  55320. return this._sourceMesh.isReady(completeCheck, true);
  55321. };
  55322. /**
  55323. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55324. */
  55325. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55326. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55327. };
  55328. /**
  55329. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55330. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55331. * The `data` are either a numeric array either a Float32Array.
  55332. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55333. * 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).
  55334. * Note that a new underlying VertexBuffer object is created each call.
  55335. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55336. *
  55337. * Possible `kind` values :
  55338. * - BABYLON.VertexBuffer.PositionKind
  55339. * - BABYLON.VertexBuffer.UVKind
  55340. * - BABYLON.VertexBuffer.UV2Kind
  55341. * - BABYLON.VertexBuffer.UV3Kind
  55342. * - BABYLON.VertexBuffer.UV4Kind
  55343. * - BABYLON.VertexBuffer.UV5Kind
  55344. * - BABYLON.VertexBuffer.UV6Kind
  55345. * - BABYLON.VertexBuffer.ColorKind
  55346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55350. *
  55351. * Returns the Mesh.
  55352. */
  55353. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55354. if (this.sourceMesh) {
  55355. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55356. }
  55357. return this.sourceMesh;
  55358. };
  55359. /**
  55360. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55361. * If the mesh has no geometry, it is simply returned as it is.
  55362. * The `data` are either a numeric array either a Float32Array.
  55363. * No new underlying VertexBuffer object is created.
  55364. * 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.
  55365. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55366. *
  55367. * Possible `kind` values :
  55368. * - BABYLON.VertexBuffer.PositionKind
  55369. * - BABYLON.VertexBuffer.UVKind
  55370. * - BABYLON.VertexBuffer.UV2Kind
  55371. * - BABYLON.VertexBuffer.UV3Kind
  55372. * - BABYLON.VertexBuffer.UV4Kind
  55373. * - BABYLON.VertexBuffer.UV5Kind
  55374. * - BABYLON.VertexBuffer.UV6Kind
  55375. * - BABYLON.VertexBuffer.ColorKind
  55376. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55377. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55378. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55379. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55380. *
  55381. * Returns the Mesh.
  55382. */
  55383. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55384. if (this.sourceMesh) {
  55385. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55386. }
  55387. return this.sourceMesh;
  55388. };
  55389. /**
  55390. * Sets the mesh indices.
  55391. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55392. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55393. * This method creates a new index buffer each call.
  55394. * Returns the Mesh.
  55395. */
  55396. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55397. if (totalVertices === void 0) { totalVertices = null; }
  55398. if (this.sourceMesh) {
  55399. this.sourceMesh.setIndices(indices, totalVertices);
  55400. }
  55401. return this.sourceMesh;
  55402. };
  55403. /**
  55404. * Boolean : True if the mesh owns the requested kind of data.
  55405. */
  55406. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55407. return this._sourceMesh.isVerticesDataPresent(kind);
  55408. };
  55409. /**
  55410. * Returns an array of indices (IndicesArray).
  55411. */
  55412. InstancedMesh.prototype.getIndices = function () {
  55413. return this._sourceMesh.getIndices();
  55414. };
  55415. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55416. get: function () {
  55417. return this._sourceMesh._positions;
  55418. },
  55419. enumerable: true,
  55420. configurable: true
  55421. });
  55422. /**
  55423. * Sets a new updated BoundingInfo to the mesh.
  55424. * Returns the mesh.
  55425. */
  55426. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55427. var meshBB = this._sourceMesh.getBoundingInfo();
  55428. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55429. this._updateBoundingInfo();
  55430. return this;
  55431. };
  55432. InstancedMesh.prototype._preActivate = function () {
  55433. if (this._currentLOD) {
  55434. this._currentLOD._preActivate();
  55435. }
  55436. return this;
  55437. };
  55438. InstancedMesh.prototype._activate = function (renderId) {
  55439. if (this._currentLOD) {
  55440. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55441. }
  55442. return this;
  55443. };
  55444. /**
  55445. * Returns the current associated LOD AbstractMesh.
  55446. */
  55447. InstancedMesh.prototype.getLOD = function (camera) {
  55448. if (!camera) {
  55449. return this;
  55450. }
  55451. var boundingInfo = this.getBoundingInfo();
  55452. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55453. if (this._currentLOD === this.sourceMesh) {
  55454. return this;
  55455. }
  55456. return this._currentLOD;
  55457. };
  55458. InstancedMesh.prototype._syncSubMeshes = function () {
  55459. this.releaseSubMeshes();
  55460. if (this._sourceMesh.subMeshes) {
  55461. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55462. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55463. }
  55464. }
  55465. return this;
  55466. };
  55467. InstancedMesh.prototype._generatePointsArray = function () {
  55468. return this._sourceMesh._generatePointsArray();
  55469. };
  55470. /**
  55471. * Creates a new InstancedMesh from the current mesh.
  55472. * - name (string) : the cloned mesh name
  55473. * - newParent (optional Node) : the optional Node to parent the clone to.
  55474. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55475. *
  55476. * Returns the clone.
  55477. */
  55478. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55479. var result = this._sourceMesh.createInstance(name);
  55480. // Deep copy
  55481. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55482. // Bounding info
  55483. this.refreshBoundingInfo();
  55484. // Parent
  55485. if (newParent) {
  55486. result.parent = newParent;
  55487. }
  55488. if (!doNotCloneChildren) {
  55489. // Children
  55490. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55491. var mesh = this.getScene().meshes[index];
  55492. if (mesh.parent === this) {
  55493. mesh.clone(mesh.name, result);
  55494. }
  55495. }
  55496. }
  55497. result.computeWorldMatrix(true);
  55498. return result;
  55499. };
  55500. /**
  55501. * Disposes the InstancedMesh.
  55502. * Returns nothing.
  55503. */
  55504. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55505. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55506. // Remove from mesh
  55507. var index = this._sourceMesh.instances.indexOf(this);
  55508. this._sourceMesh.instances.splice(index, 1);
  55509. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55510. };
  55511. return InstancedMesh;
  55512. }(BABYLON.AbstractMesh));
  55513. BABYLON.InstancedMesh = InstancedMesh;
  55514. })(BABYLON || (BABYLON = {}));
  55515. //# sourceMappingURL=babylon.instancedMesh.js.map
  55516. var BABYLON;
  55517. (function (BABYLON) {
  55518. var LinesMesh = /** @class */ (function (_super) {
  55519. __extends(LinesMesh, _super);
  55520. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55521. if (scene === void 0) { scene = null; }
  55522. if (parent === void 0) { parent = null; }
  55523. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55524. _this.useVertexColor = useVertexColor;
  55525. _this.useVertexAlpha = useVertexAlpha;
  55526. _this.color = new BABYLON.Color3(1, 1, 1);
  55527. _this.alpha = 1;
  55528. if (source) {
  55529. _this.color = source.color.clone();
  55530. _this.alpha = source.alpha;
  55531. _this.useVertexColor = source.useVertexColor;
  55532. _this.useVertexAlpha = source.useVertexAlpha;
  55533. }
  55534. _this._intersectionThreshold = 0.1;
  55535. var defines = [];
  55536. var options = {
  55537. attributes: [BABYLON.VertexBuffer.PositionKind],
  55538. uniforms: ["world", "viewProjection"],
  55539. needAlphaBlending: true,
  55540. defines: defines
  55541. };
  55542. if (useVertexAlpha === false) {
  55543. options.needAlphaBlending = false;
  55544. }
  55545. if (!useVertexColor) {
  55546. options.uniforms.push("color");
  55547. }
  55548. else {
  55549. options.defines.push("#define VERTEXCOLOR");
  55550. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55551. }
  55552. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55553. return _this;
  55554. }
  55555. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55556. /**
  55557. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55558. * This margin is expressed in world space coordinates, so its value may vary.
  55559. * Default value is 0.1
  55560. * @returns the intersection Threshold value.
  55561. */
  55562. get: function () {
  55563. return this._intersectionThreshold;
  55564. },
  55565. /**
  55566. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55567. * This margin is expressed in world space coordinates, so its value may vary.
  55568. * @param value the new threshold to apply
  55569. */
  55570. set: function (value) {
  55571. if (this._intersectionThreshold === value) {
  55572. return;
  55573. }
  55574. this._intersectionThreshold = value;
  55575. if (this.geometry) {
  55576. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55577. }
  55578. },
  55579. enumerable: true,
  55580. configurable: true
  55581. });
  55582. /**
  55583. * Returns the string "LineMesh"
  55584. */
  55585. LinesMesh.prototype.getClassName = function () {
  55586. return "LinesMesh";
  55587. };
  55588. Object.defineProperty(LinesMesh.prototype, "material", {
  55589. get: function () {
  55590. return this._colorShader;
  55591. },
  55592. set: function (value) {
  55593. // Do nothing
  55594. },
  55595. enumerable: true,
  55596. configurable: true
  55597. });
  55598. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55599. get: function () {
  55600. return false;
  55601. },
  55602. enumerable: true,
  55603. configurable: true
  55604. });
  55605. LinesMesh.prototype.createInstance = function (name) {
  55606. throw new Error("LinesMeshes do not support createInstance.");
  55607. };
  55608. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55609. if (!this._geometry) {
  55610. return this;
  55611. }
  55612. // VBOs
  55613. this._geometry._bind(this._colorShader.getEffect());
  55614. // Color
  55615. if (!this.useVertexColor) {
  55616. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55617. }
  55618. return this;
  55619. };
  55620. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55621. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55622. return this;
  55623. }
  55624. var engine = this.getScene().getEngine();
  55625. // Draw order
  55626. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55627. return this;
  55628. };
  55629. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55630. this._colorShader.dispose();
  55631. _super.prototype.dispose.call(this, doNotRecurse);
  55632. };
  55633. /**
  55634. * Returns a new LineMesh object cloned from the current one.
  55635. */
  55636. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55637. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55638. };
  55639. return LinesMesh;
  55640. }(BABYLON.Mesh));
  55641. BABYLON.LinesMesh = LinesMesh;
  55642. })(BABYLON || (BABYLON = {}));
  55643. //# sourceMappingURL=babylon.linesMesh.js.map
  55644. var BABYLON;
  55645. (function (BABYLON) {
  55646. var MeshBuilder = /** @class */ (function () {
  55647. function MeshBuilder() {
  55648. }
  55649. MeshBuilder.updateSideOrientation = function (orientation) {
  55650. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55651. return BABYLON.Mesh.DOUBLESIDE;
  55652. }
  55653. if (orientation === undefined || orientation === null) {
  55654. return BABYLON.Mesh.FRONTSIDE;
  55655. }
  55656. return orientation;
  55657. };
  55658. /**
  55659. * Creates a box mesh.
  55660. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55661. * The parameter `size` sets the size (float) of each box side (default 1).
  55662. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55663. * 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).
  55664. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55666. * 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).
  55667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55669. */
  55670. MeshBuilder.CreateBox = function (name, options, scene) {
  55671. if (scene === void 0) { scene = null; }
  55672. var box = new BABYLON.Mesh(name, scene);
  55673. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55674. box._originalBuilderSideOrientation = options.sideOrientation;
  55675. var vertexData = BABYLON.VertexData.CreateBox(options);
  55676. vertexData.applyToMesh(box, options.updatable);
  55677. return box;
  55678. };
  55679. /**
  55680. * Creates a sphere mesh.
  55681. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55682. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55683. * 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`).
  55684. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55685. * 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
  55686. * 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).
  55687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55688. * 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).
  55689. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55691. */
  55692. MeshBuilder.CreateSphere = function (name, options, scene) {
  55693. var sphere = new BABYLON.Mesh(name, scene);
  55694. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55695. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55696. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55697. vertexData.applyToMesh(sphere, options.updatable);
  55698. return sphere;
  55699. };
  55700. /**
  55701. * Creates a plane polygonal mesh. By default, this is a disc.
  55702. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55703. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55704. * 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.
  55705. * 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
  55706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55707. * 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).
  55708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55710. */
  55711. MeshBuilder.CreateDisc = function (name, options, scene) {
  55712. if (scene === void 0) { scene = null; }
  55713. var disc = new BABYLON.Mesh(name, scene);
  55714. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55715. disc._originalBuilderSideOrientation = options.sideOrientation;
  55716. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55717. vertexData.applyToMesh(disc, options.updatable);
  55718. return disc;
  55719. };
  55720. /**
  55721. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55722. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55723. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55724. * 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`).
  55725. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55726. * 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.
  55727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55728. * 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).
  55729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55731. */
  55732. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55733. var sphere = new BABYLON.Mesh(name, scene);
  55734. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55735. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55736. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55737. vertexData.applyToMesh(sphere, options.updatable);
  55738. return sphere;
  55739. };
  55740. ;
  55741. /**
  55742. * Creates a ribbon mesh.
  55743. * 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.
  55744. *
  55745. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55746. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55747. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55748. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55749. * 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.
  55750. * 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.
  55751. * 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
  55752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55753. * 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).
  55754. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55755. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55756. * 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.
  55757. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55758. * 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
  55759. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55760. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55762. */
  55763. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55764. if (scene === void 0) { scene = null; }
  55765. var pathArray = options.pathArray;
  55766. var closeArray = options.closeArray;
  55767. var closePath = options.closePath;
  55768. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55769. var instance = options.instance;
  55770. var updatable = options.updatable;
  55771. if (instance) {
  55772. // positionFunction : ribbon case
  55773. // only pathArray and sideOrientation parameters are taken into account for positions update
  55774. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55775. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55776. var positionFunction = function (positions) {
  55777. var minlg = pathArray[0].length;
  55778. var i = 0;
  55779. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55780. for (var si = 1; si <= ns; si++) {
  55781. for (var p = 0; p < pathArray.length; p++) {
  55782. var path = pathArray[p];
  55783. var l = path.length;
  55784. minlg = (minlg < l) ? minlg : l;
  55785. var j = 0;
  55786. while (j < minlg) {
  55787. positions[i] = path[j].x;
  55788. positions[i + 1] = path[j].y;
  55789. positions[i + 2] = path[j].z;
  55790. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55791. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55792. }
  55793. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55794. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55795. }
  55796. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55797. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55798. }
  55799. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55800. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55801. }
  55802. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55803. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55804. }
  55805. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55806. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55807. }
  55808. j++;
  55809. i += 3;
  55810. }
  55811. if (instance._closePath) {
  55812. positions[i] = path[0].x;
  55813. positions[i + 1] = path[0].y;
  55814. positions[i + 2] = path[0].z;
  55815. i += 3;
  55816. }
  55817. }
  55818. }
  55819. };
  55820. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55821. positionFunction(positions);
  55822. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55823. instance._boundingInfo.update(instance._worldMatrix);
  55824. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55825. if (options.colors) {
  55826. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55827. for (var c = 0; c < options.colors.length; c++) {
  55828. colors[c * 4] = options.colors[c].r;
  55829. colors[c * 4 + 1] = options.colors[c].g;
  55830. colors[c * 4 + 2] = options.colors[c].b;
  55831. colors[c * 4 + 3] = options.colors[c].a;
  55832. }
  55833. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55834. }
  55835. if (options.uvs) {
  55836. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55837. for (var i = 0; i < options.uvs.length; i++) {
  55838. uvs[i * 2] = options.uvs[i].x;
  55839. uvs[i * 2 + 1] = options.uvs[i].y;
  55840. }
  55841. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55842. }
  55843. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55844. var indices = instance.getIndices();
  55845. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55846. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55847. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55848. if (instance._closePath) {
  55849. var indexFirst = 0;
  55850. var indexLast = 0;
  55851. for (var p = 0; p < pathArray.length; p++) {
  55852. indexFirst = instance._idx[p] * 3;
  55853. if (p + 1 < pathArray.length) {
  55854. indexLast = (instance._idx[p + 1] - 1) * 3;
  55855. }
  55856. else {
  55857. indexLast = normals.length - 3;
  55858. }
  55859. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55860. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55861. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55862. normals[indexLast] = normals[indexFirst];
  55863. normals[indexLast + 1] = normals[indexFirst + 1];
  55864. normals[indexLast + 2] = normals[indexFirst + 2];
  55865. }
  55866. }
  55867. if (!(instance.areNormalsFrozen)) {
  55868. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55869. }
  55870. }
  55871. return instance;
  55872. }
  55873. else {
  55874. var ribbon = new BABYLON.Mesh(name, scene);
  55875. ribbon._originalBuilderSideOrientation = sideOrientation;
  55876. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55877. if (closePath) {
  55878. ribbon._idx = vertexData._idx;
  55879. }
  55880. ribbon._closePath = closePath;
  55881. ribbon._closeArray = closeArray;
  55882. vertexData.applyToMesh(ribbon, updatable);
  55883. return ribbon;
  55884. }
  55885. };
  55886. /**
  55887. * Creates a cylinder or a cone mesh.
  55888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55889. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55890. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55891. * 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.
  55892. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55893. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55894. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55895. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55896. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55897. * 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).
  55898. * 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
  55899. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55900. * 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
  55901. * 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.
  55902. * If `enclose` is false, a ring surface is one element.
  55903. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55904. * 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
  55905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55906. * 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).
  55907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55909. */
  55910. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55911. var cylinder = new BABYLON.Mesh(name, scene);
  55912. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55913. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55914. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55915. vertexData.applyToMesh(cylinder, options.updatable);
  55916. return cylinder;
  55917. };
  55918. /**
  55919. * Creates a torus mesh.
  55920. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55921. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55922. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55923. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55925. * 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).
  55926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55928. */
  55929. MeshBuilder.CreateTorus = function (name, options, scene) {
  55930. var torus = new BABYLON.Mesh(name, scene);
  55931. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55932. torus._originalBuilderSideOrientation = options.sideOrientation;
  55933. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55934. vertexData.applyToMesh(torus, options.updatable);
  55935. return torus;
  55936. };
  55937. /**
  55938. * Creates a torus knot mesh.
  55939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55940. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55941. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55942. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55943. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55945. * 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).
  55946. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55948. */
  55949. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55950. var torusKnot = new BABYLON.Mesh(name, scene);
  55951. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55952. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55953. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55954. vertexData.applyToMesh(torusKnot, options.updatable);
  55955. return torusKnot;
  55956. };
  55957. /**
  55958. * Creates a line system mesh.
  55959. * A line system is a pool of many lines gathered in a single mesh.
  55960. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55961. * 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.
  55962. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55963. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55964. * 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
  55965. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55966. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55967. * 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
  55968. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55970. */
  55971. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55972. var instance = options.instance;
  55973. var lines = options.lines;
  55974. var colors = options.colors;
  55975. if (instance) {
  55976. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55977. var vertexColor;
  55978. var lineColors;
  55979. if (colors) {
  55980. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55981. }
  55982. var i = 0;
  55983. var c = 0;
  55984. for (var l = 0; l < lines.length; l++) {
  55985. var points = lines[l];
  55986. for (var p = 0; p < points.length; p++) {
  55987. positions[i] = points[p].x;
  55988. positions[i + 1] = points[p].y;
  55989. positions[i + 2] = points[p].z;
  55990. if (colors && vertexColor) {
  55991. lineColors = colors[l];
  55992. vertexColor[c] = lineColors[p].r;
  55993. vertexColor[c + 1] = lineColors[p].g;
  55994. vertexColor[c + 2] = lineColors[p].b;
  55995. vertexColor[c + 3] = lineColors[p].a;
  55996. c += 4;
  55997. }
  55998. i += 3;
  55999. }
  56000. }
  56001. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56002. if (colors && vertexColor) {
  56003. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56004. }
  56005. return instance;
  56006. }
  56007. // line system creation
  56008. var useVertexColor = (colors) ? true : false;
  56009. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56010. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56011. vertexData.applyToMesh(lineSystem, options.updatable);
  56012. return lineSystem;
  56013. };
  56014. /**
  56015. * Creates a line mesh.
  56016. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56017. * 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.
  56018. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56019. * The parameter `points` is an array successive Vector3.
  56020. * 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
  56021. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56022. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56023. * When updating an instance, remember that only point positions can change, not the number of points.
  56024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56025. */
  56026. MeshBuilder.CreateLines = function (name, options, scene) {
  56027. if (scene === void 0) { scene = null; }
  56028. var colors = (options.colors) ? [options.colors] : null;
  56029. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56030. return lines;
  56031. };
  56032. /**
  56033. * Creates a dashed line mesh.
  56034. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56035. * 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.
  56036. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56037. * The parameter `points` is an array successive Vector3.
  56038. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56039. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56040. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56041. * 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
  56042. * When updating an instance, remember that only point positions can change, not the number of points.
  56043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56044. */
  56045. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56046. if (scene === void 0) { scene = null; }
  56047. var points = options.points;
  56048. var instance = options.instance;
  56049. var gapSize = options.gapSize || 1;
  56050. var dashSize = options.dashSize || 3;
  56051. if (instance) {
  56052. var positionFunction = function (positions) {
  56053. var curvect = BABYLON.Vector3.Zero();
  56054. var nbSeg = positions.length / 6;
  56055. var lg = 0;
  56056. var nb = 0;
  56057. var shft = 0;
  56058. var dashshft = 0;
  56059. var curshft = 0;
  56060. var p = 0;
  56061. var i = 0;
  56062. var j = 0;
  56063. for (i = 0; i < points.length - 1; i++) {
  56064. points[i + 1].subtractToRef(points[i], curvect);
  56065. lg += curvect.length();
  56066. }
  56067. shft = lg / nbSeg;
  56068. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56069. for (i = 0; i < points.length - 1; i++) {
  56070. points[i + 1].subtractToRef(points[i], curvect);
  56071. nb = Math.floor(curvect.length() / shft);
  56072. curvect.normalize();
  56073. j = 0;
  56074. while (j < nb && p < positions.length) {
  56075. curshft = shft * j;
  56076. positions[p] = points[i].x + curshft * curvect.x;
  56077. positions[p + 1] = points[i].y + curshft * curvect.y;
  56078. positions[p + 2] = points[i].z + curshft * curvect.z;
  56079. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56080. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56081. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56082. p += 6;
  56083. j++;
  56084. }
  56085. }
  56086. while (p < positions.length) {
  56087. positions[p] = points[i].x;
  56088. positions[p + 1] = points[i].y;
  56089. positions[p + 2] = points[i].z;
  56090. p += 3;
  56091. }
  56092. };
  56093. instance.updateMeshPositions(positionFunction, false);
  56094. return instance;
  56095. }
  56096. // dashed lines creation
  56097. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56098. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56099. vertexData.applyToMesh(dashedLines, options.updatable);
  56100. dashedLines.dashSize = dashSize;
  56101. dashedLines.gapSize = gapSize;
  56102. return dashedLines;
  56103. };
  56104. /**
  56105. * Creates an extruded shape mesh.
  56106. * 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.
  56107. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56108. *
  56109. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56110. * 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
  56111. * extruded along the Z axis.
  56112. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56113. * 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.
  56114. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56115. * 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
  56116. * 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
  56117. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56119. * 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).
  56120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56121. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56123. */
  56124. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56125. if (scene === void 0) { scene = null; }
  56126. var path = options.path;
  56127. var shape = options.shape;
  56128. var scale = options.scale || 1;
  56129. var rotation = options.rotation || 0;
  56130. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56131. var updatable = options.updatable;
  56132. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56133. var instance = options.instance || null;
  56134. var invertUV = options.invertUV || false;
  56135. 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);
  56136. };
  56137. /**
  56138. * Creates an custom extruded shape mesh.
  56139. * 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.
  56140. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56141. *
  56142. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56143. * 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
  56144. * extruded along the Z axis.
  56145. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56146. * 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
  56147. * and the distance of this point from the begining of the path :
  56148. * ```javascript
  56149. * var rotationFunction = function(i, distance) {
  56150. * // do things
  56151. * return rotationValue; }
  56152. * ```
  56153. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56154. * 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
  56155. * and the distance of this point from the begining of the path :
  56156. * ```javascript
  56157. * var scaleFunction = function(i, distance) {
  56158. * // do things
  56159. * return scaleValue;}
  56160. * ```
  56161. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56162. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56163. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56164. * 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
  56165. * 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
  56166. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56168. * 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).
  56169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56170. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56172. */
  56173. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56174. var path = options.path;
  56175. var shape = options.shape;
  56176. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56177. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56178. var ribbonCloseArray = options.ribbonCloseArray || false;
  56179. var ribbonClosePath = options.ribbonClosePath || false;
  56180. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56181. var updatable = options.updatable;
  56182. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56183. var instance = options.instance;
  56184. var invertUV = options.invertUV || false;
  56185. 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);
  56186. };
  56187. /**
  56188. * Creates lathe mesh.
  56189. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56191. *
  56192. * 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
  56193. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56194. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56195. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56196. * 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.
  56197. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56198. * 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
  56199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56200. * 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).
  56201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56202. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56204. */
  56205. MeshBuilder.CreateLathe = function (name, options, scene) {
  56206. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56207. var closed = (options.closed === undefined) ? true : options.closed;
  56208. var shape = options.shape;
  56209. var radius = options.radius || 1;
  56210. var tessellation = options.tessellation || 64;
  56211. var updatable = options.updatable;
  56212. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56213. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56214. var pi2 = Math.PI * 2;
  56215. var paths = new Array();
  56216. var invertUV = options.invertUV || false;
  56217. var i = 0;
  56218. var p = 0;
  56219. var step = pi2 / tessellation * arc;
  56220. var rotated;
  56221. var path = new Array();
  56222. ;
  56223. for (i = 0; i <= tessellation; i++) {
  56224. var path = [];
  56225. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56226. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56227. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56228. }
  56229. for (p = 0; p < shape.length; p++) {
  56230. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56231. path.push(rotated);
  56232. }
  56233. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56234. 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));
  56235. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56236. }
  56237. paths.push(path);
  56238. }
  56239. // lathe ribbon
  56240. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56241. return lathe;
  56242. };
  56243. /**
  56244. * Creates a plane mesh.
  56245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56246. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56247. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56248. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56250. * 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).
  56251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56253. */
  56254. MeshBuilder.CreatePlane = function (name, options, scene) {
  56255. var plane = new BABYLON.Mesh(name, scene);
  56256. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56257. plane._originalBuilderSideOrientation = options.sideOrientation;
  56258. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56259. vertexData.applyToMesh(plane, options.updatable);
  56260. if (options.sourcePlane) {
  56261. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56262. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56263. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56264. plane.rotate(vectorProduct, product);
  56265. }
  56266. return plane;
  56267. };
  56268. /**
  56269. * Creates a ground mesh.
  56270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56271. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56272. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56274. */
  56275. MeshBuilder.CreateGround = function (name, options, scene) {
  56276. var ground = new BABYLON.GroundMesh(name, scene);
  56277. ground._setReady(false);
  56278. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56279. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56280. ground._width = options.width || 1;
  56281. ground._height = options.height || 1;
  56282. ground._maxX = ground._width / 2;
  56283. ground._maxZ = ground._height / 2;
  56284. ground._minX = -ground._maxX;
  56285. ground._minZ = -ground._maxZ;
  56286. var vertexData = BABYLON.VertexData.CreateGround(options);
  56287. vertexData.applyToMesh(ground, options.updatable);
  56288. ground._setReady(true);
  56289. return ground;
  56290. };
  56291. /**
  56292. * Creates a tiled ground mesh.
  56293. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56294. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56295. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56296. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56297. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56298. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56299. * numbers of subdivisions on the ground width and height of each tile.
  56300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56301. */
  56302. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56303. var tiledGround = new BABYLON.Mesh(name, scene);
  56304. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56305. vertexData.applyToMesh(tiledGround, options.updatable);
  56306. return tiledGround;
  56307. };
  56308. /**
  56309. * Creates a ground mesh from a height map.
  56310. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56311. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56312. * The parameter `url` sets the URL of the height map image resource.
  56313. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56314. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56315. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56316. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56317. * 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.
  56318. * 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).
  56319. * This function is passed the newly built mesh :
  56320. * ```javascript
  56321. * function(mesh) { // do things
  56322. * return; }
  56323. * ```
  56324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56325. */
  56326. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56327. var width = options.width || 10.0;
  56328. var height = options.height || 10.0;
  56329. var subdivisions = options.subdivisions || 1 | 0;
  56330. var minHeight = options.minHeight || 0.0;
  56331. var maxHeight = options.maxHeight || 1.0;
  56332. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56333. var updatable = options.updatable;
  56334. var onReady = options.onReady;
  56335. var ground = new BABYLON.GroundMesh(name, scene);
  56336. ground._subdivisionsX = subdivisions;
  56337. ground._subdivisionsY = subdivisions;
  56338. ground._width = width;
  56339. ground._height = height;
  56340. ground._maxX = ground._width / 2.0;
  56341. ground._maxZ = ground._height / 2.0;
  56342. ground._minX = -ground._maxX;
  56343. ground._minZ = -ground._maxZ;
  56344. ground._setReady(false);
  56345. var onload = function (img) {
  56346. // Getting height map data
  56347. var canvas = document.createElement("canvas");
  56348. var context = canvas.getContext("2d");
  56349. if (!context) {
  56350. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56351. }
  56352. if (scene.isDisposed) {
  56353. return;
  56354. }
  56355. var bufferWidth = img.width;
  56356. var bufferHeight = img.height;
  56357. canvas.width = bufferWidth;
  56358. canvas.height = bufferHeight;
  56359. context.drawImage(img, 0, 0);
  56360. // Create VertexData from map data
  56361. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56362. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56363. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56364. width: width, height: height,
  56365. subdivisions: subdivisions,
  56366. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56367. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56368. });
  56369. vertexData.applyToMesh(ground, updatable);
  56370. ground._setReady(true);
  56371. //execute ready callback, if set
  56372. if (onReady) {
  56373. onReady(ground);
  56374. }
  56375. };
  56376. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56377. return ground;
  56378. };
  56379. /**
  56380. * Creates a polygon mesh.
  56381. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56382. * 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.
  56383. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56385. * 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).
  56386. * Remember you can only change the shape positions, not their number when updating a polygon.
  56387. */
  56388. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56389. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56390. var shape = options.shape;
  56391. var holes = options.holes || [];
  56392. var depth = options.depth || 0;
  56393. var contours = [];
  56394. var hole = [];
  56395. for (var i = 0; i < shape.length; i++) {
  56396. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56397. }
  56398. var epsilon = 0.00000001;
  56399. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56400. contours.pop();
  56401. }
  56402. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56403. for (var hNb = 0; hNb < holes.length; hNb++) {
  56404. hole = [];
  56405. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56406. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56407. }
  56408. polygonTriangulation.addHole(hole);
  56409. }
  56410. var polygon = polygonTriangulation.build(options.updatable, depth);
  56411. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56412. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56413. vertexData.applyToMesh(polygon, options.updatable);
  56414. return polygon;
  56415. };
  56416. ;
  56417. /**
  56418. * Creates an extruded polygon mesh, with depth in the Y direction.
  56419. * 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).
  56420. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56421. */
  56422. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56423. return MeshBuilder.CreatePolygon(name, options, scene);
  56424. };
  56425. ;
  56426. /**
  56427. * Creates a tube mesh.
  56428. * 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.
  56429. *
  56430. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56431. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56432. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56433. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56434. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56435. * 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.
  56436. * It must return a radius value (positive float) :
  56437. * ```javascript
  56438. * var radiusFunction = function(i, distance) {
  56439. * // do things
  56440. * return radius; }
  56441. * ```
  56442. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56443. * 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
  56444. * 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
  56445. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56446. * 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).
  56447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56448. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56450. */
  56451. MeshBuilder.CreateTube = function (name, options, scene) {
  56452. var path = options.path;
  56453. var instance = options.instance;
  56454. var radius = 1.0;
  56455. if (instance) {
  56456. radius = instance.radius;
  56457. }
  56458. if (options.radius !== undefined) {
  56459. radius = options.radius;
  56460. }
  56461. ;
  56462. var tessellation = options.tessellation || 64 | 0;
  56463. var radiusFunction = options.radiusFunction || null;
  56464. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56465. var invertUV = options.invertUV || false;
  56466. var updatable = options.updatable;
  56467. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56468. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56469. // tube geometry
  56470. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56471. var tangents = path3D.getTangents();
  56472. var normals = path3D.getNormals();
  56473. var distances = path3D.getDistances();
  56474. var pi2 = Math.PI * 2;
  56475. var step = pi2 / tessellation * arc;
  56476. var returnRadius = function () { return radius; };
  56477. var radiusFunctionFinal = radiusFunction || returnRadius;
  56478. var circlePath;
  56479. var rad;
  56480. var normal;
  56481. var rotated;
  56482. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56483. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56484. for (var i = 0; i < path.length; i++) {
  56485. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56486. circlePath = Array(); // current circle array
  56487. normal = normals[i]; // current normal
  56488. for (var t = 0; t < tessellation; t++) {
  56489. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56490. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56491. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56492. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56493. circlePath[t] = rotated;
  56494. }
  56495. circlePaths[index] = circlePath;
  56496. index++;
  56497. }
  56498. // cap
  56499. var capPath = function (nbPoints, pathIndex) {
  56500. var pointCap = Array();
  56501. for (var i = 0; i < nbPoints; i++) {
  56502. pointCap.push(path[pathIndex]);
  56503. }
  56504. return pointCap;
  56505. };
  56506. switch (cap) {
  56507. case BABYLON.Mesh.NO_CAP:
  56508. break;
  56509. case BABYLON.Mesh.CAP_START:
  56510. circlePaths[0] = capPath(tessellation, 0);
  56511. circlePaths[1] = circlePaths[2].slice(0);
  56512. break;
  56513. case BABYLON.Mesh.CAP_END:
  56514. circlePaths[index] = circlePaths[index - 1].slice(0);
  56515. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56516. break;
  56517. case BABYLON.Mesh.CAP_ALL:
  56518. circlePaths[0] = capPath(tessellation, 0);
  56519. circlePaths[1] = circlePaths[2].slice(0);
  56520. circlePaths[index] = circlePaths[index - 1].slice(0);
  56521. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56522. break;
  56523. default:
  56524. break;
  56525. }
  56526. return circlePaths;
  56527. };
  56528. var path3D;
  56529. var pathArray;
  56530. if (instance) {
  56531. var arc = options.arc || instance.arc;
  56532. path3D = (instance.path3D).update(path);
  56533. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56534. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56535. instance.path3D = path3D;
  56536. instance.pathArray = pathArray;
  56537. instance.arc = arc;
  56538. instance.radius = radius;
  56539. return instance;
  56540. }
  56541. // tube creation
  56542. path3D = new BABYLON.Path3D(path);
  56543. var newPathArray = new Array();
  56544. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56545. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56546. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56547. tube.pathArray = pathArray;
  56548. tube.path3D = path3D;
  56549. tube.tessellation = tessellation;
  56550. tube.cap = cap;
  56551. tube.arc = options.arc;
  56552. tube.radius = radius;
  56553. return tube;
  56554. };
  56555. /**
  56556. * Creates a polyhedron mesh.
  56557. *
  56558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56559. * 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
  56560. * to choose the wanted type.
  56561. * The parameter `size` (positive float, default 1) sets the polygon size.
  56562. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56563. * 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`.
  56564. * 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
  56565. * 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)`).
  56566. * 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
  56567. * 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.
  56568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56569. * 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).
  56570. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56572. */
  56573. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56574. var polyhedron = new BABYLON.Mesh(name, scene);
  56575. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56576. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56577. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56578. vertexData.applyToMesh(polyhedron, options.updatable);
  56579. return polyhedron;
  56580. };
  56581. /**
  56582. * Creates a decal mesh.
  56583. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56584. * 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.
  56585. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56586. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56587. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56588. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56589. */
  56590. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56591. var indices = sourceMesh.getIndices();
  56592. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56593. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56594. var position = options.position || BABYLON.Vector3.Zero();
  56595. var normal = options.normal || BABYLON.Vector3.Up();
  56596. var size = options.size || BABYLON.Vector3.One();
  56597. var angle = options.angle || 0;
  56598. // Getting correct rotation
  56599. if (!normal) {
  56600. var target = new BABYLON.Vector3(0, 0, 1);
  56601. var camera = sourceMesh.getScene().activeCamera;
  56602. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56603. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56604. }
  56605. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56606. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56607. var pitch = Math.atan2(normal.y, len);
  56608. // Matrix
  56609. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56610. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56611. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56612. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56613. var vertexData = new BABYLON.VertexData();
  56614. vertexData.indices = [];
  56615. vertexData.positions = [];
  56616. vertexData.normals = [];
  56617. vertexData.uvs = [];
  56618. var currentVertexDataIndex = 0;
  56619. var extractDecalVector3 = function (indexId) {
  56620. var result = new BABYLON.PositionNormalVertex();
  56621. if (!indices || !positions || !normals) {
  56622. return result;
  56623. }
  56624. var vertexId = indices[indexId];
  56625. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56626. // Send vector to decal local world
  56627. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56628. // Get normal
  56629. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56630. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56631. return result;
  56632. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56633. var clip = function (vertices, axis) {
  56634. if (vertices.length === 0) {
  56635. return vertices;
  56636. }
  56637. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56638. var clipVertices = function (v0, v1) {
  56639. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56640. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56641. };
  56642. var result = new Array();
  56643. for (var index = 0; index < vertices.length; index += 3) {
  56644. var v1Out;
  56645. var v2Out;
  56646. var v3Out;
  56647. var total = 0;
  56648. var nV1 = null;
  56649. var nV2 = null;
  56650. var nV3 = null;
  56651. var nV4 = null;
  56652. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56653. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56654. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56655. v1Out = d1 > 0;
  56656. v2Out = d2 > 0;
  56657. v3Out = d3 > 0;
  56658. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56659. switch (total) {
  56660. case 0:
  56661. result.push(vertices[index]);
  56662. result.push(vertices[index + 1]);
  56663. result.push(vertices[index + 2]);
  56664. break;
  56665. case 1:
  56666. if (v1Out) {
  56667. nV1 = vertices[index + 1];
  56668. nV2 = vertices[index + 2];
  56669. nV3 = clipVertices(vertices[index], nV1);
  56670. nV4 = clipVertices(vertices[index], nV2);
  56671. }
  56672. if (v2Out) {
  56673. nV1 = vertices[index];
  56674. nV2 = vertices[index + 2];
  56675. nV3 = clipVertices(vertices[index + 1], nV1);
  56676. nV4 = clipVertices(vertices[index + 1], nV2);
  56677. result.push(nV3);
  56678. result.push(nV2.clone());
  56679. result.push(nV1.clone());
  56680. result.push(nV2.clone());
  56681. result.push(nV3.clone());
  56682. result.push(nV4);
  56683. break;
  56684. }
  56685. if (v3Out) {
  56686. nV1 = vertices[index];
  56687. nV2 = vertices[index + 1];
  56688. nV3 = clipVertices(vertices[index + 2], nV1);
  56689. nV4 = clipVertices(vertices[index + 2], nV2);
  56690. }
  56691. if (nV1 && nV2 && nV3 && nV4) {
  56692. result.push(nV1.clone());
  56693. result.push(nV2.clone());
  56694. result.push(nV3);
  56695. result.push(nV4);
  56696. result.push(nV3.clone());
  56697. result.push(nV2.clone());
  56698. }
  56699. break;
  56700. case 2:
  56701. if (!v1Out) {
  56702. nV1 = vertices[index].clone();
  56703. nV2 = clipVertices(nV1, vertices[index + 1]);
  56704. nV3 = clipVertices(nV1, vertices[index + 2]);
  56705. result.push(nV1);
  56706. result.push(nV2);
  56707. result.push(nV3);
  56708. }
  56709. if (!v2Out) {
  56710. nV1 = vertices[index + 1].clone();
  56711. nV2 = clipVertices(nV1, vertices[index + 2]);
  56712. nV3 = clipVertices(nV1, vertices[index]);
  56713. result.push(nV1);
  56714. result.push(nV2);
  56715. result.push(nV3);
  56716. }
  56717. if (!v3Out) {
  56718. nV1 = vertices[index + 2].clone();
  56719. nV2 = clipVertices(nV1, vertices[index]);
  56720. nV3 = clipVertices(nV1, vertices[index + 1]);
  56721. result.push(nV1);
  56722. result.push(nV2);
  56723. result.push(nV3);
  56724. }
  56725. break;
  56726. case 3:
  56727. break;
  56728. }
  56729. }
  56730. return result;
  56731. };
  56732. for (var index = 0; index < indices.length; index += 3) {
  56733. var faceVertices = new Array();
  56734. faceVertices.push(extractDecalVector3(index));
  56735. faceVertices.push(extractDecalVector3(index + 1));
  56736. faceVertices.push(extractDecalVector3(index + 2));
  56737. // Clip
  56738. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56739. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56740. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56741. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56742. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56743. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56744. if (faceVertices.length === 0) {
  56745. continue;
  56746. }
  56747. // Add UVs and get back to world
  56748. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56749. var vertex = faceVertices[vIndex];
  56750. //TODO check for Int32Array | Uint32Array | Uint16Array
  56751. vertexData.indices.push(currentVertexDataIndex);
  56752. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56753. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56754. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56755. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56756. currentVertexDataIndex++;
  56757. }
  56758. }
  56759. // Return mesh
  56760. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56761. vertexData.applyToMesh(decal);
  56762. decal.position = position.clone();
  56763. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56764. return decal;
  56765. };
  56766. // Privates
  56767. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56768. // extrusion geometry
  56769. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56770. var tangents = path3D.getTangents();
  56771. var normals = path3D.getNormals();
  56772. var binormals = path3D.getBinormals();
  56773. var distances = path3D.getDistances();
  56774. var angle = 0;
  56775. var returnScale = function () { return scale !== null ? scale : 1; };
  56776. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56777. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56778. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56779. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56780. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56781. for (var i = 0; i < curve.length; i++) {
  56782. var shapePath = new Array();
  56783. var angleStep = rotate(i, distances[i]);
  56784. var scaleRatio = scl(i, distances[i]);
  56785. for (var p = 0; p < shape.length; p++) {
  56786. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56787. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56788. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56789. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56790. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56791. shapePath[p] = rotated;
  56792. }
  56793. shapePaths[index] = shapePath;
  56794. angle += angleStep;
  56795. index++;
  56796. }
  56797. // cap
  56798. var capPath = function (shapePath) {
  56799. var pointCap = Array();
  56800. var barycenter = BABYLON.Vector3.Zero();
  56801. var i;
  56802. for (i = 0; i < shapePath.length; i++) {
  56803. barycenter.addInPlace(shapePath[i]);
  56804. }
  56805. barycenter.scaleInPlace(1.0 / shapePath.length);
  56806. for (i = 0; i < shapePath.length; i++) {
  56807. pointCap.push(barycenter);
  56808. }
  56809. return pointCap;
  56810. };
  56811. switch (cap) {
  56812. case BABYLON.Mesh.NO_CAP:
  56813. break;
  56814. case BABYLON.Mesh.CAP_START:
  56815. shapePaths[0] = capPath(shapePaths[2]);
  56816. shapePaths[1] = shapePaths[2];
  56817. break;
  56818. case BABYLON.Mesh.CAP_END:
  56819. shapePaths[index] = shapePaths[index - 1];
  56820. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56821. break;
  56822. case BABYLON.Mesh.CAP_ALL:
  56823. shapePaths[0] = capPath(shapePaths[2]);
  56824. shapePaths[1] = shapePaths[2];
  56825. shapePaths[index] = shapePaths[index - 1];
  56826. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56827. break;
  56828. default:
  56829. break;
  56830. }
  56831. return shapePaths;
  56832. };
  56833. var path3D;
  56834. var pathArray;
  56835. if (instance) {
  56836. path3D = (instance.path3D).update(curve);
  56837. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56838. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56839. return instance;
  56840. }
  56841. // extruded shape creation
  56842. path3D = new BABYLON.Path3D(curve);
  56843. var newShapePaths = new Array();
  56844. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56845. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56846. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56847. extrudedGeneric.pathArray = pathArray;
  56848. extrudedGeneric.path3D = path3D;
  56849. extrudedGeneric.cap = cap;
  56850. return extrudedGeneric;
  56851. };
  56852. return MeshBuilder;
  56853. }());
  56854. BABYLON.MeshBuilder = MeshBuilder;
  56855. })(BABYLON || (BABYLON = {}));
  56856. //# sourceMappingURL=babylon.meshBuilder.js.map
  56857. var BABYLON;
  56858. (function (BABYLON) {
  56859. /**
  56860. * Draco compression (https://google.github.io/draco/)
  56861. */
  56862. var DracoCompression = /** @class */ (function () {
  56863. /**
  56864. * Constructor
  56865. * @param numWorkers The number of workers for async operations
  56866. */
  56867. function DracoCompression(numWorkers) {
  56868. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56869. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56870. if (!workerBlobUrl || !Worker) {
  56871. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56872. return;
  56873. }
  56874. var workers = new Array(numWorkers);
  56875. for (var i = 0; i < workers.length; i++) {
  56876. var worker = new Worker(workerBlobUrl);
  56877. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56878. workers[i] = worker;
  56879. }
  56880. this._workerPool = new BABYLON.WorkerPool(workers);
  56881. }
  56882. /**
  56883. * Stop all async operations and release resources.
  56884. */
  56885. DracoCompression.prototype.dispose = function () {
  56886. this._workerPool.dispose();
  56887. delete this._workerPool;
  56888. };
  56889. /**
  56890. * Decode Draco compressed mesh data to vertex data.
  56891. * @param data The array buffer view for the Draco compression data
  56892. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56893. * @returns A promise that resolves with the decoded vertex data
  56894. */
  56895. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56896. var _this = this;
  56897. return new Promise(function (resolve, reject) {
  56898. _this._workerPool.push(function (worker, onComplete) {
  56899. var vertexData = new BABYLON.VertexData();
  56900. var onError = function (error) {
  56901. worker.removeEventListener("error", onError);
  56902. worker.removeEventListener("message", onMessage);
  56903. reject(error);
  56904. onComplete();
  56905. };
  56906. var onMessage = function (message) {
  56907. if (message.data === "done") {
  56908. worker.removeEventListener("error", onError);
  56909. worker.removeEventListener("message", onMessage);
  56910. resolve(vertexData);
  56911. onComplete();
  56912. }
  56913. else if (message.data.id === "indices") {
  56914. vertexData.indices = message.data.value;
  56915. }
  56916. else {
  56917. vertexData.set(message.data.value, message.data.id);
  56918. }
  56919. };
  56920. worker.addEventListener("error", onError);
  56921. worker.addEventListener("message", onMessage);
  56922. var dataCopy = new Uint8Array(data.byteLength);
  56923. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56924. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56925. });
  56926. });
  56927. };
  56928. /**
  56929. * The worker function that gets converted to a blob url to pass into a worker.
  56930. */
  56931. DracoCompression._Worker = function () {
  56932. // self is actually a DedicatedWorkerGlobalScope
  56933. var _self = self;
  56934. var decodeMesh = function (data, attributes) {
  56935. var dracoModule = new DracoDecoderModule();
  56936. var buffer = new dracoModule.DecoderBuffer();
  56937. buffer.Init(data, data.byteLength);
  56938. var decoder = new dracoModule.Decoder();
  56939. var geometry;
  56940. var status;
  56941. try {
  56942. var type = decoder.GetEncodedGeometryType(buffer);
  56943. switch (type) {
  56944. case dracoModule.TRIANGULAR_MESH:
  56945. geometry = new dracoModule.Mesh();
  56946. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56947. break;
  56948. case dracoModule.POINT_CLOUD:
  56949. geometry = new dracoModule.PointCloud();
  56950. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56951. break;
  56952. default:
  56953. throw new Error("Invalid geometry type " + type);
  56954. }
  56955. if (!status.ok() || !geometry.ptr) {
  56956. throw new Error(status.error_msg());
  56957. }
  56958. var numPoints = geometry.num_points();
  56959. if (type === dracoModule.TRIANGULAR_MESH) {
  56960. var numFaces = geometry.num_faces();
  56961. var faceIndices = new dracoModule.DracoInt32Array();
  56962. try {
  56963. var indices = new Uint32Array(numFaces * 3);
  56964. for (var i = 0; i < numFaces; i++) {
  56965. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56966. var offset = i * 3;
  56967. indices[offset + 0] = faceIndices.GetValue(0);
  56968. indices[offset + 1] = faceIndices.GetValue(1);
  56969. indices[offset + 2] = faceIndices.GetValue(2);
  56970. }
  56971. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56972. }
  56973. finally {
  56974. dracoModule.destroy(faceIndices);
  56975. }
  56976. }
  56977. for (var kind in attributes) {
  56978. var uniqueId = attributes[kind];
  56979. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56980. var dracoData = new dracoModule.DracoFloat32Array();
  56981. try {
  56982. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56983. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56984. for (var i = 0; i < babylonData.length; i++) {
  56985. babylonData[i] = dracoData.GetValue(i);
  56986. }
  56987. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56988. }
  56989. finally {
  56990. dracoModule.destroy(dracoData);
  56991. }
  56992. }
  56993. }
  56994. finally {
  56995. if (geometry) {
  56996. dracoModule.destroy(geometry);
  56997. }
  56998. dracoModule.destroy(decoder);
  56999. dracoModule.destroy(buffer);
  57000. }
  57001. _self.postMessage("done");
  57002. };
  57003. _self.onmessage = function (event) {
  57004. switch (event.data.id) {
  57005. case "initDecoder": {
  57006. importScripts(event.data.url);
  57007. break;
  57008. }
  57009. case "decodeMesh": {
  57010. decodeMesh(event.data.data, event.data.attributes);
  57011. break;
  57012. }
  57013. }
  57014. };
  57015. };
  57016. DracoCompression._GetDefaultDecoderUrl = function () {
  57017. if (!BABYLON.Tools.IsWindowObjectExist) {
  57018. return null;
  57019. }
  57020. for (var i = 0; i < document.scripts.length; i++) {
  57021. if (document.scripts[i].type === "text/x-draco-decoder") {
  57022. return document.scripts[i].src;
  57023. }
  57024. }
  57025. return null;
  57026. };
  57027. /**
  57028. * Gets the url to the draco decoder if available.
  57029. */
  57030. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57031. return DracoCompression;
  57032. }());
  57033. BABYLON.DracoCompression = DracoCompression;
  57034. })(BABYLON || (BABYLON = {}));
  57035. //# sourceMappingURL=babylon.dracoCompression.js.map
  57036. var BABYLON;
  57037. (function (BABYLON) {
  57038. var AudioEngine = /** @class */ (function () {
  57039. function AudioEngine() {
  57040. this._audioContext = null;
  57041. this._audioContextInitialized = false;
  57042. this.canUseWebAudio = false;
  57043. this.WarnedWebAudioUnsupported = false;
  57044. this.unlocked = false;
  57045. this.isMP3supported = false;
  57046. this.isOGGsupported = false;
  57047. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57048. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57049. this.canUseWebAudio = true;
  57050. }
  57051. var audioElem = document.createElement('audio');
  57052. try {
  57053. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57054. this.isMP3supported = true;
  57055. }
  57056. }
  57057. catch (e) {
  57058. // protect error during capability check.
  57059. }
  57060. try {
  57061. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57062. this.isOGGsupported = true;
  57063. }
  57064. }
  57065. catch (e) {
  57066. // protect error during capability check.
  57067. }
  57068. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57069. this._unlockiOSaudio();
  57070. }
  57071. else {
  57072. this.unlocked = true;
  57073. }
  57074. }
  57075. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57076. get: function () {
  57077. if (!this._audioContextInitialized) {
  57078. this._initializeAudioContext();
  57079. }
  57080. return this._audioContext;
  57081. },
  57082. enumerable: true,
  57083. configurable: true
  57084. });
  57085. AudioEngine.prototype._unlockiOSaudio = function () {
  57086. var _this = this;
  57087. var unlockaudio = function () {
  57088. if (!_this.audioContext) {
  57089. return;
  57090. }
  57091. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57092. var source = _this.audioContext.createBufferSource();
  57093. source.buffer = buffer;
  57094. source.connect(_this.audioContext.destination);
  57095. source.start(0);
  57096. setTimeout(function () {
  57097. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57098. _this.unlocked = true;
  57099. window.removeEventListener('touchend', unlockaudio, false);
  57100. if (_this.onAudioUnlocked) {
  57101. _this.onAudioUnlocked();
  57102. }
  57103. }
  57104. }, 0);
  57105. };
  57106. window.addEventListener('touchend', unlockaudio, false);
  57107. };
  57108. AudioEngine.prototype._initializeAudioContext = function () {
  57109. try {
  57110. if (this.canUseWebAudio) {
  57111. this._audioContext = new AudioContext();
  57112. // create a global volume gain node
  57113. this.masterGain = this._audioContext.createGain();
  57114. this.masterGain.gain.value = 1;
  57115. this.masterGain.connect(this._audioContext.destination);
  57116. this._audioContextInitialized = true;
  57117. }
  57118. }
  57119. catch (e) {
  57120. this.canUseWebAudio = false;
  57121. BABYLON.Tools.Error("Web Audio: " + e.message);
  57122. }
  57123. };
  57124. AudioEngine.prototype.dispose = function () {
  57125. if (this.canUseWebAudio && this._audioContextInitialized) {
  57126. if (this._connectedAnalyser && this._audioContext) {
  57127. this._connectedAnalyser.stopDebugCanvas();
  57128. this._connectedAnalyser.dispose();
  57129. this.masterGain.disconnect();
  57130. this.masterGain.connect(this._audioContext.destination);
  57131. this._connectedAnalyser = null;
  57132. }
  57133. this.masterGain.gain.value = 1;
  57134. }
  57135. this.WarnedWebAudioUnsupported = false;
  57136. };
  57137. AudioEngine.prototype.getGlobalVolume = function () {
  57138. if (this.canUseWebAudio && this._audioContextInitialized) {
  57139. return this.masterGain.gain.value;
  57140. }
  57141. else {
  57142. return -1;
  57143. }
  57144. };
  57145. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57146. if (this.canUseWebAudio && this._audioContextInitialized) {
  57147. this.masterGain.gain.value = newVolume;
  57148. }
  57149. };
  57150. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57151. if (this._connectedAnalyser) {
  57152. this._connectedAnalyser.stopDebugCanvas();
  57153. }
  57154. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57155. this._connectedAnalyser = analyser;
  57156. this.masterGain.disconnect();
  57157. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57158. }
  57159. };
  57160. return AudioEngine;
  57161. }());
  57162. BABYLON.AudioEngine = AudioEngine;
  57163. })(BABYLON || (BABYLON = {}));
  57164. //# sourceMappingURL=babylon.audioEngine.js.map
  57165. var BABYLON;
  57166. (function (BABYLON) {
  57167. var Sound = /** @class */ (function () {
  57168. /**
  57169. * Create a sound and attach it to a scene
  57170. * @param name Name of your sound
  57171. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57172. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57173. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57174. */
  57175. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57176. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57177. var _this = this;
  57178. this.autoplay = false;
  57179. this.loop = false;
  57180. this.useCustomAttenuation = false;
  57181. this.spatialSound = false;
  57182. this.refDistance = 1;
  57183. this.rolloffFactor = 1;
  57184. this.maxDistance = 100;
  57185. this.distanceModel = "linear";
  57186. this._panningModel = "equalpower";
  57187. this._playbackRate = 1;
  57188. this._streaming = false;
  57189. this._startTime = 0;
  57190. this._startOffset = 0;
  57191. this._position = BABYLON.Vector3.Zero();
  57192. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57193. this._volume = 1;
  57194. this._isReadyToPlay = false;
  57195. this.isPlaying = false;
  57196. this.isPaused = false;
  57197. this._isDirectional = false;
  57198. // Used if you'd like to create a directional sound.
  57199. // If not set, the sound will be omnidirectional
  57200. this._coneInnerAngle = 360;
  57201. this._coneOuterAngle = 360;
  57202. this._coneOuterGain = 0;
  57203. this._isOutputConnected = false;
  57204. this._urlType = "Unknown";
  57205. this.name = name;
  57206. this._scene = scene;
  57207. this._readyToPlayCallback = readyToPlayCallback;
  57208. // Default custom attenuation function is a linear attenuation
  57209. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57210. if (currentDistance < maxDistance) {
  57211. return currentVolume * (1 - currentDistance / maxDistance);
  57212. }
  57213. else {
  57214. return 0;
  57215. }
  57216. };
  57217. if (options) {
  57218. this.autoplay = options.autoplay || false;
  57219. this.loop = options.loop || false;
  57220. // if volume === 0, we need another way to check this option
  57221. if (options.volume !== undefined) {
  57222. this._volume = options.volume;
  57223. }
  57224. this.spatialSound = options.spatialSound || false;
  57225. this.maxDistance = options.maxDistance || 100;
  57226. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57227. this.rolloffFactor = options.rolloffFactor || 1;
  57228. this.refDistance = options.refDistance || 1;
  57229. this.distanceModel = options.distanceModel || "linear";
  57230. this._playbackRate = options.playbackRate || 1;
  57231. this._streaming = options.streaming || false;
  57232. }
  57233. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57234. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57235. this._soundGain.gain.value = this._volume;
  57236. this._inputAudioNode = this._soundGain;
  57237. this._ouputAudioNode = this._soundGain;
  57238. if (this.spatialSound) {
  57239. this._createSpatialParameters();
  57240. }
  57241. this._scene.mainSoundTrack.AddSound(this);
  57242. var validParameter = true;
  57243. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57244. if (urlOrArrayBuffer) {
  57245. if (typeof (urlOrArrayBuffer) === "string")
  57246. this._urlType = "String";
  57247. if (Array.isArray(urlOrArrayBuffer))
  57248. this._urlType = "Array";
  57249. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57250. this._urlType = "ArrayBuffer";
  57251. var urls = [];
  57252. var codecSupportedFound = false;
  57253. switch (this._urlType) {
  57254. case "ArrayBuffer":
  57255. if (urlOrArrayBuffer.byteLength > 0) {
  57256. codecSupportedFound = true;
  57257. this._soundLoaded(urlOrArrayBuffer);
  57258. }
  57259. break;
  57260. case "String":
  57261. urls.push(urlOrArrayBuffer);
  57262. case "Array":
  57263. if (urls.length === 0)
  57264. urls = urlOrArrayBuffer;
  57265. // If we found a supported format, we load it immediately and stop the loop
  57266. for (var i = 0; i < urls.length; i++) {
  57267. var url = urls[i];
  57268. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57269. codecSupportedFound = true;
  57270. }
  57271. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57272. codecSupportedFound = true;
  57273. }
  57274. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57275. codecSupportedFound = true;
  57276. }
  57277. if (url.indexOf("blob:") !== -1) {
  57278. codecSupportedFound = true;
  57279. }
  57280. if (codecSupportedFound) {
  57281. // Loading sound using XHR2
  57282. if (!this._streaming) {
  57283. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57284. }
  57285. else {
  57286. this._htmlAudioElement = new Audio(url);
  57287. this._htmlAudioElement.controls = false;
  57288. this._htmlAudioElement.loop = this.loop;
  57289. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57290. this._htmlAudioElement.preload = "auto";
  57291. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57292. _this._isReadyToPlay = true;
  57293. if (_this.autoplay) {
  57294. _this.play();
  57295. }
  57296. if (_this._readyToPlayCallback) {
  57297. _this._readyToPlayCallback();
  57298. }
  57299. });
  57300. document.body.appendChild(this._htmlAudioElement);
  57301. }
  57302. break;
  57303. }
  57304. }
  57305. break;
  57306. default:
  57307. validParameter = false;
  57308. break;
  57309. }
  57310. if (!validParameter) {
  57311. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57312. }
  57313. else {
  57314. if (!codecSupportedFound) {
  57315. this._isReadyToPlay = true;
  57316. // Simulating a ready to play event to avoid breaking code path
  57317. if (this._readyToPlayCallback) {
  57318. window.setTimeout(function () {
  57319. if (_this._readyToPlayCallback) {
  57320. _this._readyToPlayCallback();
  57321. }
  57322. }, 1000);
  57323. }
  57324. }
  57325. }
  57326. }
  57327. }
  57328. else {
  57329. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57330. this._scene.mainSoundTrack.AddSound(this);
  57331. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57332. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57333. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57334. }
  57335. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57336. if (this._readyToPlayCallback) {
  57337. window.setTimeout(function () {
  57338. if (_this._readyToPlayCallback) {
  57339. _this._readyToPlayCallback();
  57340. }
  57341. }, 1000);
  57342. }
  57343. }
  57344. }
  57345. Sound.prototype.dispose = function () {
  57346. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57347. if (this.isPlaying) {
  57348. this.stop();
  57349. }
  57350. this._isReadyToPlay = false;
  57351. if (this.soundTrackId === -1) {
  57352. this._scene.mainSoundTrack.RemoveSound(this);
  57353. }
  57354. else {
  57355. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57356. }
  57357. if (this._soundGain) {
  57358. this._soundGain.disconnect();
  57359. this._soundGain = null;
  57360. }
  57361. if (this._soundPanner) {
  57362. this._soundPanner.disconnect();
  57363. this._soundPanner = null;
  57364. }
  57365. if (this._soundSource) {
  57366. this._soundSource.disconnect();
  57367. this._soundSource = null;
  57368. }
  57369. this._audioBuffer = null;
  57370. if (this._htmlAudioElement) {
  57371. this._htmlAudioElement.pause();
  57372. this._htmlAudioElement.src = "";
  57373. document.body.removeChild(this._htmlAudioElement);
  57374. }
  57375. if (this._connectedMesh && this._registerFunc) {
  57376. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57377. this._connectedMesh = null;
  57378. }
  57379. }
  57380. };
  57381. Sound.prototype.isReady = function () {
  57382. return this._isReadyToPlay;
  57383. };
  57384. Sound.prototype._soundLoaded = function (audioData) {
  57385. var _this = this;
  57386. if (!BABYLON.Engine.audioEngine.audioContext) {
  57387. return;
  57388. }
  57389. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57390. _this._audioBuffer = buffer;
  57391. _this._isReadyToPlay = true;
  57392. if (_this.autoplay) {
  57393. _this.play();
  57394. }
  57395. if (_this._readyToPlayCallback) {
  57396. _this._readyToPlayCallback();
  57397. }
  57398. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57399. };
  57400. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57401. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57402. this._audioBuffer = audioBuffer;
  57403. this._isReadyToPlay = true;
  57404. }
  57405. };
  57406. Sound.prototype.updateOptions = function (options) {
  57407. if (options) {
  57408. this.loop = options.loop || this.loop;
  57409. this.maxDistance = options.maxDistance || this.maxDistance;
  57410. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57411. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57412. this.refDistance = options.refDistance || this.refDistance;
  57413. this.distanceModel = options.distanceModel || this.distanceModel;
  57414. this._playbackRate = options.playbackRate || this._playbackRate;
  57415. this._updateSpatialParameters();
  57416. if (this.isPlaying) {
  57417. if (this._streaming) {
  57418. this._htmlAudioElement.playbackRate = this._playbackRate;
  57419. }
  57420. else {
  57421. if (this._soundSource) {
  57422. this._soundSource.playbackRate.value = this._playbackRate;
  57423. }
  57424. }
  57425. }
  57426. }
  57427. };
  57428. Sound.prototype._createSpatialParameters = function () {
  57429. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57430. if (this._scene.headphone) {
  57431. this._panningModel = "HRTF";
  57432. }
  57433. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57434. this._updateSpatialParameters();
  57435. this._soundPanner.connect(this._ouputAudioNode);
  57436. this._inputAudioNode = this._soundPanner;
  57437. }
  57438. };
  57439. Sound.prototype._updateSpatialParameters = function () {
  57440. if (this.spatialSound && this._soundPanner) {
  57441. if (this.useCustomAttenuation) {
  57442. // Tricks to disable in a way embedded Web Audio attenuation
  57443. this._soundPanner.distanceModel = "linear";
  57444. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57445. this._soundPanner.refDistance = 1;
  57446. this._soundPanner.rolloffFactor = 1;
  57447. this._soundPanner.panningModel = this._panningModel;
  57448. }
  57449. else {
  57450. this._soundPanner.distanceModel = this.distanceModel;
  57451. this._soundPanner.maxDistance = this.maxDistance;
  57452. this._soundPanner.refDistance = this.refDistance;
  57453. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57454. this._soundPanner.panningModel = this._panningModel;
  57455. }
  57456. }
  57457. };
  57458. Sound.prototype.switchPanningModelToHRTF = function () {
  57459. this._panningModel = "HRTF";
  57460. this._switchPanningModel();
  57461. };
  57462. Sound.prototype.switchPanningModelToEqualPower = function () {
  57463. this._panningModel = "equalpower";
  57464. this._switchPanningModel();
  57465. };
  57466. Sound.prototype._switchPanningModel = function () {
  57467. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57468. this._soundPanner.panningModel = this._panningModel;
  57469. }
  57470. };
  57471. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57472. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57473. if (this._isOutputConnected) {
  57474. this._ouputAudioNode.disconnect();
  57475. }
  57476. this._ouputAudioNode.connect(soundTrackAudioNode);
  57477. this._isOutputConnected = true;
  57478. }
  57479. };
  57480. /**
  57481. * Transform this sound into a directional source
  57482. * @param coneInnerAngle Size of the inner cone in degree
  57483. * @param coneOuterAngle Size of the outer cone in degree
  57484. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57485. */
  57486. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57487. if (coneOuterAngle < coneInnerAngle) {
  57488. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57489. return;
  57490. }
  57491. this._coneInnerAngle = coneInnerAngle;
  57492. this._coneOuterAngle = coneOuterAngle;
  57493. this._coneOuterGain = coneOuterGain;
  57494. this._isDirectional = true;
  57495. if (this.isPlaying && this.loop) {
  57496. this.stop();
  57497. this.play();
  57498. }
  57499. };
  57500. Sound.prototype.setPosition = function (newPosition) {
  57501. this._position = newPosition;
  57502. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57503. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57504. }
  57505. };
  57506. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57507. this._localDirection = newLocalDirection;
  57508. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57509. this._updateDirection();
  57510. }
  57511. };
  57512. Sound.prototype._updateDirection = function () {
  57513. if (!this._connectedMesh || !this._soundPanner) {
  57514. return;
  57515. }
  57516. var mat = this._connectedMesh.getWorldMatrix();
  57517. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57518. direction.normalize();
  57519. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57520. };
  57521. Sound.prototype.updateDistanceFromListener = function () {
  57522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57523. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57524. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57525. }
  57526. };
  57527. Sound.prototype.setAttenuationFunction = function (callback) {
  57528. this._customAttenuationFunction = callback;
  57529. };
  57530. /**
  57531. * Play the sound
  57532. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57533. * @param offset (optional) Start the sound setting it at a specific time
  57534. */
  57535. Sound.prototype.play = function (time, offset) {
  57536. var _this = this;
  57537. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57538. try {
  57539. if (this._startOffset < 0) {
  57540. time = -this._startOffset;
  57541. this._startOffset = 0;
  57542. }
  57543. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57544. if (!this._soundSource || !this._streamingSource) {
  57545. if (this.spatialSound && this._soundPanner) {
  57546. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57547. if (this._isDirectional) {
  57548. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57549. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57550. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57551. if (this._connectedMesh) {
  57552. this._updateDirection();
  57553. }
  57554. else {
  57555. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57556. }
  57557. }
  57558. }
  57559. }
  57560. if (this._streaming) {
  57561. if (!this._streamingSource) {
  57562. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57563. this._htmlAudioElement.onended = function () { _this._onended(); };
  57564. this._htmlAudioElement.playbackRate = this._playbackRate;
  57565. }
  57566. this._streamingSource.disconnect();
  57567. this._streamingSource.connect(this._inputAudioNode);
  57568. this._htmlAudioElement.play();
  57569. }
  57570. else {
  57571. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57572. this._soundSource.buffer = this._audioBuffer;
  57573. this._soundSource.connect(this._inputAudioNode);
  57574. this._soundSource.loop = this.loop;
  57575. this._soundSource.playbackRate.value = this._playbackRate;
  57576. this._soundSource.onended = function () { _this._onended(); };
  57577. if (this._soundSource.buffer) {
  57578. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57579. }
  57580. }
  57581. this._startTime = startTime;
  57582. this.isPlaying = true;
  57583. this.isPaused = false;
  57584. }
  57585. catch (ex) {
  57586. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57587. }
  57588. }
  57589. };
  57590. Sound.prototype._onended = function () {
  57591. this.isPlaying = false;
  57592. if (this.onended) {
  57593. this.onended();
  57594. }
  57595. };
  57596. /**
  57597. * Stop the sound
  57598. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57599. */
  57600. Sound.prototype.stop = function (time) {
  57601. if (this.isPlaying) {
  57602. if (this._streaming) {
  57603. this._htmlAudioElement.pause();
  57604. // Test needed for Firefox or it will generate an Invalid State Error
  57605. if (this._htmlAudioElement.currentTime > 0) {
  57606. this._htmlAudioElement.currentTime = 0;
  57607. }
  57608. }
  57609. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57610. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57611. this._soundSource.stop(stopTime);
  57612. this._soundSource.onended = function () { };
  57613. if (!this.isPaused) {
  57614. this._startOffset = 0;
  57615. }
  57616. }
  57617. this.isPlaying = false;
  57618. }
  57619. };
  57620. Sound.prototype.pause = function () {
  57621. if (this.isPlaying) {
  57622. this.isPaused = true;
  57623. if (this._streaming) {
  57624. this._htmlAudioElement.pause();
  57625. }
  57626. else if (BABYLON.Engine.audioEngine.audioContext) {
  57627. this.stop(0);
  57628. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57629. }
  57630. }
  57631. };
  57632. Sound.prototype.setVolume = function (newVolume, time) {
  57633. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57634. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57635. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57636. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57637. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57638. }
  57639. else {
  57640. this._soundGain.gain.value = newVolume;
  57641. }
  57642. }
  57643. this._volume = newVolume;
  57644. };
  57645. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57646. this._playbackRate = newPlaybackRate;
  57647. if (this.isPlaying) {
  57648. if (this._streaming) {
  57649. this._htmlAudioElement.playbackRate = this._playbackRate;
  57650. }
  57651. else if (this._soundSource) {
  57652. this._soundSource.playbackRate.value = this._playbackRate;
  57653. }
  57654. }
  57655. };
  57656. Sound.prototype.getVolume = function () {
  57657. return this._volume;
  57658. };
  57659. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57660. var _this = this;
  57661. if (this._connectedMesh && this._registerFunc) {
  57662. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57663. this._registerFunc = null;
  57664. }
  57665. this._connectedMesh = meshToConnectTo;
  57666. if (!this.spatialSound) {
  57667. this.spatialSound = true;
  57668. this._createSpatialParameters();
  57669. if (this.isPlaying && this.loop) {
  57670. this.stop();
  57671. this.play();
  57672. }
  57673. }
  57674. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57675. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57676. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57677. };
  57678. Sound.prototype.detachFromMesh = function () {
  57679. if (this._connectedMesh && this._registerFunc) {
  57680. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57681. this._registerFunc = null;
  57682. this._connectedMesh = null;
  57683. }
  57684. };
  57685. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57686. if (!node.getBoundingInfo) {
  57687. return;
  57688. }
  57689. var mesh = node;
  57690. var boundingInfo = mesh.getBoundingInfo();
  57691. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57692. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57693. this._updateDirection();
  57694. }
  57695. };
  57696. Sound.prototype.clone = function () {
  57697. var _this = this;
  57698. if (!this._streaming) {
  57699. var setBufferAndRun = function () {
  57700. if (_this._isReadyToPlay) {
  57701. clonedSound._audioBuffer = _this.getAudioBuffer();
  57702. clonedSound._isReadyToPlay = true;
  57703. if (clonedSound.autoplay) {
  57704. clonedSound.play();
  57705. }
  57706. }
  57707. else {
  57708. window.setTimeout(setBufferAndRun, 300);
  57709. }
  57710. };
  57711. var currentOptions = {
  57712. autoplay: this.autoplay, loop: this.loop,
  57713. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57714. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57715. refDistance: this.refDistance, distanceModel: this.distanceModel
  57716. };
  57717. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57718. if (this.useCustomAttenuation) {
  57719. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57720. }
  57721. clonedSound.setPosition(this._position);
  57722. clonedSound.setPlaybackRate(this._playbackRate);
  57723. setBufferAndRun();
  57724. return clonedSound;
  57725. }
  57726. else {
  57727. return null;
  57728. }
  57729. };
  57730. Sound.prototype.getAudioBuffer = function () {
  57731. return this._audioBuffer;
  57732. };
  57733. Sound.prototype.serialize = function () {
  57734. var serializationObject = {
  57735. name: this.name,
  57736. url: this.name,
  57737. autoplay: this.autoplay,
  57738. loop: this.loop,
  57739. volume: this._volume,
  57740. spatialSound: this.spatialSound,
  57741. maxDistance: this.maxDistance,
  57742. rolloffFactor: this.rolloffFactor,
  57743. refDistance: this.refDistance,
  57744. distanceModel: this.distanceModel,
  57745. playbackRate: this._playbackRate,
  57746. panningModel: this._panningModel,
  57747. soundTrackId: this.soundTrackId
  57748. };
  57749. if (this.spatialSound) {
  57750. if (this._connectedMesh)
  57751. serializationObject.connectedMeshId = this._connectedMesh.id;
  57752. serializationObject.position = this._position.asArray();
  57753. serializationObject.refDistance = this.refDistance;
  57754. serializationObject.distanceModel = this.distanceModel;
  57755. serializationObject.isDirectional = this._isDirectional;
  57756. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57757. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57758. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57759. serializationObject.coneOuterGain = this._coneOuterGain;
  57760. }
  57761. return serializationObject;
  57762. };
  57763. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57764. var soundName = parsedSound.name;
  57765. var soundUrl;
  57766. if (parsedSound.url) {
  57767. soundUrl = rootUrl + parsedSound.url;
  57768. }
  57769. else {
  57770. soundUrl = rootUrl + soundName;
  57771. }
  57772. var options = {
  57773. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57774. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57775. rolloffFactor: parsedSound.rolloffFactor,
  57776. refDistance: parsedSound.refDistance,
  57777. distanceModel: parsedSound.distanceModel,
  57778. playbackRate: parsedSound.playbackRate
  57779. };
  57780. var newSound;
  57781. if (!sourceSound) {
  57782. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57783. scene._addPendingData(newSound);
  57784. }
  57785. else {
  57786. var setBufferAndRun = function () {
  57787. if (sourceSound._isReadyToPlay) {
  57788. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57789. newSound._isReadyToPlay = true;
  57790. if (newSound.autoplay) {
  57791. newSound.play();
  57792. }
  57793. }
  57794. else {
  57795. window.setTimeout(setBufferAndRun, 300);
  57796. }
  57797. };
  57798. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57799. setBufferAndRun();
  57800. }
  57801. if (parsedSound.position) {
  57802. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57803. newSound.setPosition(soundPosition);
  57804. }
  57805. if (parsedSound.isDirectional) {
  57806. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57807. if (parsedSound.localDirectionToMesh) {
  57808. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57809. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57810. }
  57811. }
  57812. if (parsedSound.connectedMeshId) {
  57813. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57814. if (connectedMesh) {
  57815. newSound.attachToMesh(connectedMesh);
  57816. }
  57817. }
  57818. return newSound;
  57819. };
  57820. return Sound;
  57821. }());
  57822. BABYLON.Sound = Sound;
  57823. })(BABYLON || (BABYLON = {}));
  57824. //# sourceMappingURL=babylon.sound.js.map
  57825. var BABYLON;
  57826. (function (BABYLON) {
  57827. var SoundTrack = /** @class */ (function () {
  57828. function SoundTrack(scene, options) {
  57829. this.id = -1;
  57830. this._isMainTrack = false;
  57831. this._isInitialized = false;
  57832. this._scene = scene;
  57833. this.soundCollection = new Array();
  57834. this._options = options;
  57835. if (!this._isMainTrack) {
  57836. this._scene.soundTracks.push(this);
  57837. this.id = this._scene.soundTracks.length - 1;
  57838. }
  57839. }
  57840. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57841. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57842. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57843. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57844. if (this._options) {
  57845. if (this._options.volume) {
  57846. this._outputAudioNode.gain.value = this._options.volume;
  57847. }
  57848. if (this._options.mainTrack) {
  57849. this._isMainTrack = this._options.mainTrack;
  57850. }
  57851. }
  57852. this._isInitialized = true;
  57853. }
  57854. };
  57855. SoundTrack.prototype.dispose = function () {
  57856. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57857. if (this._connectedAnalyser) {
  57858. this._connectedAnalyser.stopDebugCanvas();
  57859. }
  57860. while (this.soundCollection.length) {
  57861. this.soundCollection[0].dispose();
  57862. }
  57863. if (this._outputAudioNode) {
  57864. this._outputAudioNode.disconnect();
  57865. }
  57866. this._outputAudioNode = null;
  57867. }
  57868. };
  57869. SoundTrack.prototype.AddSound = function (sound) {
  57870. if (!this._isInitialized) {
  57871. this._initializeSoundTrackAudioGraph();
  57872. }
  57873. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57874. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57875. }
  57876. if (sound.soundTrackId) {
  57877. if (sound.soundTrackId === -1) {
  57878. this._scene.mainSoundTrack.RemoveSound(sound);
  57879. }
  57880. else {
  57881. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57882. }
  57883. }
  57884. this.soundCollection.push(sound);
  57885. sound.soundTrackId = this.id;
  57886. };
  57887. SoundTrack.prototype.RemoveSound = function (sound) {
  57888. var index = this.soundCollection.indexOf(sound);
  57889. if (index !== -1) {
  57890. this.soundCollection.splice(index, 1);
  57891. }
  57892. };
  57893. SoundTrack.prototype.setVolume = function (newVolume) {
  57894. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57895. this._outputAudioNode.gain.value = newVolume;
  57896. }
  57897. };
  57898. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57900. for (var i = 0; i < this.soundCollection.length; i++) {
  57901. this.soundCollection[i].switchPanningModelToHRTF();
  57902. }
  57903. }
  57904. };
  57905. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57906. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57907. for (var i = 0; i < this.soundCollection.length; i++) {
  57908. this.soundCollection[i].switchPanningModelToEqualPower();
  57909. }
  57910. }
  57911. };
  57912. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57913. if (this._connectedAnalyser) {
  57914. this._connectedAnalyser.stopDebugCanvas();
  57915. }
  57916. this._connectedAnalyser = analyser;
  57917. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57918. this._outputAudioNode.disconnect();
  57919. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57920. }
  57921. };
  57922. return SoundTrack;
  57923. }());
  57924. BABYLON.SoundTrack = SoundTrack;
  57925. })(BABYLON || (BABYLON = {}));
  57926. //# sourceMappingURL=babylon.soundtrack.js.map
  57927. var BABYLON;
  57928. (function (BABYLON) {
  57929. var Analyser = /** @class */ (function () {
  57930. function Analyser(scene) {
  57931. this.SMOOTHING = 0.75;
  57932. this.FFT_SIZE = 512;
  57933. this.BARGRAPHAMPLITUDE = 256;
  57934. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57935. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57936. this._scene = scene;
  57937. this._audioEngine = BABYLON.Engine.audioEngine;
  57938. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57939. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57940. this._webAudioAnalyser.minDecibels = -140;
  57941. this._webAudioAnalyser.maxDecibels = 0;
  57942. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57943. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57944. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57945. }
  57946. }
  57947. Analyser.prototype.getFrequencyBinCount = function () {
  57948. if (this._audioEngine.canUseWebAudio) {
  57949. return this._webAudioAnalyser.frequencyBinCount;
  57950. }
  57951. else {
  57952. return 0;
  57953. }
  57954. };
  57955. Analyser.prototype.getByteFrequencyData = function () {
  57956. if (this._audioEngine.canUseWebAudio) {
  57957. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57958. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57959. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57960. }
  57961. return this._byteFreqs;
  57962. };
  57963. Analyser.prototype.getByteTimeDomainData = function () {
  57964. if (this._audioEngine.canUseWebAudio) {
  57965. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57966. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57967. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57968. }
  57969. return this._byteTime;
  57970. };
  57971. Analyser.prototype.getFloatFrequencyData = function () {
  57972. if (this._audioEngine.canUseWebAudio) {
  57973. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57974. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57975. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57976. }
  57977. return this._floatFreqs;
  57978. };
  57979. Analyser.prototype.drawDebugCanvas = function () {
  57980. var _this = this;
  57981. if (this._audioEngine.canUseWebAudio) {
  57982. if (!this._debugCanvas) {
  57983. this._debugCanvas = document.createElement("canvas");
  57984. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57985. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57986. this._debugCanvas.style.position = "absolute";
  57987. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57988. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57989. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57990. document.body.appendChild(this._debugCanvas);
  57991. this._registerFunc = function () {
  57992. _this.drawDebugCanvas();
  57993. };
  57994. this._scene.registerBeforeRender(this._registerFunc);
  57995. }
  57996. if (this._registerFunc && this._debugCanvasContext) {
  57997. var workingArray = this.getByteFrequencyData();
  57998. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57999. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58000. // Draw the frequency domain chart.
  58001. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58002. var value = workingArray[i];
  58003. var percent = value / this.BARGRAPHAMPLITUDE;
  58004. var height = this.DEBUGCANVASSIZE.height * percent;
  58005. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58006. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58007. var hue = i / this.getFrequencyBinCount() * 360;
  58008. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58009. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58010. }
  58011. }
  58012. }
  58013. };
  58014. Analyser.prototype.stopDebugCanvas = function () {
  58015. if (this._debugCanvas) {
  58016. if (this._registerFunc) {
  58017. this._scene.unregisterBeforeRender(this._registerFunc);
  58018. this._registerFunc = null;
  58019. }
  58020. document.body.removeChild(this._debugCanvas);
  58021. this._debugCanvas = null;
  58022. this._debugCanvasContext = null;
  58023. }
  58024. };
  58025. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58026. if (this._audioEngine.canUseWebAudio) {
  58027. inputAudioNode.connect(this._webAudioAnalyser);
  58028. this._webAudioAnalyser.connect(outputAudioNode);
  58029. }
  58030. };
  58031. Analyser.prototype.dispose = function () {
  58032. if (this._audioEngine.canUseWebAudio) {
  58033. this._webAudioAnalyser.disconnect();
  58034. }
  58035. };
  58036. return Analyser;
  58037. }());
  58038. BABYLON.Analyser = Analyser;
  58039. })(BABYLON || (BABYLON = {}));
  58040. //# sourceMappingURL=babylon.analyser.js.map
  58041. var BABYLON;
  58042. (function (BABYLON) {
  58043. var CubeTexture = /** @class */ (function (_super) {
  58044. __extends(CubeTexture, _super);
  58045. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58046. if (extensions === void 0) { extensions = null; }
  58047. if (noMipmap === void 0) { noMipmap = false; }
  58048. if (files === void 0) { files = null; }
  58049. if (onLoad === void 0) { onLoad = null; }
  58050. if (onError === void 0) { onError = null; }
  58051. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58052. if (prefiltered === void 0) { prefiltered = false; }
  58053. if (forcedExtension === void 0) { forcedExtension = null; }
  58054. var _this = _super.call(this, scene) || this;
  58055. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58056. /**
  58057. * Gets or sets the center of the bounding box associated with the cube texture
  58058. * It must define where the camera used to render the texture was set
  58059. */
  58060. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58061. _this.name = rootUrl;
  58062. _this.url = rootUrl;
  58063. _this._noMipmap = noMipmap;
  58064. _this.hasAlpha = false;
  58065. _this._format = format;
  58066. _this._prefiltered = prefiltered;
  58067. _this.isCube = true;
  58068. _this._textureMatrix = BABYLON.Matrix.Identity();
  58069. if (prefiltered) {
  58070. _this.gammaSpace = false;
  58071. }
  58072. if (!rootUrl && !files) {
  58073. return _this;
  58074. }
  58075. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58076. var lastDot = rootUrl.lastIndexOf(".");
  58077. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58078. var isDDS = (extension === ".dds");
  58079. if (!files) {
  58080. if (!isDDS && !extensions) {
  58081. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58082. }
  58083. files = [];
  58084. if (extensions) {
  58085. for (var index = 0; index < extensions.length; index++) {
  58086. files.push(rootUrl + extensions[index]);
  58087. }
  58088. }
  58089. }
  58090. _this._files = files;
  58091. if (!_this._texture) {
  58092. if (!scene.useDelayedTextureLoading) {
  58093. if (prefiltered) {
  58094. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58095. }
  58096. else {
  58097. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58098. }
  58099. }
  58100. else {
  58101. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58102. }
  58103. }
  58104. else if (onLoad) {
  58105. if (_this._texture.isReady) {
  58106. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58107. }
  58108. else {
  58109. _this._texture.onLoadedObservable.add(onLoad);
  58110. }
  58111. }
  58112. return _this;
  58113. }
  58114. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58115. get: function () {
  58116. return this._boundingBoxSize;
  58117. },
  58118. /**
  58119. * Gets or sets the size of the bounding box associated with the cube texture
  58120. * When defined, the cubemap will switch to local mode
  58121. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58122. * @example https://www.babylonjs-playground.com/#RNASML
  58123. */
  58124. set: function (value) {
  58125. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58126. return;
  58127. }
  58128. this._boundingBoxSize = value;
  58129. var scene = this.getScene();
  58130. if (scene) {
  58131. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58132. }
  58133. },
  58134. enumerable: true,
  58135. configurable: true
  58136. });
  58137. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58138. var rootUrlKey = "";
  58139. files.forEach(function (url) { return rootUrlKey += url; });
  58140. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58141. };
  58142. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58143. if (forcedExtension === void 0) { forcedExtension = null; }
  58144. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58145. };
  58146. // Methods
  58147. CubeTexture.prototype.delayLoad = function () {
  58148. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58149. return;
  58150. }
  58151. var scene = this.getScene();
  58152. if (!scene) {
  58153. return;
  58154. }
  58155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58156. this._texture = this._getFromCache(this.url, this._noMipmap);
  58157. if (!this._texture) {
  58158. if (this._prefiltered) {
  58159. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58160. }
  58161. else {
  58162. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58163. }
  58164. }
  58165. };
  58166. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58167. return this._textureMatrix;
  58168. };
  58169. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58170. this._textureMatrix = value;
  58171. };
  58172. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58173. var texture = BABYLON.SerializationHelper.Parse(function () {
  58174. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58175. }, parsedTexture, scene);
  58176. // Local Cubemaps
  58177. if (parsedTexture.boundingBoxPosition) {
  58178. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58179. }
  58180. if (parsedTexture.boundingBoxSize) {
  58181. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58182. }
  58183. // Animations
  58184. if (parsedTexture.animations) {
  58185. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58186. var parsedAnimation = parsedTexture.animations[animationIndex];
  58187. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58188. }
  58189. }
  58190. return texture;
  58191. };
  58192. CubeTexture.prototype.clone = function () {
  58193. var _this = this;
  58194. return BABYLON.SerializationHelper.Clone(function () {
  58195. var scene = _this.getScene();
  58196. if (!scene) {
  58197. return _this;
  58198. }
  58199. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58200. }, this);
  58201. };
  58202. return CubeTexture;
  58203. }(BABYLON.BaseTexture));
  58204. BABYLON.CubeTexture = CubeTexture;
  58205. })(BABYLON || (BABYLON = {}));
  58206. //# sourceMappingURL=babylon.cubeTexture.js.map
  58207. var BABYLON;
  58208. (function (BABYLON) {
  58209. var RenderTargetTexture = /** @class */ (function (_super) {
  58210. __extends(RenderTargetTexture, _super);
  58211. /**
  58212. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58213. * or used a shadow, depth texture...
  58214. * @param name The friendly name of the texture
  58215. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58216. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58217. * @param generateMipMaps True if mip maps need to be generated after render.
  58218. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58219. * @param type The type of the buffer in the RTT (int, half float, float...)
  58220. * @param isCube True if a cube texture needs to be created
  58221. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58222. * @param generateDepthBuffer True to generate a depth buffer
  58223. * @param generateStencilBuffer True to generate a stencil buffer
  58224. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58225. */
  58226. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58227. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58228. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58229. if (isCube === void 0) { isCube = false; }
  58230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58231. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58232. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58233. if (isMulti === void 0) { isMulti = false; }
  58234. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58235. _this.isCube = isCube;
  58236. /**
  58237. * Use this list to define the list of mesh you want to render.
  58238. */
  58239. _this.renderList = new Array();
  58240. _this.renderParticles = true;
  58241. _this.renderSprites = false;
  58242. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58243. _this.ignoreCameraViewport = false;
  58244. // Events
  58245. /**
  58246. * An event triggered when the texture is unbind.
  58247. * @type {BABYLON.Observable}
  58248. */
  58249. _this.onBeforeBindObservable = new BABYLON.Observable();
  58250. /**
  58251. * An event triggered when the texture is unbind.
  58252. * @type {BABYLON.Observable}
  58253. */
  58254. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58255. /**
  58256. * An event triggered before rendering the texture
  58257. * @type {BABYLON.Observable}
  58258. */
  58259. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58260. /**
  58261. * An event triggered after rendering the texture
  58262. * @type {BABYLON.Observable}
  58263. */
  58264. _this.onAfterRenderObservable = new BABYLON.Observable();
  58265. /**
  58266. * An event triggered after the texture clear
  58267. * @type {BABYLON.Observable}
  58268. */
  58269. _this.onClearObservable = new BABYLON.Observable();
  58270. _this._currentRefreshId = -1;
  58271. _this._refreshRate = 1;
  58272. _this._samples = 1;
  58273. /**
  58274. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58275. * It must define where the camera used to render the texture is set
  58276. */
  58277. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58278. scene = _this.getScene();
  58279. if (!scene) {
  58280. return _this;
  58281. }
  58282. _this._engine = scene.getEngine();
  58283. _this.name = name;
  58284. _this.isRenderTarget = true;
  58285. _this._initialSizeParameter = size;
  58286. _this._processSizeParameter(size);
  58287. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58288. });
  58289. _this._generateMipMaps = generateMipMaps ? true : false;
  58290. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58291. // Rendering groups
  58292. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58293. if (isMulti) {
  58294. return _this;
  58295. }
  58296. _this._renderTargetOptions = {
  58297. generateMipMaps: generateMipMaps,
  58298. type: type,
  58299. samplingMode: samplingMode,
  58300. generateDepthBuffer: generateDepthBuffer,
  58301. generateStencilBuffer: generateStencilBuffer
  58302. };
  58303. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58304. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58305. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58306. }
  58307. if (isCube) {
  58308. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58309. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58310. _this._textureMatrix = BABYLON.Matrix.Identity();
  58311. }
  58312. else {
  58313. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58314. }
  58315. return _this;
  58316. }
  58317. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58318. get: function () {
  58319. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58320. },
  58321. enumerable: true,
  58322. configurable: true
  58323. });
  58324. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58325. get: function () {
  58326. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58327. },
  58328. enumerable: true,
  58329. configurable: true
  58330. });
  58331. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58332. get: function () {
  58333. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58334. },
  58335. enumerable: true,
  58336. configurable: true
  58337. });
  58338. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58339. set: function (callback) {
  58340. if (this._onAfterUnbindObserver) {
  58341. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58342. }
  58343. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58344. },
  58345. enumerable: true,
  58346. configurable: true
  58347. });
  58348. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58349. set: function (callback) {
  58350. if (this._onBeforeRenderObserver) {
  58351. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58352. }
  58353. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58354. },
  58355. enumerable: true,
  58356. configurable: true
  58357. });
  58358. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58359. set: function (callback) {
  58360. if (this._onAfterRenderObserver) {
  58361. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58362. }
  58363. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58364. },
  58365. enumerable: true,
  58366. configurable: true
  58367. });
  58368. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58369. set: function (callback) {
  58370. if (this._onClearObserver) {
  58371. this.onClearObservable.remove(this._onClearObserver);
  58372. }
  58373. this._onClearObserver = this.onClearObservable.add(callback);
  58374. },
  58375. enumerable: true,
  58376. configurable: true
  58377. });
  58378. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58379. get: function () {
  58380. return this._renderTargetOptions;
  58381. },
  58382. enumerable: true,
  58383. configurable: true
  58384. });
  58385. RenderTargetTexture.prototype._onRatioRescale = function () {
  58386. if (this._sizeRatio) {
  58387. this.resize(this._initialSizeParameter);
  58388. }
  58389. };
  58390. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58391. get: function () {
  58392. return this._boundingBoxSize;
  58393. },
  58394. /**
  58395. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58396. * When defined, the cubemap will switch to local mode
  58397. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58398. * @example https://www.babylonjs-playground.com/#RNASML
  58399. */
  58400. set: function (value) {
  58401. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58402. return;
  58403. }
  58404. this._boundingBoxSize = value;
  58405. var scene = this.getScene();
  58406. if (scene) {
  58407. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58408. }
  58409. },
  58410. enumerable: true,
  58411. configurable: true
  58412. });
  58413. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58414. if (size.ratio) {
  58415. this._sizeRatio = size.ratio;
  58416. this._size = {
  58417. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58418. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58419. };
  58420. }
  58421. else {
  58422. this._size = size;
  58423. }
  58424. };
  58425. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58426. get: function () {
  58427. return this._samples;
  58428. },
  58429. set: function (value) {
  58430. if (this._samples === value) {
  58431. return;
  58432. }
  58433. var scene = this.getScene();
  58434. if (!scene) {
  58435. return;
  58436. }
  58437. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58443. this._currentRefreshId = -1;
  58444. };
  58445. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58446. get: function () {
  58447. return this._refreshRate;
  58448. },
  58449. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58450. set: function (value) {
  58451. this._refreshRate = value;
  58452. this.resetRefreshCounter();
  58453. },
  58454. enumerable: true,
  58455. configurable: true
  58456. });
  58457. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58458. if (!this._postProcessManager) {
  58459. var scene = this.getScene();
  58460. if (!scene) {
  58461. return;
  58462. }
  58463. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58464. this._postProcesses = new Array();
  58465. }
  58466. this._postProcesses.push(postProcess);
  58467. this._postProcesses[0].autoClear = false;
  58468. };
  58469. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58470. if (!this._postProcesses) {
  58471. return;
  58472. }
  58473. if (dispose) {
  58474. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58475. var postProcess = _a[_i];
  58476. postProcess.dispose();
  58477. }
  58478. }
  58479. this._postProcesses = [];
  58480. };
  58481. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58482. if (!this._postProcesses) {
  58483. return;
  58484. }
  58485. var index = this._postProcesses.indexOf(postProcess);
  58486. if (index === -1) {
  58487. return;
  58488. }
  58489. this._postProcesses.splice(index, 1);
  58490. if (this._postProcesses.length > 0) {
  58491. this._postProcesses[0].autoClear = false;
  58492. }
  58493. };
  58494. RenderTargetTexture.prototype._shouldRender = function () {
  58495. if (this._currentRefreshId === -1) {
  58496. this._currentRefreshId = 1;
  58497. return true;
  58498. }
  58499. if (this.refreshRate === this._currentRefreshId) {
  58500. this._currentRefreshId = 1;
  58501. return true;
  58502. }
  58503. this._currentRefreshId++;
  58504. return false;
  58505. };
  58506. RenderTargetTexture.prototype.getRenderSize = function () {
  58507. if (this._size.width) {
  58508. return this._size.width;
  58509. }
  58510. return this._size;
  58511. };
  58512. RenderTargetTexture.prototype.getRenderWidth = function () {
  58513. if (this._size.width) {
  58514. return this._size.width;
  58515. }
  58516. return this._size;
  58517. };
  58518. RenderTargetTexture.prototype.getRenderHeight = function () {
  58519. if (this._size.width) {
  58520. return this._size.height;
  58521. }
  58522. return this._size;
  58523. };
  58524. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58525. get: function () {
  58526. return true;
  58527. },
  58528. enumerable: true,
  58529. configurable: true
  58530. });
  58531. RenderTargetTexture.prototype.scale = function (ratio) {
  58532. var newSize = this.getRenderSize() * ratio;
  58533. this.resize(newSize);
  58534. };
  58535. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58536. if (this.isCube) {
  58537. return this._textureMatrix;
  58538. }
  58539. return _super.prototype.getReflectionTextureMatrix.call(this);
  58540. };
  58541. RenderTargetTexture.prototype.resize = function (size) {
  58542. this.releaseInternalTexture();
  58543. var scene = this.getScene();
  58544. if (!scene) {
  58545. return;
  58546. }
  58547. this._processSizeParameter(size);
  58548. if (this.isCube) {
  58549. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58550. }
  58551. else {
  58552. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58553. }
  58554. };
  58555. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58556. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58557. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58558. var scene = this.getScene();
  58559. if (!scene) {
  58560. return;
  58561. }
  58562. var engine = scene.getEngine();
  58563. if (this.useCameraPostProcesses !== undefined) {
  58564. useCameraPostProcess = this.useCameraPostProcesses;
  58565. }
  58566. if (this._waitingRenderList) {
  58567. this.renderList = [];
  58568. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58569. var id = this._waitingRenderList[index];
  58570. var mesh_1 = scene.getMeshByID(id);
  58571. if (mesh_1) {
  58572. this.renderList.push(mesh_1);
  58573. }
  58574. }
  58575. delete this._waitingRenderList;
  58576. }
  58577. // Is predicate defined?
  58578. if (this.renderListPredicate) {
  58579. if (this.renderList) {
  58580. this.renderList.splice(0); // Clear previous renderList
  58581. }
  58582. else {
  58583. this.renderList = [];
  58584. }
  58585. var scene = this.getScene();
  58586. if (!scene) {
  58587. return;
  58588. }
  58589. var sceneMeshes = scene.meshes;
  58590. for (var index = 0; index < sceneMeshes.length; index++) {
  58591. var mesh = sceneMeshes[index];
  58592. if (this.renderListPredicate(mesh)) {
  58593. this.renderList.push(mesh);
  58594. }
  58595. }
  58596. }
  58597. this.onBeforeBindObservable.notifyObservers(this);
  58598. // Set custom projection.
  58599. // Needs to be before binding to prevent changing the aspect ratio.
  58600. var camera;
  58601. if (this.activeCamera) {
  58602. camera = this.activeCamera;
  58603. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58604. if (this.activeCamera !== scene.activeCamera) {
  58605. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58606. }
  58607. }
  58608. else {
  58609. camera = scene.activeCamera;
  58610. if (camera) {
  58611. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58612. }
  58613. }
  58614. // Prepare renderingManager
  58615. this._renderingManager.reset();
  58616. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58617. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58618. var sceneRenderId = scene.getRenderId();
  58619. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58620. var mesh = currentRenderList[meshIndex];
  58621. if (mesh) {
  58622. if (!mesh.isReady()) {
  58623. // Reset _currentRefreshId
  58624. this.resetRefreshCounter();
  58625. continue;
  58626. }
  58627. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58628. var isMasked = void 0;
  58629. if (!this.renderList && camera) {
  58630. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58631. }
  58632. else {
  58633. isMasked = false;
  58634. }
  58635. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58636. mesh._activate(sceneRenderId);
  58637. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58638. var subMesh = mesh.subMeshes[subIndex];
  58639. scene._activeIndices.addCount(subMesh.indexCount, false);
  58640. this._renderingManager.dispatch(subMesh, mesh);
  58641. }
  58642. }
  58643. }
  58644. }
  58645. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58646. var particleSystem = scene.particleSystems[particleIndex];
  58647. var emitter = particleSystem.emitter;
  58648. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58649. continue;
  58650. }
  58651. if (currentRenderList.indexOf(emitter) >= 0) {
  58652. this._renderingManager.dispatchParticles(particleSystem);
  58653. }
  58654. }
  58655. if (this.isCube) {
  58656. for (var face = 0; face < 6; face++) {
  58657. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58658. scene.incrementRenderId();
  58659. scene.resetCachedMaterial();
  58660. }
  58661. }
  58662. else {
  58663. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58664. }
  58665. this.onAfterUnbindObservable.notifyObservers(this);
  58666. if (scene.activeCamera) {
  58667. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58668. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58669. }
  58670. engine.setViewport(scene.activeCamera.viewport);
  58671. }
  58672. scene.resetCachedMaterial();
  58673. };
  58674. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58675. var minimum = 128;
  58676. var x = renderDimension * scale;
  58677. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58678. // Ensure we don't exceed the render dimension (while staying POT)
  58679. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58680. };
  58681. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58682. var _this = this;
  58683. if (!this._texture) {
  58684. return;
  58685. }
  58686. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58687. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58688. });
  58689. };
  58690. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58691. var scene = this.getScene();
  58692. if (!scene) {
  58693. return;
  58694. }
  58695. var engine = scene.getEngine();
  58696. if (!this._texture) {
  58697. return;
  58698. }
  58699. // Bind
  58700. if (this._postProcessManager) {
  58701. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58702. }
  58703. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58704. if (this._texture) {
  58705. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58706. }
  58707. }
  58708. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58709. // Clear
  58710. if (this.onClearObservable.hasObservers()) {
  58711. this.onClearObservable.notifyObservers(engine);
  58712. }
  58713. else {
  58714. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58715. }
  58716. if (!this._doNotChangeAspectRatio) {
  58717. scene.updateTransformMatrix(true);
  58718. }
  58719. // Render
  58720. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58721. if (this._postProcessManager) {
  58722. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58723. }
  58724. else if (useCameraPostProcess) {
  58725. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58726. }
  58727. if (!this._doNotChangeAspectRatio) {
  58728. scene.updateTransformMatrix(true);
  58729. }
  58730. // Dump ?
  58731. if (dumpForDebug) {
  58732. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58733. }
  58734. // Unbind
  58735. if (!this.isCube || faceIndex === 5) {
  58736. if (this.isCube) {
  58737. if (faceIndex === 5) {
  58738. engine.generateMipMapsForCubemap(this._texture);
  58739. }
  58740. }
  58741. this.unbindFrameBuffer(engine, faceIndex);
  58742. }
  58743. else {
  58744. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58745. }
  58746. };
  58747. /**
  58748. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58749. * This allowed control for front to back rendering or reversly depending of the special needs.
  58750. *
  58751. * @param renderingGroupId The rendering group id corresponding to its index
  58752. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58753. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58754. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58755. */
  58756. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58757. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58758. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58759. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58760. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58761. };
  58762. /**
  58763. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58764. *
  58765. * @param renderingGroupId The rendering group id corresponding to its index
  58766. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58767. */
  58768. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58769. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58770. };
  58771. RenderTargetTexture.prototype.clone = function () {
  58772. var textureSize = this.getSize();
  58773. 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);
  58774. // Base texture
  58775. newTexture.hasAlpha = this.hasAlpha;
  58776. newTexture.level = this.level;
  58777. // RenderTarget Texture
  58778. newTexture.coordinatesMode = this.coordinatesMode;
  58779. if (this.renderList) {
  58780. newTexture.renderList = this.renderList.slice(0);
  58781. }
  58782. return newTexture;
  58783. };
  58784. RenderTargetTexture.prototype.serialize = function () {
  58785. if (!this.name) {
  58786. return null;
  58787. }
  58788. var serializationObject = _super.prototype.serialize.call(this);
  58789. serializationObject.renderTargetSize = this.getRenderSize();
  58790. serializationObject.renderList = [];
  58791. if (this.renderList) {
  58792. for (var index = 0; index < this.renderList.length; index++) {
  58793. serializationObject.renderList.push(this.renderList[index].id);
  58794. }
  58795. }
  58796. return serializationObject;
  58797. };
  58798. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58799. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58800. var objBuffer = this.getInternalTexture();
  58801. var scene = this.getScene();
  58802. if (objBuffer && scene) {
  58803. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58804. }
  58805. };
  58806. RenderTargetTexture.prototype.dispose = function () {
  58807. if (this._postProcessManager) {
  58808. this._postProcessManager.dispose();
  58809. this._postProcessManager = null;
  58810. }
  58811. this.clearPostProcesses(true);
  58812. if (this._resizeObserver) {
  58813. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58814. this._resizeObserver = null;
  58815. }
  58816. this.renderList = null;
  58817. // Remove from custom render targets
  58818. var scene = this.getScene();
  58819. if (!scene) {
  58820. return;
  58821. }
  58822. var index = scene.customRenderTargets.indexOf(this);
  58823. if (index >= 0) {
  58824. scene.customRenderTargets.splice(index, 1);
  58825. }
  58826. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58827. var camera = _a[_i];
  58828. index = camera.customRenderTargets.indexOf(this);
  58829. if (index >= 0) {
  58830. camera.customRenderTargets.splice(index, 1);
  58831. }
  58832. }
  58833. _super.prototype.dispose.call(this);
  58834. };
  58835. RenderTargetTexture.prototype._rebuild = function () {
  58836. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58837. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58838. }
  58839. if (this._postProcessManager) {
  58840. this._postProcessManager._rebuild();
  58841. }
  58842. };
  58843. /**
  58844. * Clear the info related to rendering groups preventing retention point in material dispose.
  58845. */
  58846. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58847. if (this._renderingManager) {
  58848. this._renderingManager.freeRenderingGroups();
  58849. }
  58850. };
  58851. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58852. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58853. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58854. return RenderTargetTexture;
  58855. }(BABYLON.Texture));
  58856. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58857. })(BABYLON || (BABYLON = {}));
  58858. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58859. var BABYLON;
  58860. (function (BABYLON) {
  58861. ;
  58862. var MultiRenderTarget = /** @class */ (function (_super) {
  58863. __extends(MultiRenderTarget, _super);
  58864. function MultiRenderTarget(name, size, count, scene, options) {
  58865. var _this = this;
  58866. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58867. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58868. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58869. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58870. _this._engine = scene.getEngine();
  58871. if (!_this.isSupported) {
  58872. _this.dispose();
  58873. return;
  58874. }
  58875. var types = [];
  58876. var samplingModes = [];
  58877. for (var i = 0; i < count; i++) {
  58878. if (options && options.types && options.types[i] !== undefined) {
  58879. types.push(options.types[i]);
  58880. }
  58881. else {
  58882. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58883. }
  58884. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58885. samplingModes.push(options.samplingModes[i]);
  58886. }
  58887. else {
  58888. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58889. }
  58890. }
  58891. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58892. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58893. _this._size = size;
  58894. _this._multiRenderTargetOptions = {
  58895. samplingModes: samplingModes,
  58896. generateMipMaps: generateMipMaps,
  58897. generateDepthBuffer: generateDepthBuffer,
  58898. generateStencilBuffer: generateStencilBuffer,
  58899. generateDepthTexture: generateDepthTexture,
  58900. types: types,
  58901. textureCount: count
  58902. };
  58903. _this._createInternalTextures();
  58904. _this._createTextures();
  58905. return _this;
  58906. }
  58907. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58908. get: function () {
  58909. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58910. },
  58911. enumerable: true,
  58912. configurable: true
  58913. });
  58914. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58915. get: function () {
  58916. return this._textures;
  58917. },
  58918. enumerable: true,
  58919. configurable: true
  58920. });
  58921. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58922. get: function () {
  58923. return this._textures[this._textures.length - 1];
  58924. },
  58925. enumerable: true,
  58926. configurable: true
  58927. });
  58928. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58929. set: function (wrap) {
  58930. if (this._textures) {
  58931. for (var i = 0; i < this._textures.length; i++) {
  58932. this._textures[i].wrapU = wrap;
  58933. }
  58934. }
  58935. },
  58936. enumerable: true,
  58937. configurable: true
  58938. });
  58939. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58940. set: function (wrap) {
  58941. if (this._textures) {
  58942. for (var i = 0; i < this._textures.length; i++) {
  58943. this._textures[i].wrapV = wrap;
  58944. }
  58945. }
  58946. },
  58947. enumerable: true,
  58948. configurable: true
  58949. });
  58950. MultiRenderTarget.prototype._rebuild = function () {
  58951. this.releaseInternalTextures();
  58952. this._createInternalTextures();
  58953. for (var i = 0; i < this._internalTextures.length; i++) {
  58954. var texture = this._textures[i];
  58955. texture._texture = this._internalTextures[i];
  58956. }
  58957. // Keeps references to frame buffer and stencil/depth buffer
  58958. this._texture = this._internalTextures[0];
  58959. };
  58960. MultiRenderTarget.prototype._createInternalTextures = function () {
  58961. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58962. };
  58963. MultiRenderTarget.prototype._createTextures = function () {
  58964. this._textures = [];
  58965. for (var i = 0; i < this._internalTextures.length; i++) {
  58966. var texture = new BABYLON.Texture(null, this.getScene());
  58967. texture._texture = this._internalTextures[i];
  58968. this._textures.push(texture);
  58969. }
  58970. // Keeps references to frame buffer and stencil/depth buffer
  58971. this._texture = this._internalTextures[0];
  58972. };
  58973. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58974. get: function () {
  58975. return this._samples;
  58976. },
  58977. set: function (value) {
  58978. if (this._samples === value) {
  58979. return;
  58980. }
  58981. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58982. },
  58983. enumerable: true,
  58984. configurable: true
  58985. });
  58986. MultiRenderTarget.prototype.resize = function (size) {
  58987. this.releaseInternalTextures();
  58988. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58989. this._createInternalTextures();
  58990. };
  58991. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58992. var _this = this;
  58993. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58994. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58995. });
  58996. };
  58997. MultiRenderTarget.prototype.dispose = function () {
  58998. this.releaseInternalTextures();
  58999. _super.prototype.dispose.call(this);
  59000. };
  59001. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59002. if (!this._internalTextures) {
  59003. return;
  59004. }
  59005. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59006. if (this._internalTextures[i] !== undefined) {
  59007. this._internalTextures[i].dispose();
  59008. this._internalTextures.splice(i, 1);
  59009. }
  59010. }
  59011. };
  59012. return MultiRenderTarget;
  59013. }(BABYLON.RenderTargetTexture));
  59014. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59015. })(BABYLON || (BABYLON = {}));
  59016. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59017. var BABYLON;
  59018. (function (BABYLON) {
  59019. var MirrorTexture = /** @class */ (function (_super) {
  59020. __extends(MirrorTexture, _super);
  59021. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59022. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59024. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59025. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59026. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59027. _this._transformMatrix = BABYLON.Matrix.Zero();
  59028. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59029. _this._adaptiveBlurKernel = 0;
  59030. _this._blurKernelX = 0;
  59031. _this._blurKernelY = 0;
  59032. _this._blurRatio = 1.0;
  59033. _this.ignoreCameraViewport = true;
  59034. _this.onBeforeRenderObservable.add(function () {
  59035. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59036. _this._savedViewMatrix = scene.getViewMatrix();
  59037. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59038. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59039. scene.clipPlane = _this.mirrorPlane;
  59040. scene.getEngine().cullBackFaces = false;
  59041. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59042. });
  59043. _this.onAfterRenderObservable.add(function () {
  59044. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59045. scene.getEngine().cullBackFaces = true;
  59046. scene._mirroredCameraPosition = null;
  59047. delete scene.clipPlane;
  59048. });
  59049. return _this;
  59050. }
  59051. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59052. get: function () {
  59053. return this._blurRatio;
  59054. },
  59055. set: function (value) {
  59056. if (this._blurRatio === value) {
  59057. return;
  59058. }
  59059. this._blurRatio = value;
  59060. this._preparePostProcesses();
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59066. set: function (value) {
  59067. this._adaptiveBlurKernel = value;
  59068. this._autoComputeBlurKernel();
  59069. },
  59070. enumerable: true,
  59071. configurable: true
  59072. });
  59073. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59074. set: function (value) {
  59075. this.blurKernelX = value;
  59076. this.blurKernelY = value;
  59077. },
  59078. enumerable: true,
  59079. configurable: true
  59080. });
  59081. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59082. get: function () {
  59083. return this._blurKernelX;
  59084. },
  59085. set: function (value) {
  59086. if (this._blurKernelX === value) {
  59087. return;
  59088. }
  59089. this._blurKernelX = value;
  59090. this._preparePostProcesses();
  59091. },
  59092. enumerable: true,
  59093. configurable: true
  59094. });
  59095. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59096. get: function () {
  59097. return this._blurKernelY;
  59098. },
  59099. set: function (value) {
  59100. if (this._blurKernelY === value) {
  59101. return;
  59102. }
  59103. this._blurKernelY = value;
  59104. this._preparePostProcesses();
  59105. },
  59106. enumerable: true,
  59107. configurable: true
  59108. });
  59109. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59110. var engine = this.getScene().getEngine();
  59111. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59112. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59113. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59114. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59115. };
  59116. MirrorTexture.prototype._onRatioRescale = function () {
  59117. if (this._sizeRatio) {
  59118. this.resize(this._initialSizeParameter);
  59119. if (!this._adaptiveBlurKernel) {
  59120. this._preparePostProcesses();
  59121. }
  59122. }
  59123. if (this._adaptiveBlurKernel) {
  59124. this._autoComputeBlurKernel();
  59125. }
  59126. };
  59127. MirrorTexture.prototype._preparePostProcesses = function () {
  59128. this.clearPostProcesses(true);
  59129. if (this._blurKernelX && this._blurKernelY) {
  59130. var engine = this.getScene().getEngine();
  59131. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59132. 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);
  59133. this._blurX.autoClear = false;
  59134. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59135. this._blurX.inputTexture = this._texture;
  59136. }
  59137. else {
  59138. this._blurX.alwaysForcePOT = true;
  59139. }
  59140. 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);
  59141. this._blurY.autoClear = false;
  59142. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59143. this.addPostProcess(this._blurX);
  59144. this.addPostProcess(this._blurY);
  59145. }
  59146. else {
  59147. if (this._blurY) {
  59148. this.removePostProcess(this._blurY);
  59149. this._blurY.dispose();
  59150. this._blurY = null;
  59151. }
  59152. if (this._blurX) {
  59153. this.removePostProcess(this._blurX);
  59154. this._blurX.dispose();
  59155. this._blurX = null;
  59156. }
  59157. }
  59158. };
  59159. MirrorTexture.prototype.clone = function () {
  59160. var scene = this.getScene();
  59161. if (!scene) {
  59162. return this;
  59163. }
  59164. var textureSize = this.getSize();
  59165. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59166. // Base texture
  59167. newTexture.hasAlpha = this.hasAlpha;
  59168. newTexture.level = this.level;
  59169. // Mirror Texture
  59170. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59171. if (this.renderList) {
  59172. newTexture.renderList = this.renderList.slice(0);
  59173. }
  59174. return newTexture;
  59175. };
  59176. MirrorTexture.prototype.serialize = function () {
  59177. if (!this.name) {
  59178. return null;
  59179. }
  59180. var serializationObject = _super.prototype.serialize.call(this);
  59181. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59182. return serializationObject;
  59183. };
  59184. return MirrorTexture;
  59185. }(BABYLON.RenderTargetTexture));
  59186. BABYLON.MirrorTexture = MirrorTexture;
  59187. })(BABYLON || (BABYLON = {}));
  59188. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59189. var BABYLON;
  59190. (function (BABYLON) {
  59191. /**
  59192. * Creates a refraction texture used by refraction channel of the standard material.
  59193. * @param name the texture name
  59194. * @param size size of the underlying texture
  59195. * @param scene root scene
  59196. */
  59197. var RefractionTexture = /** @class */ (function (_super) {
  59198. __extends(RefractionTexture, _super);
  59199. function RefractionTexture(name, size, scene, generateMipMaps) {
  59200. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59201. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59202. _this.depth = 2.0;
  59203. _this.onBeforeRenderObservable.add(function () {
  59204. scene.clipPlane = _this.refractionPlane;
  59205. });
  59206. _this.onAfterRenderObservable.add(function () {
  59207. delete scene.clipPlane;
  59208. });
  59209. return _this;
  59210. }
  59211. RefractionTexture.prototype.clone = function () {
  59212. var scene = this.getScene();
  59213. if (!scene) {
  59214. return this;
  59215. }
  59216. var textureSize = this.getSize();
  59217. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59218. // Base texture
  59219. newTexture.hasAlpha = this.hasAlpha;
  59220. newTexture.level = this.level;
  59221. // Refraction Texture
  59222. newTexture.refractionPlane = this.refractionPlane.clone();
  59223. if (this.renderList) {
  59224. newTexture.renderList = this.renderList.slice(0);
  59225. }
  59226. newTexture.depth = this.depth;
  59227. return newTexture;
  59228. };
  59229. RefractionTexture.prototype.serialize = function () {
  59230. if (!this.name) {
  59231. return null;
  59232. }
  59233. var serializationObject = _super.prototype.serialize.call(this);
  59234. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59235. serializationObject.depth = this.depth;
  59236. return serializationObject;
  59237. };
  59238. return RefractionTexture;
  59239. }(BABYLON.RenderTargetTexture));
  59240. BABYLON.RefractionTexture = RefractionTexture;
  59241. })(BABYLON || (BABYLON = {}));
  59242. //# sourceMappingURL=babylon.refractionTexture.js.map
  59243. var BABYLON;
  59244. (function (BABYLON) {
  59245. var DynamicTexture = /** @class */ (function (_super) {
  59246. __extends(DynamicTexture, _super);
  59247. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59248. if (scene === void 0) { scene = null; }
  59249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59250. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59251. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59252. _this.name = name;
  59253. _this._engine = _this.getScene().getEngine();
  59254. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59255. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59256. _this._generateMipMaps = generateMipMaps;
  59257. if (options.getContext) {
  59258. _this._canvas = options;
  59259. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59260. }
  59261. else {
  59262. _this._canvas = document.createElement("canvas");
  59263. if (options.width) {
  59264. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59265. }
  59266. else {
  59267. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59268. }
  59269. }
  59270. var textureSize = _this.getSize();
  59271. _this._canvas.width = textureSize.width;
  59272. _this._canvas.height = textureSize.height;
  59273. _this._context = _this._canvas.getContext("2d");
  59274. return _this;
  59275. }
  59276. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59277. get: function () {
  59278. return true;
  59279. },
  59280. enumerable: true,
  59281. configurable: true
  59282. });
  59283. DynamicTexture.prototype._recreate = function (textureSize) {
  59284. this._canvas.width = textureSize.width;
  59285. this._canvas.height = textureSize.height;
  59286. this.releaseInternalTexture();
  59287. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59288. };
  59289. DynamicTexture.prototype.scale = function (ratio) {
  59290. var textureSize = this.getSize();
  59291. textureSize.width *= ratio;
  59292. textureSize.height *= ratio;
  59293. this._recreate(textureSize);
  59294. };
  59295. DynamicTexture.prototype.scaleTo = function (width, height) {
  59296. var textureSize = this.getSize();
  59297. textureSize.width = width;
  59298. textureSize.height = height;
  59299. this._recreate(textureSize);
  59300. };
  59301. DynamicTexture.prototype.getContext = function () {
  59302. return this._context;
  59303. };
  59304. DynamicTexture.prototype.clear = function () {
  59305. var size = this.getSize();
  59306. this._context.fillRect(0, 0, size.width, size.height);
  59307. };
  59308. DynamicTexture.prototype.update = function (invertY) {
  59309. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59310. };
  59311. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59312. if (update === void 0) { update = true; }
  59313. var size = this.getSize();
  59314. if (clearColor) {
  59315. this._context.fillStyle = clearColor;
  59316. this._context.fillRect(0, 0, size.width, size.height);
  59317. }
  59318. this._context.font = font;
  59319. if (x === null || x === undefined) {
  59320. var textSize = this._context.measureText(text);
  59321. x = (size.width - textSize.width) / 2;
  59322. }
  59323. if (y === null || y === undefined) {
  59324. var fontSize = parseInt((font.replace(/\D/g, '')));
  59325. ;
  59326. y = (size.height / 2) + (fontSize / 3.65);
  59327. }
  59328. this._context.fillStyle = color;
  59329. this._context.fillText(text, x, y);
  59330. if (update) {
  59331. this.update(invertY);
  59332. }
  59333. };
  59334. DynamicTexture.prototype.clone = function () {
  59335. var scene = this.getScene();
  59336. if (!scene) {
  59337. return this;
  59338. }
  59339. var textureSize = this.getSize();
  59340. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59341. // Base texture
  59342. newTexture.hasAlpha = this.hasAlpha;
  59343. newTexture.level = this.level;
  59344. // Dynamic Texture
  59345. newTexture.wrapU = this.wrapU;
  59346. newTexture.wrapV = this.wrapV;
  59347. return newTexture;
  59348. };
  59349. DynamicTexture.prototype._rebuild = function () {
  59350. this.update();
  59351. };
  59352. return DynamicTexture;
  59353. }(BABYLON.Texture));
  59354. BABYLON.DynamicTexture = DynamicTexture;
  59355. })(BABYLON || (BABYLON = {}));
  59356. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59357. var BABYLON;
  59358. (function (BABYLON) {
  59359. var VideoTexture = /** @class */ (function (_super) {
  59360. __extends(VideoTexture, _super);
  59361. /**
  59362. * Creates a video texture.
  59363. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59364. * @param {string | null} name optional name, will detect from video source, if not defined
  59365. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59366. * @param {BABYLON.Scene} scene is obviously the current scene.
  59367. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59368. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59369. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59370. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59371. */
  59372. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59373. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59374. if (invertY === void 0) { invertY = false; }
  59375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59376. if (settings === void 0) { settings = {
  59377. autoPlay: true,
  59378. loop: true,
  59379. autoUpdateTexture: true,
  59380. }; }
  59381. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59382. _this._createInternalTexture = function () {
  59383. if (_this._texture != null) {
  59384. return;
  59385. }
  59386. if (!_this._engine.needPOTTextures ||
  59387. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59388. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59389. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59390. }
  59391. else {
  59392. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59393. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59394. _this._generateMipMaps = false;
  59395. }
  59396. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59397. _this._texture.isReady = true;
  59398. _this._updateInternalTexture();
  59399. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59400. _this.onLoadObservable.notifyObservers(_this);
  59401. }
  59402. };
  59403. _this.reset = function () {
  59404. if (_this._texture == null) {
  59405. return;
  59406. }
  59407. _this._texture.dispose();
  59408. _this._texture = null;
  59409. };
  59410. _this._updateInternalTexture = function (e) {
  59411. if (_this._texture == null || !_this._texture.isReady) {
  59412. return;
  59413. }
  59414. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59415. return;
  59416. }
  59417. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59418. };
  59419. _this._engine = _this.getScene().getEngine();
  59420. _this._generateMipMaps = generateMipMaps;
  59421. _this._samplingMode = samplingMode;
  59422. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59423. _this.name = name || _this._getName(src);
  59424. _this.video = _this._getVideo(src);
  59425. if (settings.autoPlay !== undefined) {
  59426. _this.video.autoplay = settings.autoPlay;
  59427. }
  59428. if (settings.loop !== undefined) {
  59429. _this.video.loop = settings.loop;
  59430. }
  59431. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59432. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59433. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59434. _this.video.addEventListener("emptied", _this.reset);
  59435. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59436. _this._createInternalTexture();
  59437. }
  59438. return _this;
  59439. }
  59440. VideoTexture.prototype._getName = function (src) {
  59441. if (src instanceof HTMLVideoElement) {
  59442. return src.currentSrc;
  59443. }
  59444. if (typeof src === "object") {
  59445. return src.toString();
  59446. }
  59447. return src;
  59448. };
  59449. ;
  59450. VideoTexture.prototype._getVideo = function (src) {
  59451. if (src instanceof HTMLVideoElement) {
  59452. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59453. return src;
  59454. }
  59455. var video = document.createElement("video");
  59456. if (typeof src === "string") {
  59457. BABYLON.Tools.SetCorsBehavior(src, video);
  59458. video.src = src;
  59459. }
  59460. else {
  59461. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59462. src.forEach(function (url) {
  59463. var source = document.createElement("source");
  59464. source.src = url;
  59465. video.appendChild(source);
  59466. });
  59467. }
  59468. return video;
  59469. };
  59470. ;
  59471. /**
  59472. * Internal method to initiate `update`.
  59473. */
  59474. VideoTexture.prototype._rebuild = function () {
  59475. this.update();
  59476. };
  59477. /**
  59478. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59479. */
  59480. VideoTexture.prototype.update = function () {
  59481. if (!this.autoUpdateTexture) {
  59482. // Expecting user to call `updateTexture` manually
  59483. return;
  59484. }
  59485. this.updateTexture(true);
  59486. };
  59487. /**
  59488. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59489. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59490. */
  59491. VideoTexture.prototype.updateTexture = function (isVisible) {
  59492. if (!isVisible) {
  59493. return;
  59494. }
  59495. if (this.video.paused) {
  59496. return;
  59497. }
  59498. this._updateInternalTexture();
  59499. };
  59500. /**
  59501. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59502. * @param url New url.
  59503. */
  59504. VideoTexture.prototype.updateURL = function (url) {
  59505. this.video.src = url;
  59506. };
  59507. VideoTexture.prototype.dispose = function () {
  59508. _super.prototype.dispose.call(this);
  59509. this.video.removeEventListener("canplay", this._createInternalTexture);
  59510. this.video.removeEventListener("paused", this._updateInternalTexture);
  59511. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59512. this.video.removeEventListener("emptied", this.reset);
  59513. this.video.pause();
  59514. };
  59515. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59516. var video = document.createElement("video");
  59517. var constraintsDeviceId;
  59518. if (constraints && constraints.deviceId) {
  59519. constraintsDeviceId = {
  59520. exact: constraints.deviceId,
  59521. };
  59522. }
  59523. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59524. if (navigator.mediaDevices) {
  59525. navigator.mediaDevices.getUserMedia({ video: constraints })
  59526. .then(function (stream) {
  59527. if (video.mozSrcObject !== undefined) {
  59528. // hack for Firefox < 19
  59529. video.mozSrcObject = stream;
  59530. }
  59531. else {
  59532. video.srcObject = stream;
  59533. }
  59534. var onPlaying = function () {
  59535. if (onReady) {
  59536. onReady(new VideoTexture("video", video, scene, true, true));
  59537. }
  59538. video.removeEventListener("playing", onPlaying);
  59539. };
  59540. video.addEventListener("playing", onPlaying);
  59541. video.play();
  59542. })
  59543. .catch(function (err) {
  59544. BABYLON.Tools.Error(err.name);
  59545. });
  59546. }
  59547. else {
  59548. navigator.getUserMedia =
  59549. navigator.getUserMedia ||
  59550. navigator.webkitGetUserMedia ||
  59551. navigator.mozGetUserMedia ||
  59552. navigator.msGetUserMedia;
  59553. if (navigator.getUserMedia) {
  59554. navigator.getUserMedia({
  59555. video: {
  59556. deviceId: constraintsDeviceId,
  59557. width: {
  59558. min: (constraints && constraints.minWidth) || 256,
  59559. max: (constraints && constraints.maxWidth) || 640,
  59560. },
  59561. height: {
  59562. min: (constraints && constraints.minHeight) || 256,
  59563. max: (constraints && constraints.maxHeight) || 480,
  59564. },
  59565. },
  59566. }, function (stream) {
  59567. if (video.mozSrcObject !== undefined) {
  59568. // hack for Firefox < 19
  59569. video.mozSrcObject = stream;
  59570. }
  59571. else {
  59572. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59573. }
  59574. video.play();
  59575. if (onReady) {
  59576. onReady(new VideoTexture("video", video, scene, true, true));
  59577. }
  59578. }, function (e) {
  59579. BABYLON.Tools.Error(e.name);
  59580. });
  59581. }
  59582. }
  59583. };
  59584. return VideoTexture;
  59585. }(BABYLON.Texture));
  59586. BABYLON.VideoTexture = VideoTexture;
  59587. })(BABYLON || (BABYLON = {}));
  59588. //# sourceMappingURL=babylon.videoTexture.js.map
  59589. var BABYLON;
  59590. (function (BABYLON) {
  59591. var RawTexture = /** @class */ (function (_super) {
  59592. __extends(RawTexture, _super);
  59593. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59594. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59595. if (invertY === void 0) { invertY = false; }
  59596. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59597. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59598. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59599. _this.format = format;
  59600. _this._engine = scene.getEngine();
  59601. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59602. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59603. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59604. return _this;
  59605. }
  59606. RawTexture.prototype.update = function (data) {
  59607. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59608. };
  59609. // Statics
  59610. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59612. if (invertY === void 0) { invertY = false; }
  59613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59614. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59615. };
  59616. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59618. if (invertY === void 0) { invertY = false; }
  59619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59620. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59621. };
  59622. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59624. if (invertY === void 0) { invertY = false; }
  59625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59626. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59627. };
  59628. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59630. if (invertY === void 0) { invertY = false; }
  59631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59632. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59633. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59634. };
  59635. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59636. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59637. if (invertY === void 0) { invertY = false; }
  59638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59639. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59640. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59641. };
  59642. return RawTexture;
  59643. }(BABYLON.Texture));
  59644. BABYLON.RawTexture = RawTexture;
  59645. })(BABYLON || (BABYLON = {}));
  59646. //# sourceMappingURL=babylon.rawTexture.js.map
  59647. var BABYLON;
  59648. (function (BABYLON) {
  59649. /**
  59650. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59651. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59652. */
  59653. var PostProcess = /** @class */ (function () {
  59654. /**
  59655. * Creates a new instance of @see PostProcess
  59656. * @param name The name of the PostProcess.
  59657. * @param fragmentUrl The url of the fragment shader to be used.
  59658. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59659. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59660. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59661. * @param camera The camera to apply the render pass to.
  59662. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59663. * @param engine The engine which the post process will be applied. (default: current engine)
  59664. * @param reusable If the post process can be reused on the same frame. (default: false)
  59665. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59666. * @param textureType Type of textures used when performing the post process. (default: 0)
  59667. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59668. * @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
  59669. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59670. */
  59671. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59673. if (defines === void 0) { defines = null; }
  59674. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59675. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59676. if (blockCompilation === void 0) { blockCompilation = false; }
  59677. this.name = name;
  59678. /**
  59679. * Width of the texture to apply the post process on
  59680. */
  59681. this.width = -1;
  59682. /**
  59683. * Height of the texture to apply the post process on
  59684. */
  59685. this.height = -1;
  59686. /**
  59687. * If the buffer needs to be cleared before applying the post process. (default: true)
  59688. * Should be set to false if shader will overwrite all previous pixels.
  59689. */
  59690. this.autoClear = true;
  59691. /**
  59692. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59693. */
  59694. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59695. /**
  59696. * Animations to be used for the post processing
  59697. */
  59698. this.animations = new Array();
  59699. /**
  59700. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59701. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59702. */
  59703. this.enablePixelPerfectMode = false;
  59704. /**
  59705. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59706. */
  59707. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59708. /**
  59709. * Force textures to be a power of two (default: false)
  59710. */
  59711. this.alwaysForcePOT = false;
  59712. /**
  59713. * Number of sample textures (default: 1)
  59714. */
  59715. this.samples = 1;
  59716. /**
  59717. * Modify the scale of the post process to be the same as the viewport (default: false)
  59718. */
  59719. this.adaptScaleToCurrentViewport = false;
  59720. this._reusable = false;
  59721. /**
  59722. * Smart array of input and output textures for the post process.
  59723. */
  59724. this._textures = new BABYLON.SmartArray(2);
  59725. /**
  59726. * The index in _textures that corresponds to the output texture.
  59727. */
  59728. this._currentRenderTextureInd = 0;
  59729. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59730. this._texelSize = BABYLON.Vector2.Zero();
  59731. // Events
  59732. /**
  59733. * An event triggered when the postprocess is activated.
  59734. * @type {BABYLON.Observable}
  59735. */
  59736. this.onActivateObservable = new BABYLON.Observable();
  59737. /**
  59738. * An event triggered when the postprocess changes its size.
  59739. * @type {BABYLON.Observable}
  59740. */
  59741. this.onSizeChangedObservable = new BABYLON.Observable();
  59742. /**
  59743. * An event triggered when the postprocess applies its effect.
  59744. * @type {BABYLON.Observable}
  59745. */
  59746. this.onApplyObservable = new BABYLON.Observable();
  59747. /**
  59748. * An event triggered before rendering the postprocess
  59749. * @type {BABYLON.Observable}
  59750. */
  59751. this.onBeforeRenderObservable = new BABYLON.Observable();
  59752. /**
  59753. * An event triggered after rendering the postprocess
  59754. * @type {BABYLON.Observable}
  59755. */
  59756. this.onAfterRenderObservable = new BABYLON.Observable();
  59757. if (camera != null) {
  59758. this._camera = camera;
  59759. this._scene = camera.getScene();
  59760. camera.attachPostProcess(this);
  59761. this._engine = this._scene.getEngine();
  59762. this._scene.postProcesses.push(this);
  59763. }
  59764. else if (engine) {
  59765. this._engine = engine;
  59766. this._engine.postProcesses.push(this);
  59767. }
  59768. this._options = options;
  59769. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59770. this._reusable = reusable || false;
  59771. this._textureType = textureType;
  59772. this._samplers = samplers || [];
  59773. this._samplers.push("textureSampler");
  59774. this._fragmentUrl = fragmentUrl;
  59775. this._vertexUrl = vertexUrl;
  59776. this._parameters = parameters || [];
  59777. this._parameters.push("scale");
  59778. this._indexParameters = indexParameters;
  59779. if (!blockCompilation) {
  59780. this.updateEffect(defines);
  59781. }
  59782. }
  59783. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59784. /**
  59785. * A function that is added to the onActivateObservable
  59786. */
  59787. set: function (callback) {
  59788. if (this._onActivateObserver) {
  59789. this.onActivateObservable.remove(this._onActivateObserver);
  59790. }
  59791. if (callback) {
  59792. this._onActivateObserver = this.onActivateObservable.add(callback);
  59793. }
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59799. /**
  59800. * A function that is added to the onSizeChangedObservable
  59801. */
  59802. set: function (callback) {
  59803. if (this._onSizeChangedObserver) {
  59804. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59805. }
  59806. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. Object.defineProperty(PostProcess.prototype, "onApply", {
  59812. /**
  59813. * A function that is added to the onApplyObservable
  59814. */
  59815. set: function (callback) {
  59816. if (this._onApplyObserver) {
  59817. this.onApplyObservable.remove(this._onApplyObserver);
  59818. }
  59819. this._onApplyObserver = this.onApplyObservable.add(callback);
  59820. },
  59821. enumerable: true,
  59822. configurable: true
  59823. });
  59824. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59825. /**
  59826. * A function that is added to the onBeforeRenderObservable
  59827. */
  59828. set: function (callback) {
  59829. if (this._onBeforeRenderObserver) {
  59830. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59831. }
  59832. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59833. },
  59834. enumerable: true,
  59835. configurable: true
  59836. });
  59837. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59838. /**
  59839. * A function that is added to the onAfterRenderObservable
  59840. */
  59841. set: function (callback) {
  59842. if (this._onAfterRenderObserver) {
  59843. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59844. }
  59845. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59846. },
  59847. enumerable: true,
  59848. configurable: true
  59849. });
  59850. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59851. /**
  59852. * 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
  59853. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59854. */
  59855. get: function () {
  59856. return this._textures.data[this._currentRenderTextureInd];
  59857. },
  59858. set: function (value) {
  59859. this._forcedOutputTexture = value;
  59860. },
  59861. enumerable: true,
  59862. configurable: true
  59863. });
  59864. /**
  59865. * Gets the camera which post process is applied to.
  59866. * @returns The camera the post process is applied to.
  59867. */
  59868. PostProcess.prototype.getCamera = function () {
  59869. return this._camera;
  59870. };
  59871. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59872. /**
  59873. * Gets the texel size of the postprocess.
  59874. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59875. */
  59876. get: function () {
  59877. if (this._shareOutputWithPostProcess) {
  59878. return this._shareOutputWithPostProcess.texelSize;
  59879. }
  59880. if (this._forcedOutputTexture) {
  59881. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59882. }
  59883. return this._texelSize;
  59884. },
  59885. enumerable: true,
  59886. configurable: true
  59887. });
  59888. /**
  59889. * Gets the engine which this post process belongs to.
  59890. * @returns The engine the post process was enabled with.
  59891. */
  59892. PostProcess.prototype.getEngine = function () {
  59893. return this._engine;
  59894. };
  59895. /**
  59896. * The effect that is created when initializing the post process.
  59897. * @returns The created effect corrisponding the the postprocess.
  59898. */
  59899. PostProcess.prototype.getEffect = function () {
  59900. return this._effect;
  59901. };
  59902. /**
  59903. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59904. * @param postProcess The post process to share the output with.
  59905. * @returns This post process.
  59906. */
  59907. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59908. this._disposeTextures();
  59909. this._shareOutputWithPostProcess = postProcess;
  59910. return this;
  59911. };
  59912. /**
  59913. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59914. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59915. */
  59916. PostProcess.prototype.useOwnOutput = function () {
  59917. if (this._textures.length == 0) {
  59918. this._textures = new BABYLON.SmartArray(2);
  59919. }
  59920. this._shareOutputWithPostProcess = null;
  59921. };
  59922. /**
  59923. * Updates the effect with the current post process compile time values and recompiles the shader.
  59924. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59925. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59926. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59927. * @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
  59928. * @param onCompiled Called when the shader has been compiled.
  59929. * @param onError Called if there is an error when compiling a shader.
  59930. */
  59931. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59932. if (defines === void 0) { defines = null; }
  59933. if (uniforms === void 0) { uniforms = null; }
  59934. if (samplers === void 0) { samplers = null; }
  59935. 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);
  59936. };
  59937. /**
  59938. * The post process is reusable if it can be used multiple times within one frame.
  59939. * @returns If the post process is reusable
  59940. */
  59941. PostProcess.prototype.isReusable = function () {
  59942. return this._reusable;
  59943. };
  59944. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59945. PostProcess.prototype.markTextureDirty = function () {
  59946. this.width = -1;
  59947. };
  59948. /**
  59949. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59950. * 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.
  59951. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59952. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59953. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59954. */
  59955. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59956. var _this = this;
  59957. if (sourceTexture === void 0) { sourceTexture = null; }
  59958. camera = camera || this._camera;
  59959. var scene = camera.getScene();
  59960. var engine = scene.getEngine();
  59961. var maxSize = engine.getCaps().maxTextureSize;
  59962. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59963. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59964. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59965. var webVRCamera = camera.parent;
  59966. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59967. requiredWidth /= 2;
  59968. }
  59969. var desiredWidth = (this._options.width || requiredWidth);
  59970. var desiredHeight = this._options.height || requiredHeight;
  59971. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59972. if (this.adaptScaleToCurrentViewport) {
  59973. var currentViewport = engine.currentViewport;
  59974. if (currentViewport) {
  59975. desiredWidth *= currentViewport.width;
  59976. desiredHeight *= currentViewport.height;
  59977. }
  59978. }
  59979. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59980. if (!this._options.width) {
  59981. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59982. }
  59983. if (!this._options.height) {
  59984. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59985. }
  59986. }
  59987. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59988. if (this._textures.length > 0) {
  59989. for (var i = 0; i < this._textures.length; i++) {
  59990. this._engine._releaseTexture(this._textures.data[i]);
  59991. }
  59992. this._textures.reset();
  59993. }
  59994. this.width = desiredWidth;
  59995. this.height = desiredHeight;
  59996. var textureSize = { width: this.width, height: this.height };
  59997. var textureOptions = {
  59998. generateMipMaps: false,
  59999. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60000. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60001. samplingMode: this.renderTargetSamplingMode,
  60002. type: this._textureType
  60003. };
  60004. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60005. if (this._reusable) {
  60006. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60007. }
  60008. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60009. this.onSizeChangedObservable.notifyObservers(this);
  60010. }
  60011. this._textures.forEach(function (texture) {
  60012. if (texture.samples !== _this.samples) {
  60013. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60014. }
  60015. });
  60016. }
  60017. var target;
  60018. if (this._shareOutputWithPostProcess) {
  60019. target = this._shareOutputWithPostProcess.inputTexture;
  60020. }
  60021. else if (this._forcedOutputTexture) {
  60022. target = this._forcedOutputTexture;
  60023. this.width = this._forcedOutputTexture.width;
  60024. this.height = this._forcedOutputTexture.height;
  60025. }
  60026. else {
  60027. target = this.inputTexture;
  60028. }
  60029. // Bind the input of this post process to be used as the output of the previous post process.
  60030. if (this.enablePixelPerfectMode) {
  60031. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60032. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60033. }
  60034. else {
  60035. this._scaleRatio.copyFromFloats(1, 1);
  60036. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60037. }
  60038. this.onActivateObservable.notifyObservers(camera);
  60039. // Clear
  60040. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60041. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60042. }
  60043. if (this._reusable) {
  60044. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60045. }
  60046. };
  60047. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60048. /**
  60049. * If the post process is supported.
  60050. */
  60051. get: function () {
  60052. return this._effect.isSupported;
  60053. },
  60054. enumerable: true,
  60055. configurable: true
  60056. });
  60057. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60058. /**
  60059. * The aspect ratio of the output texture.
  60060. */
  60061. get: function () {
  60062. if (this._shareOutputWithPostProcess) {
  60063. return this._shareOutputWithPostProcess.aspectRatio;
  60064. }
  60065. if (this._forcedOutputTexture) {
  60066. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60067. }
  60068. return this.width / this.height;
  60069. },
  60070. enumerable: true,
  60071. configurable: true
  60072. });
  60073. /**
  60074. * Get a value indicating if the post-process is ready to be used
  60075. * @returns true if the post-process is ready (shader is compiled)
  60076. */
  60077. PostProcess.prototype.isReady = function () {
  60078. return this._effect && this._effect.isReady();
  60079. };
  60080. /**
  60081. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60082. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60083. */
  60084. PostProcess.prototype.apply = function () {
  60085. // Check
  60086. if (!this._effect || !this._effect.isReady())
  60087. return null;
  60088. // States
  60089. this._engine.enableEffect(this._effect);
  60090. this._engine.setState(false);
  60091. this._engine.setDepthBuffer(false);
  60092. this._engine.setDepthWrite(false);
  60093. // Alpha
  60094. this._engine.setAlphaMode(this.alphaMode);
  60095. if (this.alphaConstants) {
  60096. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60097. }
  60098. // Bind the output texture of the preivous post process as the input to this post process.
  60099. var source;
  60100. if (this._shareOutputWithPostProcess) {
  60101. source = this._shareOutputWithPostProcess.inputTexture;
  60102. }
  60103. else if (this._forcedOutputTexture) {
  60104. source = this._forcedOutputTexture;
  60105. }
  60106. else {
  60107. source = this.inputTexture;
  60108. }
  60109. this._effect._bindTexture("textureSampler", source);
  60110. // Parameters
  60111. this._effect.setVector2("scale", this._scaleRatio);
  60112. this.onApplyObservable.notifyObservers(this._effect);
  60113. return this._effect;
  60114. };
  60115. PostProcess.prototype._disposeTextures = function () {
  60116. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60117. return;
  60118. }
  60119. if (this._textures.length > 0) {
  60120. for (var i = 0; i < this._textures.length; i++) {
  60121. this._engine._releaseTexture(this._textures.data[i]);
  60122. }
  60123. }
  60124. this._textures.dispose();
  60125. };
  60126. /**
  60127. * Disposes the post process.
  60128. * @param camera The camera to dispose the post process on.
  60129. */
  60130. PostProcess.prototype.dispose = function (camera) {
  60131. camera = camera || this._camera;
  60132. this._disposeTextures();
  60133. if (this._scene) {
  60134. var index_1 = this._scene.postProcesses.indexOf(this);
  60135. if (index_1 !== -1) {
  60136. this._scene.postProcesses.splice(index_1, 1);
  60137. }
  60138. }
  60139. else {
  60140. var index_2 = this._engine.postProcesses.indexOf(this);
  60141. if (index_2 !== -1) {
  60142. this._engine.postProcesses.splice(index_2, 1);
  60143. }
  60144. }
  60145. if (!camera) {
  60146. return;
  60147. }
  60148. camera.detachPostProcess(this);
  60149. var index = camera._postProcesses.indexOf(this);
  60150. if (index === 0 && camera._postProcesses.length > 0) {
  60151. var firstPostProcess = this._camera._getFirstPostProcess();
  60152. if (firstPostProcess) {
  60153. firstPostProcess.markTextureDirty();
  60154. }
  60155. }
  60156. this.onActivateObservable.clear();
  60157. this.onAfterRenderObservable.clear();
  60158. this.onApplyObservable.clear();
  60159. this.onBeforeRenderObservable.clear();
  60160. this.onSizeChangedObservable.clear();
  60161. };
  60162. return PostProcess;
  60163. }());
  60164. BABYLON.PostProcess = PostProcess;
  60165. })(BABYLON || (BABYLON = {}));
  60166. //# sourceMappingURL=babylon.postProcess.js.map
  60167. var BABYLON;
  60168. (function (BABYLON) {
  60169. var PassPostProcess = /** @class */ (function (_super) {
  60170. __extends(PassPostProcess, _super);
  60171. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60172. if (camera === void 0) { camera = null; }
  60173. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60174. if (blockCompilation === void 0) { blockCompilation = false; }
  60175. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60176. }
  60177. return PassPostProcess;
  60178. }(BABYLON.PostProcess));
  60179. BABYLON.PassPostProcess = PassPostProcess;
  60180. })(BABYLON || (BABYLON = {}));
  60181. //# sourceMappingURL=babylon.passPostProcess.js.map
  60182. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60183. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60184. s = arguments[i];
  60185. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60186. t[p] = s[p];
  60187. }
  60188. return t;
  60189. };
  60190. var BABYLON;
  60191. (function (BABYLON) {
  60192. /**
  60193. * Default implementation of @see IShadowGenerator.
  60194. * This is the main object responsible of generating shadows in the framework.
  60195. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60196. */
  60197. var ShadowGenerator = /** @class */ (function () {
  60198. /**
  60199. * Creates a ShadowGenerator object.
  60200. * A ShadowGenerator is the required tool to use the shadows.
  60201. * Each light casting shadows needs to use its own ShadowGenerator.
  60202. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60203. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60204. * @param light The light object generating the shadows.
  60205. * @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.
  60206. */
  60207. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60208. this._bias = 0.00005;
  60209. this._blurBoxOffset = 1;
  60210. this._blurScale = 2;
  60211. this._blurKernel = 1;
  60212. this._useKernelBlur = false;
  60213. this._filter = ShadowGenerator.FILTER_NONE;
  60214. this._darkness = 0;
  60215. this._transparencyShadow = false;
  60216. /**
  60217. * Controls the extent to which the shadows fade out at the edge of the frustum
  60218. * Used only by directionals and spots
  60219. */
  60220. this.frustumEdgeFalloff = 0;
  60221. /**
  60222. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60223. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60224. * It might on the other hand introduce peter panning.
  60225. */
  60226. this.forceBackFacesOnly = false;
  60227. this._lightDirection = BABYLON.Vector3.Zero();
  60228. this._viewMatrix = BABYLON.Matrix.Zero();
  60229. this._projectionMatrix = BABYLON.Matrix.Zero();
  60230. this._transformMatrix = BABYLON.Matrix.Zero();
  60231. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60232. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60233. this._currentFaceIndex = 0;
  60234. this._currentFaceIndexCache = 0;
  60235. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60236. this._mapSize = mapSize;
  60237. this._light = light;
  60238. this._scene = light.getScene();
  60239. light._shadowGenerator = this;
  60240. // Texture type fallback from float to int if not supported.
  60241. var caps = this._scene.getEngine().getCaps();
  60242. if (!useFullFloatFirst) {
  60243. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60244. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60245. }
  60246. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60247. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60248. }
  60249. else {
  60250. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60251. }
  60252. }
  60253. else {
  60254. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60255. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60256. }
  60257. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60258. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60259. }
  60260. else {
  60261. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60262. }
  60263. }
  60264. this._initializeGenerator();
  60265. }
  60266. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60267. /**
  60268. * Shadow generator mode None: no filtering applied.
  60269. */
  60270. get: function () {
  60271. return ShadowGenerator._FILTER_NONE;
  60272. },
  60273. enumerable: true,
  60274. configurable: true
  60275. });
  60276. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60277. /**
  60278. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60279. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60280. */
  60281. get: function () {
  60282. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60283. },
  60284. enumerable: true,
  60285. configurable: true
  60286. });
  60287. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60288. /**
  60289. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60290. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60291. */
  60292. get: function () {
  60293. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60299. /**
  60300. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60301. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60302. */
  60303. get: function () {
  60304. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60305. },
  60306. enumerable: true,
  60307. configurable: true
  60308. });
  60309. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60310. /**
  60311. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60312. * edge artifacts on steep falloff.
  60313. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60314. */
  60315. get: function () {
  60316. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60317. },
  60318. enumerable: true,
  60319. configurable: true
  60320. });
  60321. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60322. /**
  60323. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60324. * edge artifacts on steep falloff.
  60325. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60326. */
  60327. get: function () {
  60328. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60329. },
  60330. enumerable: true,
  60331. configurable: true
  60332. });
  60333. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60334. /**
  60335. * Gets the bias: offset applied on the depth preventing acnea.
  60336. */
  60337. get: function () {
  60338. return this._bias;
  60339. },
  60340. /**
  60341. * Sets the bias: offset applied on the depth preventing acnea.
  60342. */
  60343. set: function (bias) {
  60344. this._bias = bias;
  60345. },
  60346. enumerable: true,
  60347. configurable: true
  60348. });
  60349. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60350. /**
  60351. * Gets the blur box offset: offset applied during the blur pass.
  60352. * Only usefull if useKernelBlur = false
  60353. */
  60354. get: function () {
  60355. return this._blurBoxOffset;
  60356. },
  60357. /**
  60358. * Sets the blur box offset: offset applied during the blur pass.
  60359. * Only usefull if useKernelBlur = false
  60360. */
  60361. set: function (value) {
  60362. if (this._blurBoxOffset === value) {
  60363. return;
  60364. }
  60365. this._blurBoxOffset = value;
  60366. this._disposeBlurPostProcesses();
  60367. },
  60368. enumerable: true,
  60369. configurable: true
  60370. });
  60371. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60372. /**
  60373. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60374. * 2 means half of the size.
  60375. */
  60376. get: function () {
  60377. return this._blurScale;
  60378. },
  60379. /**
  60380. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60381. * 2 means half of the size.
  60382. */
  60383. set: function (value) {
  60384. if (this._blurScale === value) {
  60385. return;
  60386. }
  60387. this._blurScale = value;
  60388. this._disposeBlurPostProcesses();
  60389. },
  60390. enumerable: true,
  60391. configurable: true
  60392. });
  60393. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60394. /**
  60395. * Gets the blur kernel: kernel size of the blur pass.
  60396. * Only usefull if useKernelBlur = true
  60397. */
  60398. get: function () {
  60399. return this._blurKernel;
  60400. },
  60401. /**
  60402. * Sets the blur kernel: kernel size of the blur pass.
  60403. * Only usefull if useKernelBlur = true
  60404. */
  60405. set: function (value) {
  60406. if (this._blurKernel === value) {
  60407. return;
  60408. }
  60409. this._blurKernel = value;
  60410. this._disposeBlurPostProcesses();
  60411. },
  60412. enumerable: true,
  60413. configurable: true
  60414. });
  60415. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60416. /**
  60417. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60418. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60419. */
  60420. get: function () {
  60421. return this._useKernelBlur;
  60422. },
  60423. /**
  60424. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60425. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60426. */
  60427. set: function (value) {
  60428. if (this._useKernelBlur === value) {
  60429. return;
  60430. }
  60431. this._useKernelBlur = value;
  60432. this._disposeBlurPostProcesses();
  60433. },
  60434. enumerable: true,
  60435. configurable: true
  60436. });
  60437. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60438. /**
  60439. * Gets the depth scale used in ESM mode.
  60440. */
  60441. get: function () {
  60442. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60443. },
  60444. /**
  60445. * Sets the depth scale used in ESM mode.
  60446. * This can override the scale stored on the light.
  60447. */
  60448. set: function (value) {
  60449. this._depthScale = value;
  60450. },
  60451. enumerable: true,
  60452. configurable: true
  60453. });
  60454. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60455. /**
  60456. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60457. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60458. */
  60459. get: function () {
  60460. return this._filter;
  60461. },
  60462. /**
  60463. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60464. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60465. */
  60466. set: function (value) {
  60467. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60468. if (this._light.needCube()) {
  60469. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60470. this.useExponentialShadowMap = true;
  60471. return;
  60472. }
  60473. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60474. this.useCloseExponentialShadowMap = true;
  60475. return;
  60476. }
  60477. }
  60478. if (this._filter === value) {
  60479. return;
  60480. }
  60481. this._filter = value;
  60482. this._disposeBlurPostProcesses();
  60483. this._applyFilterValues();
  60484. this._light._markMeshesAsLightDirty();
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60490. /**
  60491. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60492. */
  60493. get: function () {
  60494. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60495. },
  60496. /**
  60497. * Sets the current filter to Poisson Sampling aka PCF.
  60498. */
  60499. set: function (value) {
  60500. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60501. return;
  60502. }
  60503. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60504. },
  60505. enumerable: true,
  60506. configurable: true
  60507. });
  60508. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60509. /**
  60510. * Gets if the current filter is set to VSM.
  60511. * DEPRECATED. Should use useExponentialShadowMap instead.
  60512. */
  60513. get: function () {
  60514. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60515. return this.useExponentialShadowMap;
  60516. },
  60517. /**
  60518. * Sets the current filter is to VSM.
  60519. * DEPRECATED. Should use useExponentialShadowMap instead.
  60520. */
  60521. set: function (value) {
  60522. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60523. this.useExponentialShadowMap = value;
  60524. },
  60525. enumerable: true,
  60526. configurable: true
  60527. });
  60528. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60529. /**
  60530. * Gets if the current filter is set to blurred VSM.
  60531. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60532. */
  60533. get: function () {
  60534. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60535. return this.useBlurExponentialShadowMap;
  60536. },
  60537. /**
  60538. * Sets the current filter is to blurred VSM.
  60539. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60540. */
  60541. set: function (value) {
  60542. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60543. this.useBlurExponentialShadowMap = value;
  60544. },
  60545. enumerable: true,
  60546. configurable: true
  60547. });
  60548. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60549. /**
  60550. * Gets if the current filter is set to ESM.
  60551. */
  60552. get: function () {
  60553. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60554. },
  60555. /**
  60556. * Sets the current filter is to ESM.
  60557. */
  60558. set: function (value) {
  60559. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60560. return;
  60561. }
  60562. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60563. },
  60564. enumerable: true,
  60565. configurable: true
  60566. });
  60567. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60568. /**
  60569. * Gets if the current filter is set to filtered ESM.
  60570. */
  60571. get: function () {
  60572. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60573. },
  60574. /**
  60575. * Gets if the current filter is set to filtered ESM.
  60576. */
  60577. set: function (value) {
  60578. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60579. return;
  60580. }
  60581. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60582. },
  60583. enumerable: true,
  60584. configurable: true
  60585. });
  60586. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60587. /**
  60588. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60589. * exponential to prevent steep falloff artifacts).
  60590. */
  60591. get: function () {
  60592. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60593. },
  60594. /**
  60595. * Sets the current filter to "close ESM" (using the inverse of the
  60596. * exponential to prevent steep falloff artifacts).
  60597. */
  60598. set: function (value) {
  60599. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60600. return;
  60601. }
  60602. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60603. },
  60604. enumerable: true,
  60605. configurable: true
  60606. });
  60607. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60608. /**
  60609. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60610. * exponential to prevent steep falloff artifacts).
  60611. */
  60612. get: function () {
  60613. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60614. },
  60615. /**
  60616. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60617. * exponential to prevent steep falloff artifacts).
  60618. */
  60619. set: function (value) {
  60620. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60621. return;
  60622. }
  60623. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60624. },
  60625. enumerable: true,
  60626. configurable: true
  60627. });
  60628. /**
  60629. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60630. * 0 means strongest and 1 would means no shadow.
  60631. * @returns the darkness.
  60632. */
  60633. ShadowGenerator.prototype.getDarkness = function () {
  60634. return this._darkness;
  60635. };
  60636. /**
  60637. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60638. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60639. * @returns the shadow generator allowing fluent coding.
  60640. */
  60641. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60642. if (darkness >= 1.0)
  60643. this._darkness = 1.0;
  60644. else if (darkness <= 0.0)
  60645. this._darkness = 0.0;
  60646. else
  60647. this._darkness = darkness;
  60648. return this;
  60649. };
  60650. /**
  60651. * Sets the ability to have transparent shadow (boolean).
  60652. * @param transparent True if transparent else False
  60653. * @returns the shadow generator allowing fluent coding
  60654. */
  60655. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60656. this._transparencyShadow = transparent;
  60657. return this;
  60658. };
  60659. /**
  60660. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60661. * @returns The render target texture if present otherwise, null
  60662. */
  60663. ShadowGenerator.prototype.getShadowMap = function () {
  60664. return this._shadowMap;
  60665. };
  60666. /**
  60667. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60668. * @returns The render target texture if the shadow map is present otherwise, null
  60669. */
  60670. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60671. if (this._shadowMap2) {
  60672. return this._shadowMap2;
  60673. }
  60674. return this._shadowMap;
  60675. };
  60676. /**
  60677. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60678. * @param mesh Mesh to add
  60679. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60680. * @returns the Shadow Generator itself
  60681. */
  60682. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60683. if (includeDescendants === void 0) { includeDescendants = true; }
  60684. if (!this._shadowMap) {
  60685. return this;
  60686. }
  60687. if (!this._shadowMap.renderList) {
  60688. this._shadowMap.renderList = [];
  60689. }
  60690. this._shadowMap.renderList.push(mesh);
  60691. if (includeDescendants) {
  60692. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60693. }
  60694. return this;
  60695. var _a;
  60696. };
  60697. /**
  60698. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60699. * @param mesh Mesh to remove
  60700. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60701. * @returns the Shadow Generator itself
  60702. */
  60703. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60704. if (includeDescendants === void 0) { includeDescendants = true; }
  60705. if (!this._shadowMap || !this._shadowMap.renderList) {
  60706. return this;
  60707. }
  60708. var index = this._shadowMap.renderList.indexOf(mesh);
  60709. if (index !== -1) {
  60710. this._shadowMap.renderList.splice(index, 1);
  60711. }
  60712. if (includeDescendants) {
  60713. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60714. var child = _a[_i];
  60715. this.removeShadowCaster(child);
  60716. }
  60717. }
  60718. return this;
  60719. };
  60720. /**
  60721. * Returns the associated light object.
  60722. * @returns the light generating the shadow
  60723. */
  60724. ShadowGenerator.prototype.getLight = function () {
  60725. return this._light;
  60726. };
  60727. ShadowGenerator.prototype._initializeGenerator = function () {
  60728. this._light._markMeshesAsLightDirty();
  60729. this._initializeShadowMap();
  60730. };
  60731. ShadowGenerator.prototype._initializeShadowMap = function () {
  60732. var _this = this;
  60733. // Render target
  60734. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60735. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60736. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60737. this._shadowMap.anisotropicFilteringLevel = 1;
  60738. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60739. this._shadowMap.renderParticles = false;
  60740. this._shadowMap.ignoreCameraViewport = true;
  60741. // Record Face Index before render.
  60742. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60743. _this._currentFaceIndex = faceIndex;
  60744. });
  60745. // Custom render function.
  60746. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60747. // Blur if required afer render.
  60748. this._shadowMap.onAfterUnbindObservable.add(function () {
  60749. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60750. return;
  60751. }
  60752. var shadowMap = _this.getShadowMapForRendering();
  60753. if (shadowMap) {
  60754. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60755. }
  60756. });
  60757. // Clear according to the chosen filter.
  60758. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60759. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60760. this._shadowMap.onClearObservable.add(function (engine) {
  60761. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60762. engine.clear(zero, true, true, true);
  60763. }
  60764. else {
  60765. engine.clear(one, true, true, true);
  60766. }
  60767. });
  60768. };
  60769. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60770. var _this = this;
  60771. var engine = this._scene.getEngine();
  60772. var targetSize = this._mapSize / this.blurScale;
  60773. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60774. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60775. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60776. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60777. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60778. }
  60779. if (this.useKernelBlur) {
  60780. 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);
  60781. this._kernelBlurXPostprocess.width = targetSize;
  60782. this._kernelBlurXPostprocess.height = targetSize;
  60783. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60784. effect.setTexture("textureSampler", _this._shadowMap);
  60785. });
  60786. 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);
  60787. this._kernelBlurXPostprocess.autoClear = false;
  60788. this._kernelBlurYPostprocess.autoClear = false;
  60789. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60790. this._kernelBlurXPostprocess.packedFloat = true;
  60791. this._kernelBlurYPostprocess.packedFloat = true;
  60792. }
  60793. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60794. }
  60795. else {
  60796. 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);
  60797. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60798. effect.setFloat2("screenSize", targetSize, targetSize);
  60799. effect.setTexture("textureSampler", _this._shadowMap);
  60800. });
  60801. this._boxBlurPostprocess.autoClear = false;
  60802. this._blurPostProcesses = [this._boxBlurPostprocess];
  60803. }
  60804. };
  60805. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60806. var index;
  60807. var engine = this._scene.getEngine();
  60808. if (depthOnlySubMeshes.length) {
  60809. engine.setColorWrite(false);
  60810. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60811. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60812. }
  60813. engine.setColorWrite(true);
  60814. }
  60815. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60816. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60817. }
  60818. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60819. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60820. }
  60821. if (this._transparencyShadow) {
  60822. for (index = 0; index < transparentSubMeshes.length; index++) {
  60823. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60824. }
  60825. }
  60826. };
  60827. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60828. var _this = this;
  60829. var mesh = subMesh.getRenderingMesh();
  60830. var scene = this._scene;
  60831. var engine = scene.getEngine();
  60832. var material = subMesh.getMaterial();
  60833. if (!material) {
  60834. return;
  60835. }
  60836. // Culling
  60837. engine.setState(material.backFaceCulling);
  60838. // Managing instances
  60839. var batch = mesh._getInstancesRenderList(subMesh._id);
  60840. if (batch.mustReturn) {
  60841. return;
  60842. }
  60843. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60844. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60845. engine.enableEffect(this._effect);
  60846. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60847. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60848. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60849. this._effect.setVector3("lightPosition", this.getLight().position);
  60850. if (scene.activeCamera) {
  60851. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60852. }
  60853. // Alpha test
  60854. if (material && material.needAlphaTesting()) {
  60855. var alphaTexture = material.getAlphaTestTexture();
  60856. if (alphaTexture) {
  60857. this._effect.setTexture("diffuseSampler", alphaTexture);
  60858. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60859. }
  60860. }
  60861. // Bones
  60862. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60863. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60864. }
  60865. if (this.forceBackFacesOnly) {
  60866. engine.setState(true, 0, false, true);
  60867. }
  60868. // Draw
  60869. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60870. if (this.forceBackFacesOnly) {
  60871. engine.setState(true, 0, false, false);
  60872. }
  60873. }
  60874. else {
  60875. // Need to reset refresh rate of the shadowMap
  60876. if (this._shadowMap) {
  60877. this._shadowMap.resetRefreshCounter();
  60878. }
  60879. }
  60880. };
  60881. ShadowGenerator.prototype._applyFilterValues = function () {
  60882. if (!this._shadowMap) {
  60883. return;
  60884. }
  60885. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60886. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60887. }
  60888. else {
  60889. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60890. }
  60891. };
  60892. /**
  60893. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60894. * @param onCompiled Callback triggered at the and of the effects compilation
  60895. * @param options Sets of optional options forcing the compilation with different modes
  60896. */
  60897. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60898. var _this = this;
  60899. var localOptions = __assign({ useInstances: false }, options);
  60900. var shadowMap = this.getShadowMap();
  60901. if (!shadowMap) {
  60902. if (onCompiled) {
  60903. onCompiled(this);
  60904. }
  60905. return;
  60906. }
  60907. var renderList = shadowMap.renderList;
  60908. if (!renderList) {
  60909. if (onCompiled) {
  60910. onCompiled(this);
  60911. }
  60912. return;
  60913. }
  60914. var subMeshes = new Array();
  60915. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60916. var mesh = renderList_1[_i];
  60917. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60918. }
  60919. if (subMeshes.length === 0) {
  60920. if (onCompiled) {
  60921. onCompiled(this);
  60922. }
  60923. return;
  60924. }
  60925. var currentIndex = 0;
  60926. var checkReady = function () {
  60927. if (!_this._scene || !_this._scene.getEngine()) {
  60928. return;
  60929. }
  60930. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60931. currentIndex++;
  60932. if (currentIndex >= subMeshes.length) {
  60933. if (onCompiled) {
  60934. onCompiled(_this);
  60935. }
  60936. return;
  60937. }
  60938. }
  60939. setTimeout(checkReady, 16);
  60940. };
  60941. checkReady();
  60942. };
  60943. /**
  60944. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60945. * @param options Sets of optional options forcing the compilation with different modes
  60946. * @returns A promise that resolves when the compilation completes
  60947. */
  60948. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60949. var _this = this;
  60950. return new Promise(function (resolve) {
  60951. _this.forceCompilation(function () {
  60952. resolve();
  60953. }, options);
  60954. });
  60955. };
  60956. /**
  60957. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60958. * @param subMesh The submesh we want to render in the shadow map
  60959. * @param useInstances Defines wether will draw in the map using instances
  60960. * @returns true if ready otherwise, false
  60961. */
  60962. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60963. var defines = [];
  60964. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60965. defines.push("#define FLOAT");
  60966. }
  60967. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60968. defines.push("#define ESM");
  60969. }
  60970. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60971. var mesh = subMesh.getMesh();
  60972. var material = subMesh.getMaterial();
  60973. // Alpha test
  60974. if (material && material.needAlphaTesting()) {
  60975. var alphaTexture = material.getAlphaTestTexture();
  60976. if (alphaTexture) {
  60977. defines.push("#define ALPHATEST");
  60978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60979. attribs.push(BABYLON.VertexBuffer.UVKind);
  60980. defines.push("#define UV1");
  60981. }
  60982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60983. if (alphaTexture.coordinatesIndex === 1) {
  60984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60985. defines.push("#define UV2");
  60986. }
  60987. }
  60988. }
  60989. }
  60990. // Bones
  60991. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60994. if (mesh.numBoneInfluencers > 4) {
  60995. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60996. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60997. }
  60998. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60999. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61000. }
  61001. else {
  61002. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61003. }
  61004. // Instances
  61005. if (useInstances) {
  61006. defines.push("#define INSTANCES");
  61007. attribs.push("world0");
  61008. attribs.push("world1");
  61009. attribs.push("world2");
  61010. attribs.push("world3");
  61011. }
  61012. // Get correct effect
  61013. var join = defines.join("\n");
  61014. if (this._cachedDefines !== join) {
  61015. this._cachedDefines = join;
  61016. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61017. }
  61018. if (!this._effect.isReady()) {
  61019. return false;
  61020. }
  61021. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61022. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61023. this._initializeBlurRTTAndPostProcesses();
  61024. }
  61025. }
  61026. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61027. return false;
  61028. }
  61029. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61030. return false;
  61031. }
  61032. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61033. return false;
  61034. }
  61035. return true;
  61036. };
  61037. /**
  61038. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61039. * @param defines Defines of the material we want to update
  61040. * @param lightIndex Index of the light in the enabled light list of the material
  61041. */
  61042. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61043. var scene = this._scene;
  61044. var light = this._light;
  61045. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61046. return;
  61047. }
  61048. defines["SHADOW" + lightIndex] = true;
  61049. if (this.usePoissonSampling) {
  61050. defines["SHADOWPCF" + lightIndex] = true;
  61051. }
  61052. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61053. defines["SHADOWESM" + lightIndex] = true;
  61054. }
  61055. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61056. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61057. }
  61058. if (light.needCube()) {
  61059. defines["SHADOWCUBE" + lightIndex] = true;
  61060. }
  61061. };
  61062. /**
  61063. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61064. * defined in the generator but impacting the effect).
  61065. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61066. * @param effect The effect we are binfing the information for
  61067. */
  61068. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61069. var light = this._light;
  61070. var scene = this._scene;
  61071. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61072. return;
  61073. }
  61074. var camera = scene.activeCamera;
  61075. if (!camera) {
  61076. return;
  61077. }
  61078. var shadowMap = this.getShadowMap();
  61079. if (!shadowMap) {
  61080. return;
  61081. }
  61082. if (!light.needCube()) {
  61083. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61084. }
  61085. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61086. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61087. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61088. };
  61089. /**
  61090. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61091. * (eq to shadow prjection matrix * light transform matrix)
  61092. * @returns The transform matrix used to create the shadow map
  61093. */
  61094. ShadowGenerator.prototype.getTransformMatrix = function () {
  61095. var scene = this._scene;
  61096. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61097. return this._transformMatrix;
  61098. }
  61099. this._currentRenderID = scene.getRenderId();
  61100. this._currentFaceIndexCache = this._currentFaceIndex;
  61101. var lightPosition = this._light.position;
  61102. if (this._light.computeTransformedInformation()) {
  61103. lightPosition = this._light.transformedPosition;
  61104. }
  61105. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61106. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61107. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61108. }
  61109. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61110. this._cachedPosition.copyFrom(lightPosition);
  61111. this._cachedDirection.copyFrom(this._lightDirection);
  61112. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61113. var shadowMap = this.getShadowMap();
  61114. if (shadowMap) {
  61115. var renderList = shadowMap.renderList;
  61116. if (renderList) {
  61117. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61118. }
  61119. }
  61120. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61121. }
  61122. return this._transformMatrix;
  61123. };
  61124. /**
  61125. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61126. * Cube and 2D textures for instance.
  61127. */
  61128. ShadowGenerator.prototype.recreateShadowMap = function () {
  61129. var shadowMap = this._shadowMap;
  61130. if (!shadowMap) {
  61131. return;
  61132. }
  61133. // Track render list.
  61134. var renderList = shadowMap.renderList;
  61135. // Clean up existing data.
  61136. this._disposeRTTandPostProcesses();
  61137. // Reinitializes.
  61138. this._initializeGenerator();
  61139. // Reaffect the filter to ensure a correct fallback if necessary.
  61140. this.filter = this.filter;
  61141. // Reaffect the filter.
  61142. this._applyFilterValues();
  61143. // Reaffect Render List.
  61144. this._shadowMap.renderList = renderList;
  61145. };
  61146. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61147. if (this._shadowMap2) {
  61148. this._shadowMap2.dispose();
  61149. this._shadowMap2 = null;
  61150. }
  61151. if (this._boxBlurPostprocess) {
  61152. this._boxBlurPostprocess.dispose();
  61153. this._boxBlurPostprocess = null;
  61154. }
  61155. if (this._kernelBlurXPostprocess) {
  61156. this._kernelBlurXPostprocess.dispose();
  61157. this._kernelBlurXPostprocess = null;
  61158. }
  61159. if (this._kernelBlurYPostprocess) {
  61160. this._kernelBlurYPostprocess.dispose();
  61161. this._kernelBlurYPostprocess = null;
  61162. }
  61163. this._blurPostProcesses = [];
  61164. };
  61165. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61166. if (this._shadowMap) {
  61167. this._shadowMap.dispose();
  61168. this._shadowMap = null;
  61169. }
  61170. this._disposeBlurPostProcesses();
  61171. };
  61172. /**
  61173. * Disposes the ShadowGenerator.
  61174. * Returns nothing.
  61175. */
  61176. ShadowGenerator.prototype.dispose = function () {
  61177. this._disposeRTTandPostProcesses();
  61178. if (this._light) {
  61179. this._light._shadowGenerator = null;
  61180. this._light._markMeshesAsLightDirty();
  61181. }
  61182. };
  61183. /**
  61184. * Serializes the shadow generator setup to a json object.
  61185. * @returns The serialized JSON object
  61186. */
  61187. ShadowGenerator.prototype.serialize = function () {
  61188. var serializationObject = {};
  61189. var shadowMap = this.getShadowMap();
  61190. if (!shadowMap) {
  61191. return serializationObject;
  61192. }
  61193. serializationObject.lightId = this._light.id;
  61194. serializationObject.mapSize = shadowMap.getRenderSize();
  61195. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61196. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61197. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61198. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61199. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61200. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61201. serializationObject.depthScale = this.depthScale;
  61202. serializationObject.darkness = this.getDarkness();
  61203. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61204. serializationObject.blurKernel = this.blurKernel;
  61205. serializationObject.blurScale = this.blurScale;
  61206. serializationObject.useKernelBlur = this.useKernelBlur;
  61207. serializationObject.transparencyShadow = this._transparencyShadow;
  61208. serializationObject.renderList = [];
  61209. if (shadowMap.renderList) {
  61210. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61211. var mesh = shadowMap.renderList[meshIndex];
  61212. serializationObject.renderList.push(mesh.id);
  61213. }
  61214. }
  61215. return serializationObject;
  61216. };
  61217. /**
  61218. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61219. * @param parsedShadowGenerator The JSON object to parse
  61220. * @param scene The scene to create the shadow map for
  61221. * @returns The parsed shadow generator
  61222. */
  61223. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61224. //casting to point light, as light is missing the position attr and typescript complains.
  61225. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61226. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61227. var shadowMap = shadowGenerator.getShadowMap();
  61228. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61229. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61230. meshes.forEach(function (mesh) {
  61231. if (!shadowMap) {
  61232. return;
  61233. }
  61234. if (!shadowMap.renderList) {
  61235. shadowMap.renderList = [];
  61236. }
  61237. shadowMap.renderList.push(mesh);
  61238. });
  61239. }
  61240. if (parsedShadowGenerator.usePoissonSampling) {
  61241. shadowGenerator.usePoissonSampling = true;
  61242. }
  61243. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61244. shadowGenerator.useExponentialShadowMap = true;
  61245. }
  61246. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61247. shadowGenerator.useBlurExponentialShadowMap = true;
  61248. }
  61249. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61250. shadowGenerator.useCloseExponentialShadowMap = true;
  61251. }
  61252. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61253. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61254. }
  61255. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61256. shadowGenerator.useExponentialShadowMap = true;
  61257. }
  61258. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61259. shadowGenerator.useBlurExponentialShadowMap = true;
  61260. }
  61261. if (parsedShadowGenerator.depthScale) {
  61262. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61263. }
  61264. if (parsedShadowGenerator.blurScale) {
  61265. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61266. }
  61267. if (parsedShadowGenerator.blurBoxOffset) {
  61268. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61269. }
  61270. if (parsedShadowGenerator.useKernelBlur) {
  61271. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61272. }
  61273. if (parsedShadowGenerator.blurKernel) {
  61274. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61275. }
  61276. if (parsedShadowGenerator.bias !== undefined) {
  61277. shadowGenerator.bias = parsedShadowGenerator.bias;
  61278. }
  61279. if (parsedShadowGenerator.darkness) {
  61280. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61281. }
  61282. if (parsedShadowGenerator.transparencyShadow) {
  61283. shadowGenerator.setTransparencyShadow(true);
  61284. }
  61285. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61286. return shadowGenerator;
  61287. };
  61288. ShadowGenerator._FILTER_NONE = 0;
  61289. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61290. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61291. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61292. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61293. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61294. return ShadowGenerator;
  61295. }());
  61296. BABYLON.ShadowGenerator = ShadowGenerator;
  61297. })(BABYLON || (BABYLON = {}));
  61298. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61299. var BABYLON;
  61300. (function (BABYLON) {
  61301. var DefaultLoadingScreen = /** @class */ (function () {
  61302. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61303. if (_loadingText === void 0) { _loadingText = ""; }
  61304. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61305. var _this = this;
  61306. this._renderingCanvas = _renderingCanvas;
  61307. this._loadingText = _loadingText;
  61308. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61309. // Resize
  61310. this._resizeLoadingUI = function () {
  61311. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61312. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61313. if (!_this._loadingDiv) {
  61314. return;
  61315. }
  61316. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61317. _this._loadingDiv.style.left = canvasRect.left + "px";
  61318. _this._loadingDiv.style.top = canvasRect.top + "px";
  61319. _this._loadingDiv.style.width = canvasRect.width + "px";
  61320. _this._loadingDiv.style.height = canvasRect.height + "px";
  61321. };
  61322. }
  61323. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61324. if (this._loadingDiv) {
  61325. // Do not add a loading screen if there is already one
  61326. return;
  61327. }
  61328. this._loadingDiv = document.createElement("div");
  61329. this._loadingDiv.id = "babylonjsLoadingDiv";
  61330. this._loadingDiv.style.opacity = "0";
  61331. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61332. this._loadingDiv.style.pointerEvents = "none";
  61333. // Loading text
  61334. this._loadingTextDiv = document.createElement("div");
  61335. this._loadingTextDiv.style.position = "absolute";
  61336. this._loadingTextDiv.style.left = "0";
  61337. this._loadingTextDiv.style.top = "50%";
  61338. this._loadingTextDiv.style.marginTop = "80px";
  61339. this._loadingTextDiv.style.width = "100%";
  61340. this._loadingTextDiv.style.height = "20px";
  61341. this._loadingTextDiv.style.fontFamily = "Arial";
  61342. this._loadingTextDiv.style.fontSize = "14px";
  61343. this._loadingTextDiv.style.color = "white";
  61344. this._loadingTextDiv.style.textAlign = "center";
  61345. this._loadingTextDiv.innerHTML = "Loading";
  61346. this._loadingDiv.appendChild(this._loadingTextDiv);
  61347. //set the predefined text
  61348. this._loadingTextDiv.innerHTML = this._loadingText;
  61349. // Generating keyframes
  61350. var style = document.createElement('style');
  61351. style.type = 'text/css';
  61352. 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 }";
  61353. style.innerHTML = keyFrames;
  61354. document.getElementsByTagName('head')[0].appendChild(style);
  61355. // Loading img
  61356. var imgBack = new Image();
  61357. 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";
  61358. imgBack.style.position = "absolute";
  61359. imgBack.style.left = "50%";
  61360. imgBack.style.top = "50%";
  61361. imgBack.style.marginLeft = "-60px";
  61362. imgBack.style.marginTop = "-60px";
  61363. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61364. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61365. imgBack.style.transformOrigin = "50% 50%";
  61366. imgBack.style.webkitTransformOrigin = "50% 50%";
  61367. this._loadingDiv.appendChild(imgBack);
  61368. this._resizeLoadingUI();
  61369. window.addEventListener("resize", this._resizeLoadingUI);
  61370. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61371. document.body.appendChild(this._loadingDiv);
  61372. this._loadingDiv.style.opacity = "1";
  61373. };
  61374. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61375. var _this = this;
  61376. if (!this._loadingDiv) {
  61377. return;
  61378. }
  61379. var onTransitionEnd = function () {
  61380. if (!_this._loadingDiv) {
  61381. return;
  61382. }
  61383. document.body.removeChild(_this._loadingDiv);
  61384. window.removeEventListener("resize", _this._resizeLoadingUI);
  61385. _this._loadingDiv = null;
  61386. };
  61387. this._loadingDiv.style.opacity = "0";
  61388. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61389. };
  61390. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61391. set: function (text) {
  61392. this._loadingText = text;
  61393. if (this._loadingTextDiv) {
  61394. this._loadingTextDiv.innerHTML = this._loadingText;
  61395. }
  61396. },
  61397. enumerable: true,
  61398. configurable: true
  61399. });
  61400. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61401. get: function () {
  61402. return this._loadingDivBackgroundColor;
  61403. },
  61404. set: function (color) {
  61405. this._loadingDivBackgroundColor = color;
  61406. if (!this._loadingDiv) {
  61407. return;
  61408. }
  61409. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61410. },
  61411. enumerable: true,
  61412. configurable: true
  61413. });
  61414. return DefaultLoadingScreen;
  61415. }());
  61416. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61417. })(BABYLON || (BABYLON = {}));
  61418. //# sourceMappingURL=babylon.loadingScreen.js.map
  61419. var BABYLON;
  61420. (function (BABYLON) {
  61421. var SceneLoaderProgressEvent = /** @class */ (function () {
  61422. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61423. this.lengthComputable = lengthComputable;
  61424. this.loaded = loaded;
  61425. this.total = total;
  61426. }
  61427. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61428. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61429. };
  61430. return SceneLoaderProgressEvent;
  61431. }());
  61432. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61433. var SceneLoader = /** @class */ (function () {
  61434. function SceneLoader() {
  61435. }
  61436. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61437. get: function () {
  61438. return 0;
  61439. },
  61440. enumerable: true,
  61441. configurable: true
  61442. });
  61443. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61444. get: function () {
  61445. return 1;
  61446. },
  61447. enumerable: true,
  61448. configurable: true
  61449. });
  61450. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61451. get: function () {
  61452. return 2;
  61453. },
  61454. enumerable: true,
  61455. configurable: true
  61456. });
  61457. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61458. get: function () {
  61459. return 3;
  61460. },
  61461. enumerable: true,
  61462. configurable: true
  61463. });
  61464. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61465. get: function () {
  61466. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61467. },
  61468. set: function (value) {
  61469. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61475. get: function () {
  61476. return SceneLoader._ShowLoadingScreen;
  61477. },
  61478. set: function (value) {
  61479. SceneLoader._ShowLoadingScreen = value;
  61480. },
  61481. enumerable: true,
  61482. configurable: true
  61483. });
  61484. Object.defineProperty(SceneLoader, "loggingLevel", {
  61485. get: function () {
  61486. return SceneLoader._loggingLevel;
  61487. },
  61488. set: function (value) {
  61489. SceneLoader._loggingLevel = value;
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61495. get: function () {
  61496. return SceneLoader._CleanBoneMatrixWeights;
  61497. },
  61498. set: function (value) {
  61499. SceneLoader._CleanBoneMatrixWeights = value;
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. SceneLoader._getDefaultPlugin = function () {
  61505. return SceneLoader._registeredPlugins[".babylon"];
  61506. };
  61507. SceneLoader._getPluginForExtension = function (extension) {
  61508. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61509. if (registeredPlugin) {
  61510. return registeredPlugin;
  61511. }
  61512. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61513. return SceneLoader._getDefaultPlugin();
  61514. };
  61515. SceneLoader._getPluginForDirectLoad = function (data) {
  61516. for (var extension in SceneLoader._registeredPlugins) {
  61517. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61518. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61519. return SceneLoader._registeredPlugins[extension];
  61520. }
  61521. }
  61522. return SceneLoader._getDefaultPlugin();
  61523. };
  61524. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61525. if (sceneFilename.name) {
  61526. sceneFilename = sceneFilename.name;
  61527. }
  61528. var queryStringPosition = sceneFilename.indexOf("?");
  61529. if (queryStringPosition !== -1) {
  61530. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61531. }
  61532. var dotPosition = sceneFilename.lastIndexOf(".");
  61533. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61534. return SceneLoader._getPluginForExtension(extension);
  61535. };
  61536. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61537. SceneLoader._getDirectLoad = function (sceneFilename) {
  61538. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61539. return sceneFilename.substr(5);
  61540. }
  61541. return null;
  61542. };
  61543. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61544. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61545. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61546. var plugin;
  61547. if (registeredPlugin.plugin.createPlugin) {
  61548. plugin = registeredPlugin.plugin.createPlugin();
  61549. }
  61550. else {
  61551. plugin = registeredPlugin.plugin;
  61552. }
  61553. var useArrayBuffer = registeredPlugin.isBinary;
  61554. var database;
  61555. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61556. var dataCallback = function (data, responseURL) {
  61557. if (scene.isDisposed) {
  61558. onError("Scene has been disposed");
  61559. return;
  61560. }
  61561. scene.database = database;
  61562. onSuccess(plugin, data, responseURL);
  61563. };
  61564. var request = null;
  61565. var pluginDisposed = false;
  61566. var onDisposeObservable = plugin.onDisposeObservable;
  61567. if (onDisposeObservable) {
  61568. onDisposeObservable.add(function () {
  61569. pluginDisposed = true;
  61570. if (request) {
  61571. request.abort();
  61572. request = null;
  61573. }
  61574. onDispose();
  61575. });
  61576. }
  61577. var manifestChecked = function () {
  61578. if (pluginDisposed) {
  61579. return;
  61580. }
  61581. var url = rootUrl + sceneFilename;
  61582. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61583. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61584. } : undefined, database, useArrayBuffer, function (request, exception) {
  61585. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61586. });
  61587. };
  61588. if (directLoad) {
  61589. dataCallback(directLoad);
  61590. return plugin;
  61591. }
  61592. if (rootUrl.indexOf("file:") === -1) {
  61593. if (scene.getEngine().enableOfflineSupport) {
  61594. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61595. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61596. }
  61597. else {
  61598. manifestChecked();
  61599. }
  61600. }
  61601. else {
  61602. var fileOrString = sceneFilename;
  61603. if (fileOrString.name) {
  61604. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61605. }
  61606. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61607. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61608. }
  61609. else {
  61610. onError("Unable to find file named " + sceneFilename);
  61611. }
  61612. }
  61613. return plugin;
  61614. };
  61615. // Public functions
  61616. SceneLoader.GetPluginForExtension = function (extension) {
  61617. return SceneLoader._getPluginForExtension(extension).plugin;
  61618. };
  61619. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61620. return !!SceneLoader._registeredPlugins[extension];
  61621. };
  61622. SceneLoader.RegisterPlugin = function (plugin) {
  61623. if (typeof plugin.extensions === "string") {
  61624. var extension = plugin.extensions;
  61625. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61626. plugin: plugin,
  61627. isBinary: false
  61628. };
  61629. }
  61630. else {
  61631. var extensions = plugin.extensions;
  61632. Object.keys(extensions).forEach(function (extension) {
  61633. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61634. plugin: plugin,
  61635. isBinary: extensions[extension].isBinary
  61636. };
  61637. });
  61638. }
  61639. };
  61640. /**
  61641. * Import meshes into a scene
  61642. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61643. * @param rootUrl a string that defines the root url for scene and resources
  61644. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61645. * @param scene the instance of BABYLON.Scene to append to
  61646. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61647. * @param onProgress a callback with a progress event for each file being loaded
  61648. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61649. * @param pluginExtension the extension used to determine the plugin
  61650. * @returns The loaded plugin
  61651. */
  61652. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61653. if (onSuccess === void 0) { onSuccess = null; }
  61654. if (onProgress === void 0) { onProgress = null; }
  61655. if (onError === void 0) { onError = null; }
  61656. if (pluginExtension === void 0) { pluginExtension = null; }
  61657. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61658. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61659. return null;
  61660. }
  61661. var loadingToken = {};
  61662. scene._addPendingData(loadingToken);
  61663. var disposeHandler = function () {
  61664. scene._removePendingData(loadingToken);
  61665. };
  61666. var errorHandler = function (message, exception) {
  61667. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61668. if (onError) {
  61669. onError(scene, errorMessage, exception);
  61670. }
  61671. else {
  61672. BABYLON.Tools.Error(errorMessage);
  61673. // should the exception be thrown?
  61674. }
  61675. disposeHandler();
  61676. };
  61677. var progressHandler = onProgress ? function (event) {
  61678. try {
  61679. onProgress(event);
  61680. }
  61681. catch (e) {
  61682. errorHandler("Error in onProgress callback", e);
  61683. }
  61684. } : undefined;
  61685. var successHandler = function (meshes, particleSystems, skeletons) {
  61686. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61687. if (onSuccess) {
  61688. try {
  61689. onSuccess(meshes, particleSystems, skeletons);
  61690. }
  61691. catch (e) {
  61692. errorHandler("Error in onSuccess callback", e);
  61693. }
  61694. }
  61695. scene._removePendingData(loadingToken);
  61696. };
  61697. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61698. if (plugin.rewriteRootURL) {
  61699. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61700. }
  61701. if (sceneFilename === "") {
  61702. if (sceneFilename === "") {
  61703. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61704. }
  61705. }
  61706. if (plugin.importMesh) {
  61707. var syncedPlugin = plugin;
  61708. var meshes = new Array();
  61709. var particleSystems = new Array();
  61710. var skeletons = new Array();
  61711. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61712. return;
  61713. }
  61714. scene.loadingPluginName = plugin.name;
  61715. successHandler(meshes, particleSystems, skeletons);
  61716. }
  61717. else {
  61718. var asyncedPlugin = plugin;
  61719. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61720. scene.loadingPluginName = plugin.name;
  61721. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61722. }).catch(function (error) {
  61723. errorHandler(error.message, error);
  61724. });
  61725. }
  61726. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61727. };
  61728. /**
  61729. * Import meshes into a scene
  61730. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61731. * @param rootUrl a string that defines the root url for scene and resources
  61732. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61733. * @param scene the instance of BABYLON.Scene to append to
  61734. * @param onProgress a callback with a progress event for each file being loaded
  61735. * @param pluginExtension the extension used to determine the plugin
  61736. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61737. */
  61738. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61739. if (onProgress === void 0) { onProgress = null; }
  61740. if (pluginExtension === void 0) { pluginExtension = null; }
  61741. return new Promise(function (resolve, reject) {
  61742. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61743. resolve({
  61744. meshes: meshes,
  61745. particleSystems: particleSystems,
  61746. skeletons: skeletons
  61747. });
  61748. }, onProgress, function (scene, message, exception) {
  61749. reject(exception || new Error(message));
  61750. });
  61751. });
  61752. };
  61753. /**
  61754. * Load a scene
  61755. * @param rootUrl a string that defines the root url for scene and resources
  61756. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61757. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61758. * @param onSuccess a callback with the scene when import succeeds
  61759. * @param onProgress a callback with a progress event for each file being loaded
  61760. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61761. * @param pluginExtension the extension used to determine the plugin
  61762. * @returns The loaded plugin
  61763. */
  61764. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61765. if (onSuccess === void 0) { onSuccess = null; }
  61766. if (onProgress === void 0) { onProgress = null; }
  61767. if (onError === void 0) { onError = null; }
  61768. if (pluginExtension === void 0) { pluginExtension = null; }
  61769. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61770. };
  61771. /**
  61772. * Load a scene
  61773. * @param rootUrl a string that defines the root url for scene and resources
  61774. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61775. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61776. * @param onProgress a callback with a progress event for each file being loaded
  61777. * @param pluginExtension the extension used to determine the plugin
  61778. * @returns The loaded scene
  61779. */
  61780. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61781. if (onProgress === void 0) { onProgress = null; }
  61782. if (pluginExtension === void 0) { pluginExtension = null; }
  61783. return new Promise(function (resolve, reject) {
  61784. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61785. resolve(scene);
  61786. }, onProgress, function (scene, message, exception) {
  61787. reject(exception || new Error(message));
  61788. }, pluginExtension);
  61789. });
  61790. };
  61791. /**
  61792. * Append a scene
  61793. * @param rootUrl a string that defines the root url for scene and resources
  61794. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61795. * @param scene is the instance of BABYLON.Scene to append to
  61796. * @param onSuccess a callback with the scene when import succeeds
  61797. * @param onProgress a callback with a progress event for each file being loaded
  61798. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61799. * @param pluginExtension the extension used to determine the plugin
  61800. * @returns The loaded plugin
  61801. */
  61802. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61803. if (onSuccess === void 0) { onSuccess = null; }
  61804. if (onProgress === void 0) { onProgress = null; }
  61805. if (onError === void 0) { onError = null; }
  61806. if (pluginExtension === void 0) { pluginExtension = null; }
  61807. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61808. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61809. return null;
  61810. }
  61811. if (SceneLoader.ShowLoadingScreen) {
  61812. scene.getEngine().displayLoadingUI();
  61813. }
  61814. var loadingToken = {};
  61815. scene._addPendingData(loadingToken);
  61816. var disposeHandler = function () {
  61817. scene._removePendingData(loadingToken);
  61818. scene.getEngine().hideLoadingUI();
  61819. };
  61820. var errorHandler = function (message, exception) {
  61821. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61822. if (onError) {
  61823. onError(scene, errorMessage, exception);
  61824. }
  61825. else {
  61826. BABYLON.Tools.Error(errorMessage);
  61827. // should the exception be thrown?
  61828. }
  61829. disposeHandler();
  61830. };
  61831. var progressHandler = onProgress ? function (event) {
  61832. try {
  61833. onProgress(event);
  61834. }
  61835. catch (e) {
  61836. errorHandler("Error in onProgress callback", e);
  61837. }
  61838. } : undefined;
  61839. var successHandler = function () {
  61840. if (onSuccess) {
  61841. try {
  61842. onSuccess(scene);
  61843. }
  61844. catch (e) {
  61845. errorHandler("Error in onSuccess callback", e);
  61846. }
  61847. }
  61848. scene._removePendingData(loadingToken);
  61849. };
  61850. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61851. if (sceneFilename === "") {
  61852. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61853. }
  61854. if (plugin.load) {
  61855. var syncedPlugin = plugin;
  61856. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61857. return;
  61858. }
  61859. scene.loadingPluginName = plugin.name;
  61860. successHandler();
  61861. }
  61862. else {
  61863. var asyncedPlugin = plugin;
  61864. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61865. scene.loadingPluginName = plugin.name;
  61866. successHandler();
  61867. }).catch(function (error) {
  61868. errorHandler(error.message, error);
  61869. });
  61870. }
  61871. if (SceneLoader.ShowLoadingScreen) {
  61872. scene.executeWhenReady(function () {
  61873. scene.getEngine().hideLoadingUI();
  61874. });
  61875. }
  61876. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61877. };
  61878. /**
  61879. * Append a scene
  61880. * @param rootUrl a string that defines the root url for scene and resources
  61881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61882. * @param scene is the instance of BABYLON.Scene to append to
  61883. * @param onProgress a callback with a progress event for each file being loaded
  61884. * @param pluginExtension the extension used to determine the plugin
  61885. * @returns The given scene
  61886. */
  61887. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61888. if (onProgress === void 0) { onProgress = null; }
  61889. if (pluginExtension === void 0) { pluginExtension = null; }
  61890. return new Promise(function (resolve, reject) {
  61891. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61892. resolve(scene);
  61893. }, onProgress, function (scene, message, exception) {
  61894. reject(exception || new Error(message));
  61895. }, pluginExtension);
  61896. });
  61897. };
  61898. /**
  61899. * Load a scene into an asset container
  61900. * @param rootUrl a string that defines the root url for scene and resources
  61901. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61902. * @param scene is the instance of BABYLON.Scene to append to
  61903. * @param onSuccess a callback with the scene when import succeeds
  61904. * @param onProgress a callback with a progress event for each file being loaded
  61905. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61906. * @param pluginExtension the extension used to determine the plugin
  61907. * @returns The loaded plugin
  61908. */
  61909. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61910. if (onSuccess === void 0) { onSuccess = null; }
  61911. if (onProgress === void 0) { onProgress = null; }
  61912. if (onError === void 0) { onError = null; }
  61913. if (pluginExtension === void 0) { pluginExtension = null; }
  61914. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61915. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61916. return null;
  61917. }
  61918. var loadingToken = {};
  61919. scene._addPendingData(loadingToken);
  61920. var disposeHandler = function () {
  61921. scene._removePendingData(loadingToken);
  61922. };
  61923. var errorHandler = function (message, exception) {
  61924. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61925. if (onError) {
  61926. onError(scene, errorMessage, exception);
  61927. }
  61928. else {
  61929. BABYLON.Tools.Error(errorMessage);
  61930. // should the exception be thrown?
  61931. }
  61932. disposeHandler();
  61933. };
  61934. var progressHandler = onProgress ? function (event) {
  61935. try {
  61936. onProgress(event);
  61937. }
  61938. catch (e) {
  61939. errorHandler("Error in onProgress callback", e);
  61940. }
  61941. } : undefined;
  61942. var successHandler = function (assets) {
  61943. if (onSuccess) {
  61944. try {
  61945. onSuccess(assets);
  61946. }
  61947. catch (e) {
  61948. errorHandler("Error in onSuccess callback", e);
  61949. }
  61950. }
  61951. scene._removePendingData(loadingToken);
  61952. };
  61953. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61954. if (plugin.loadAssetContainer) {
  61955. var syncedPlugin = plugin;
  61956. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61957. if (!assetContainer) {
  61958. return;
  61959. }
  61960. scene.loadingPluginName = plugin.name;
  61961. successHandler(assetContainer);
  61962. }
  61963. else if (plugin.loadAssetContainerAsync) {
  61964. var asyncedPlugin = plugin;
  61965. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61966. scene.loadingPluginName = plugin.name;
  61967. successHandler(assetContainer);
  61968. }).catch(function (error) {
  61969. errorHandler(error.message, error);
  61970. });
  61971. }
  61972. else {
  61973. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61974. }
  61975. if (SceneLoader.ShowLoadingScreen) {
  61976. scene.executeWhenReady(function () {
  61977. scene.getEngine().hideLoadingUI();
  61978. });
  61979. }
  61980. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61981. };
  61982. /**
  61983. * Load a scene into an asset container
  61984. * @param rootUrl a string that defines the root url for scene and resources
  61985. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61986. * @param scene is the instance of BABYLON.Scene to append to
  61987. * @param onProgress a callback with a progress event for each file being loaded
  61988. * @param pluginExtension the extension used to determine the plugin
  61989. * @returns The loaded asset container
  61990. */
  61991. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61992. if (onProgress === void 0) { onProgress = null; }
  61993. if (pluginExtension === void 0) { pluginExtension = null; }
  61994. return new Promise(function (resolve, reject) {
  61995. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61996. resolve(assetContainer);
  61997. }, onProgress, function (scene, message, exception) {
  61998. reject(exception || new Error(message));
  61999. }, pluginExtension);
  62000. });
  62001. };
  62002. // Flags
  62003. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62004. SceneLoader._ShowLoadingScreen = true;
  62005. SceneLoader._CleanBoneMatrixWeights = false;
  62006. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62007. // Members
  62008. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62009. SceneLoader._registeredPlugins = {};
  62010. return SceneLoader;
  62011. }());
  62012. BABYLON.SceneLoader = SceneLoader;
  62013. ;
  62014. })(BABYLON || (BABYLON = {}));
  62015. //# sourceMappingURL=babylon.sceneLoader.js.map
  62016. var BABYLON;
  62017. (function (BABYLON) {
  62018. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62019. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62020. var parsedMaterial = parsedData.materials[index];
  62021. if (parsedMaterial.id === id) {
  62022. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62023. }
  62024. }
  62025. return null;
  62026. };
  62027. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62028. for (var i in names) {
  62029. if (mesh.name === names[i]) {
  62030. hierarchyIds.push(mesh.id);
  62031. return true;
  62032. }
  62033. }
  62034. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62035. hierarchyIds.push(mesh.id);
  62036. return true;
  62037. }
  62038. return false;
  62039. };
  62040. var logOperation = function (operation, producer) {
  62041. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62042. };
  62043. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62044. if (addToScene === void 0) { addToScene = false; }
  62045. var container = new BABYLON.AssetContainer(scene);
  62046. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62047. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62048. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62049. // and avoid problems with multiple concurrent .babylon loads.
  62050. var log = "importScene has failed JSON parse";
  62051. try {
  62052. var parsedData = JSON.parse(data);
  62053. log = "";
  62054. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62055. var index;
  62056. var cache;
  62057. // Lights
  62058. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62059. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62060. var parsedLight = parsedData.lights[index];
  62061. var light = BABYLON.Light.Parse(parsedLight, scene);
  62062. if (light) {
  62063. container.lights.push(light);
  62064. log += (index === 0 ? "\n\tLights:" : "");
  62065. log += "\n\t\t" + light.toString(fullDetails);
  62066. }
  62067. }
  62068. }
  62069. // Animations
  62070. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62071. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62072. var parsedAnimation = parsedData.animations[index];
  62073. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62074. scene.animations.push(animation);
  62075. container.animations.push(animation);
  62076. log += (index === 0 ? "\n\tAnimations:" : "");
  62077. log += "\n\t\t" + animation.toString(fullDetails);
  62078. }
  62079. }
  62080. // Materials
  62081. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62082. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62083. var parsedMaterial = parsedData.materials[index];
  62084. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62085. container.materials.push(mat);
  62086. log += (index === 0 ? "\n\tMaterials:" : "");
  62087. log += "\n\t\t" + mat.toString(fullDetails);
  62088. }
  62089. }
  62090. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62091. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62092. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62093. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62094. container.multiMaterials.push(mmat);
  62095. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62096. log += "\n\t\t" + mmat.toString(fullDetails);
  62097. }
  62098. }
  62099. // Morph targets
  62100. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62101. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62102. var managerData = _a[_i];
  62103. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62104. }
  62105. }
  62106. // Skeletons
  62107. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62108. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62109. var parsedSkeleton = parsedData.skeletons[index];
  62110. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62111. container.skeletons.push(skeleton);
  62112. log += (index === 0 ? "\n\tSkeletons:" : "");
  62113. log += "\n\t\t" + skeleton.toString(fullDetails);
  62114. }
  62115. }
  62116. // Geometries
  62117. var geometries = parsedData.geometries;
  62118. if (geometries !== undefined && geometries !== null) {
  62119. var addedGeometry = new Array();
  62120. // Boxes
  62121. var boxes = geometries.boxes;
  62122. if (boxes !== undefined && boxes !== null) {
  62123. for (index = 0, cache = boxes.length; index < cache; index++) {
  62124. var parsedBox = boxes[index];
  62125. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62126. }
  62127. }
  62128. // Spheres
  62129. var spheres = geometries.spheres;
  62130. if (spheres !== undefined && spheres !== null) {
  62131. for (index = 0, cache = spheres.length; index < cache; index++) {
  62132. var parsedSphere = spheres[index];
  62133. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62134. }
  62135. }
  62136. // Cylinders
  62137. var cylinders = geometries.cylinders;
  62138. if (cylinders !== undefined && cylinders !== null) {
  62139. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62140. var parsedCylinder = cylinders[index];
  62141. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62142. }
  62143. }
  62144. // Toruses
  62145. var toruses = geometries.toruses;
  62146. if (toruses !== undefined && toruses !== null) {
  62147. for (index = 0, cache = toruses.length; index < cache; index++) {
  62148. var parsedTorus = toruses[index];
  62149. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62150. }
  62151. }
  62152. // Grounds
  62153. var grounds = geometries.grounds;
  62154. if (grounds !== undefined && grounds !== null) {
  62155. for (index = 0, cache = grounds.length; index < cache; index++) {
  62156. var parsedGround = grounds[index];
  62157. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62158. }
  62159. }
  62160. // Planes
  62161. var planes = geometries.planes;
  62162. if (planes !== undefined && planes !== null) {
  62163. for (index = 0, cache = planes.length; index < cache; index++) {
  62164. var parsedPlane = planes[index];
  62165. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62166. }
  62167. }
  62168. // TorusKnots
  62169. var torusKnots = geometries.torusKnots;
  62170. if (torusKnots !== undefined && torusKnots !== null) {
  62171. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62172. var parsedTorusKnot = torusKnots[index];
  62173. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62174. }
  62175. }
  62176. // VertexData
  62177. var vertexData = geometries.vertexData;
  62178. if (vertexData !== undefined && vertexData !== null) {
  62179. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62180. var parsedVertexData = vertexData[index];
  62181. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62182. }
  62183. }
  62184. addedGeometry.forEach(function (g) {
  62185. if (g) {
  62186. container.geometries.push(g);
  62187. }
  62188. });
  62189. }
  62190. // Transform nodes
  62191. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62192. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62193. var parsedTransformNode = parsedData.transformNodes[index];
  62194. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62195. container.transformNodes.push(node);
  62196. }
  62197. }
  62198. // Meshes
  62199. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62200. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62201. var parsedMesh = parsedData.meshes[index];
  62202. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62203. container.meshes.push(mesh);
  62204. log += (index === 0 ? "\n\tMeshes:" : "");
  62205. log += "\n\t\t" + mesh.toString(fullDetails);
  62206. }
  62207. }
  62208. // Cameras
  62209. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62210. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62211. var parsedCamera = parsedData.cameras[index];
  62212. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62213. container.cameras.push(camera);
  62214. log += (index === 0 ? "\n\tCameras:" : "");
  62215. log += "\n\t\t" + camera.toString(fullDetails);
  62216. }
  62217. }
  62218. // Browsing all the graph to connect the dots
  62219. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62220. var camera = scene.cameras[index];
  62221. if (camera._waitingParentId) {
  62222. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62223. camera._waitingParentId = null;
  62224. }
  62225. }
  62226. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62227. var light_1 = scene.lights[index];
  62228. if (light_1 && light_1._waitingParentId) {
  62229. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62230. light_1._waitingParentId = null;
  62231. }
  62232. }
  62233. // Sounds
  62234. // TODO: add sound
  62235. var loadedSounds = [];
  62236. var loadedSound;
  62237. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62238. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62239. var parsedSound = parsedData.sounds[index];
  62240. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62241. if (!parsedSound.url)
  62242. parsedSound.url = parsedSound.name;
  62243. if (!loadedSounds[parsedSound.url]) {
  62244. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62245. loadedSounds[parsedSound.url] = loadedSound;
  62246. container.sounds.push(loadedSound);
  62247. }
  62248. else {
  62249. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62250. }
  62251. }
  62252. else {
  62253. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62254. }
  62255. }
  62256. }
  62257. loadedSounds = [];
  62258. // Connect parents & children and parse actions
  62259. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62260. var transformNode = scene.transformNodes[index];
  62261. if (transformNode._waitingParentId) {
  62262. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62263. transformNode._waitingParentId = null;
  62264. }
  62265. }
  62266. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62267. var mesh = scene.meshes[index];
  62268. if (mesh._waitingParentId) {
  62269. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62270. mesh._waitingParentId = null;
  62271. }
  62272. if (mesh._waitingActions) {
  62273. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62274. mesh._waitingActions = null;
  62275. }
  62276. }
  62277. // freeze world matrix application
  62278. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62279. var currentMesh = scene.meshes[index];
  62280. if (currentMesh._waitingFreezeWorldMatrix) {
  62281. currentMesh.freezeWorldMatrix();
  62282. currentMesh._waitingFreezeWorldMatrix = null;
  62283. }
  62284. else {
  62285. currentMesh.computeWorldMatrix(true);
  62286. }
  62287. }
  62288. // Particles Systems
  62289. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62290. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62291. var parsedParticleSystem = parsedData.particleSystems[index];
  62292. if (parsedParticleSystem.activeParticleCount) {
  62293. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62294. container.particleSystems.push(ps);
  62295. }
  62296. else {
  62297. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62298. container.particleSystems.push(ps);
  62299. }
  62300. }
  62301. }
  62302. // Lens flares
  62303. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62304. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62305. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62306. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62307. container.lensFlareSystems.push(lf);
  62308. }
  62309. }
  62310. // Shadows
  62311. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62312. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62313. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62314. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62315. container.shadowGenerators.push(sg);
  62316. }
  62317. }
  62318. // Lights exclusions / inclusions
  62319. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62320. var light_2 = scene.lights[index];
  62321. // Excluded check
  62322. if (light_2._excludedMeshesIds.length > 0) {
  62323. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62324. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62325. if (excludedMesh) {
  62326. light_2.excludedMeshes.push(excludedMesh);
  62327. }
  62328. }
  62329. light_2._excludedMeshesIds = [];
  62330. }
  62331. // Included check
  62332. if (light_2._includedOnlyMeshesIds.length > 0) {
  62333. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62334. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62335. if (includedOnlyMesh) {
  62336. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62337. }
  62338. }
  62339. light_2._includedOnlyMeshesIds = [];
  62340. }
  62341. }
  62342. // Actions (scene)
  62343. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62344. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62345. }
  62346. if (!addToScene) {
  62347. container.removeAllFromScene();
  62348. }
  62349. }
  62350. catch (err) {
  62351. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62352. if (onError) {
  62353. onError(msg, err);
  62354. }
  62355. else {
  62356. BABYLON.Tools.Log(msg);
  62357. throw err;
  62358. }
  62359. }
  62360. finally {
  62361. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62362. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62363. }
  62364. }
  62365. return container;
  62366. };
  62367. BABYLON.SceneLoader.RegisterPlugin({
  62368. name: "babylon.js",
  62369. extensions: ".babylon",
  62370. canDirectLoad: function (data) {
  62371. if (data.indexOf("babylon") !== -1) {
  62372. return true;
  62373. }
  62374. return false;
  62375. },
  62376. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62377. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62378. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62379. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62380. // and avoid problems with multiple concurrent .babylon loads.
  62381. var log = "importMesh has failed JSON parse";
  62382. try {
  62383. var parsedData = JSON.parse(data);
  62384. log = "";
  62385. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62386. if (!meshesNames) {
  62387. meshesNames = null;
  62388. }
  62389. else if (!Array.isArray(meshesNames)) {
  62390. meshesNames = [meshesNames];
  62391. }
  62392. var hierarchyIds = new Array();
  62393. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62394. var loadedSkeletonsIds = [];
  62395. var loadedMaterialsIds = [];
  62396. var index;
  62397. var cache;
  62398. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62399. var parsedMesh = parsedData.meshes[index];
  62400. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62401. if (meshesNames !== null) {
  62402. // Remove found mesh name from list.
  62403. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62404. }
  62405. //Geometry?
  62406. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62407. //does the file contain geometries?
  62408. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62409. //find the correct geometry and add it to the scene
  62410. var found = false;
  62411. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62412. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62413. return;
  62414. }
  62415. else {
  62416. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62417. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62418. switch (geometryType) {
  62419. case "boxes":
  62420. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62421. break;
  62422. case "spheres":
  62423. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62424. break;
  62425. case "cylinders":
  62426. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62427. break;
  62428. case "toruses":
  62429. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62430. break;
  62431. case "grounds":
  62432. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62433. break;
  62434. case "planes":
  62435. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62436. break;
  62437. case "torusKnots":
  62438. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62439. break;
  62440. case "vertexData":
  62441. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62442. break;
  62443. }
  62444. found = true;
  62445. }
  62446. });
  62447. }
  62448. });
  62449. if (found === false) {
  62450. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62451. }
  62452. }
  62453. }
  62454. // Material ?
  62455. if (parsedMesh.materialId) {
  62456. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62457. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62458. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62459. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62460. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62461. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62462. var subMatId = parsedMultiMaterial.materials[matIndex];
  62463. loadedMaterialsIds.push(subMatId);
  62464. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62465. if (mat) {
  62466. log += "\n\tMaterial " + mat.toString(fullDetails);
  62467. }
  62468. }
  62469. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62470. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62471. if (mmat) {
  62472. materialFound = true;
  62473. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62474. }
  62475. break;
  62476. }
  62477. }
  62478. }
  62479. if (materialFound === false) {
  62480. loadedMaterialsIds.push(parsedMesh.materialId);
  62481. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62482. if (!mat) {
  62483. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62484. }
  62485. else {
  62486. log += "\n\tMaterial " + mat.toString(fullDetails);
  62487. }
  62488. }
  62489. }
  62490. // Skeleton ?
  62491. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62492. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62493. if (skeletonAlreadyLoaded === false) {
  62494. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62495. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62496. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62497. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62498. skeletons.push(skeleton);
  62499. loadedSkeletonsIds.push(parsedSkeleton.id);
  62500. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62501. }
  62502. }
  62503. }
  62504. }
  62505. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62506. meshes.push(mesh);
  62507. log += "\n\tMesh " + mesh.toString(fullDetails);
  62508. }
  62509. }
  62510. // Connecting parents
  62511. var currentMesh;
  62512. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62513. currentMesh = scene.meshes[index];
  62514. if (currentMesh._waitingParentId) {
  62515. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62516. currentMesh._waitingParentId = null;
  62517. }
  62518. }
  62519. // freeze and compute world matrix application
  62520. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62521. currentMesh = scene.meshes[index];
  62522. if (currentMesh._waitingFreezeWorldMatrix) {
  62523. currentMesh.freezeWorldMatrix();
  62524. currentMesh._waitingFreezeWorldMatrix = null;
  62525. }
  62526. else {
  62527. currentMesh.computeWorldMatrix(true);
  62528. }
  62529. }
  62530. }
  62531. // Particles
  62532. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62533. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62534. var parsedParticleSystem = parsedData.particleSystems[index];
  62535. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62536. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62537. }
  62538. }
  62539. }
  62540. return true;
  62541. }
  62542. catch (err) {
  62543. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62544. if (onError) {
  62545. onError(msg, err);
  62546. }
  62547. else {
  62548. BABYLON.Tools.Log(msg);
  62549. throw err;
  62550. }
  62551. }
  62552. finally {
  62553. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62554. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62555. }
  62556. }
  62557. return false;
  62558. },
  62559. load: function (scene, data, rootUrl, onError) {
  62560. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62561. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62562. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62563. // and avoid problems with multiple concurrent .babylon loads.
  62564. var log = "importScene has failed JSON parse";
  62565. try {
  62566. var parsedData = JSON.parse(data);
  62567. log = "";
  62568. // Scene
  62569. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62570. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62571. }
  62572. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62573. scene.autoClear = parsedData.autoClear;
  62574. }
  62575. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62576. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62577. }
  62578. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62579. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62580. }
  62581. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62582. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62583. }
  62584. // Fog
  62585. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62586. scene.fogMode = parsedData.fogMode;
  62587. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62588. scene.fogStart = parsedData.fogStart;
  62589. scene.fogEnd = parsedData.fogEnd;
  62590. scene.fogDensity = parsedData.fogDensity;
  62591. log += "\tFog mode for scene: ";
  62592. switch (scene.fogMode) {
  62593. // getters not compiling, so using hardcoded
  62594. case 1:
  62595. log += "exp\n";
  62596. break;
  62597. case 2:
  62598. log += "exp2\n";
  62599. break;
  62600. case 3:
  62601. log += "linear\n";
  62602. break;
  62603. }
  62604. }
  62605. //Physics
  62606. if (parsedData.physicsEnabled) {
  62607. var physicsPlugin;
  62608. if (parsedData.physicsEngine === "cannon") {
  62609. physicsPlugin = new BABYLON.CannonJSPlugin();
  62610. }
  62611. else if (parsedData.physicsEngine === "oimo") {
  62612. physicsPlugin = new BABYLON.OimoJSPlugin();
  62613. }
  62614. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62615. //else - default engine, which is currently oimo
  62616. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62617. scene.enablePhysics(physicsGravity, physicsPlugin);
  62618. }
  62619. // Metadata
  62620. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62621. scene.metadata = parsedData.metadata;
  62622. }
  62623. //collisions, if defined. otherwise, default is true
  62624. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62625. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62626. }
  62627. scene.workerCollisions = !!parsedData.workerCollisions;
  62628. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62629. if (!container) {
  62630. return false;
  62631. }
  62632. if (parsedData.autoAnimate) {
  62633. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62634. }
  62635. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62636. scene.setActiveCameraByID(parsedData.activeCameraID);
  62637. }
  62638. // Environment texture
  62639. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62640. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62641. if (parsedData.createDefaultSkybox === true) {
  62642. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62643. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62644. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62645. }
  62646. }
  62647. // Finish
  62648. return true;
  62649. }
  62650. catch (err) {
  62651. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62652. if (onError) {
  62653. onError(msg, err);
  62654. }
  62655. else {
  62656. BABYLON.Tools.Log(msg);
  62657. throw err;
  62658. }
  62659. }
  62660. finally {
  62661. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62662. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62663. }
  62664. }
  62665. return false;
  62666. },
  62667. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62668. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62669. return container;
  62670. }
  62671. });
  62672. })(BABYLON || (BABYLON = {}));
  62673. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62674. var BABYLON;
  62675. (function (BABYLON) {
  62676. var FilesInput = /** @class */ (function () {
  62677. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62678. this.onProcessFileCallback = function () { return true; };
  62679. this._engine = engine;
  62680. this._currentScene = scene;
  62681. this._sceneLoadedCallback = sceneLoadedCallback;
  62682. this._progressCallback = progressCallback;
  62683. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62684. this._textureLoadingCallback = textureLoadingCallback;
  62685. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62686. this._onReloadCallback = onReloadCallback;
  62687. this._errorCallback = errorCallback;
  62688. }
  62689. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62690. var _this = this;
  62691. if (elementToMonitor) {
  62692. this._elementToMonitor = elementToMonitor;
  62693. this._dragEnterHandler = function (e) { _this.drag(e); };
  62694. this._dragOverHandler = function (e) { _this.drag(e); };
  62695. this._dropHandler = function (e) { _this.drop(e); };
  62696. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62697. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62698. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62699. }
  62700. };
  62701. FilesInput.prototype.dispose = function () {
  62702. if (!this._elementToMonitor) {
  62703. return;
  62704. }
  62705. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62706. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62707. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62708. };
  62709. FilesInput.prototype.renderFunction = function () {
  62710. if (this._additionalRenderLoopLogicCallback) {
  62711. this._additionalRenderLoopLogicCallback();
  62712. }
  62713. if (this._currentScene) {
  62714. if (this._textureLoadingCallback) {
  62715. var remaining = this._currentScene.getWaitingItemsCount();
  62716. if (remaining > 0) {
  62717. this._textureLoadingCallback(remaining);
  62718. }
  62719. }
  62720. this._currentScene.render();
  62721. }
  62722. };
  62723. FilesInput.prototype.drag = function (e) {
  62724. e.stopPropagation();
  62725. e.preventDefault();
  62726. };
  62727. FilesInput.prototype.drop = function (eventDrop) {
  62728. eventDrop.stopPropagation();
  62729. eventDrop.preventDefault();
  62730. this.loadFiles(eventDrop);
  62731. };
  62732. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62733. var _this = this;
  62734. var reader = folder.createReader();
  62735. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62736. reader.readEntries(function (entries) {
  62737. remaining.count += entries.length;
  62738. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62739. var entry = entries_1[_i];
  62740. if (entry.isFile) {
  62741. entry.file(function (file) {
  62742. file.correctName = relativePath + file.name;
  62743. files.push(file);
  62744. if (--remaining.count === 0) {
  62745. callback();
  62746. }
  62747. });
  62748. }
  62749. else if (entry.isDirectory) {
  62750. _this._traverseFolder(entry, files, remaining, callback);
  62751. }
  62752. }
  62753. if (--remaining.count) {
  62754. callback();
  62755. }
  62756. });
  62757. };
  62758. FilesInput.prototype._processFiles = function (files) {
  62759. for (var i = 0; i < files.length; i++) {
  62760. var name = files[i].correctName.toLowerCase();
  62761. var extension = name.split('.').pop();
  62762. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62763. continue;
  62764. }
  62765. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62766. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62767. this._sceneFileToLoad = files[i];
  62768. }
  62769. else {
  62770. FilesInput.FilesToLoad[name] = files[i];
  62771. }
  62772. }
  62773. };
  62774. FilesInput.prototype.loadFiles = function (event) {
  62775. var _this = this;
  62776. if (this._startingProcessingFilesCallback)
  62777. this._startingProcessingFilesCallback();
  62778. // Handling data transfer via drag'n'drop
  62779. if (event && event.dataTransfer && event.dataTransfer.files) {
  62780. this._filesToLoad = event.dataTransfer.files;
  62781. }
  62782. // Handling files from input files
  62783. if (event && event.target && event.target.files) {
  62784. this._filesToLoad = event.target.files;
  62785. }
  62786. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62787. var files_1 = new Array();
  62788. var folders = [];
  62789. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62790. for (var i = 0; i < this._filesToLoad.length; i++) {
  62791. var fileToLoad = this._filesToLoad[i];
  62792. var name_1 = fileToLoad.name.toLowerCase();
  62793. var entry = void 0;
  62794. fileToLoad.correctName = name_1;
  62795. if (items) {
  62796. var item = items[i];
  62797. if (item.getAsEntry) {
  62798. entry = item.getAsEntry();
  62799. }
  62800. else if (item.webkitGetAsEntry) {
  62801. entry = item.webkitGetAsEntry();
  62802. }
  62803. }
  62804. if (!entry) {
  62805. files_1.push(fileToLoad);
  62806. }
  62807. else {
  62808. if (entry.isDirectory) {
  62809. folders.push(entry);
  62810. }
  62811. else {
  62812. files_1.push(fileToLoad);
  62813. }
  62814. }
  62815. }
  62816. if (folders.length === 0) {
  62817. this._processFiles(files_1);
  62818. this._processReload();
  62819. }
  62820. else {
  62821. var remaining = { count: folders.length };
  62822. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62823. var folder = folders_1[_i];
  62824. this._traverseFolder(folder, files_1, remaining, function () {
  62825. _this._processFiles(files_1);
  62826. if (remaining.count === 0) {
  62827. _this._processReload();
  62828. }
  62829. });
  62830. }
  62831. }
  62832. }
  62833. };
  62834. FilesInput.prototype._processReload = function () {
  62835. if (this._onReloadCallback) {
  62836. this._onReloadCallback(this._sceneFileToLoad);
  62837. }
  62838. else {
  62839. this.reload();
  62840. }
  62841. };
  62842. FilesInput.prototype.reload = function () {
  62843. var _this = this;
  62844. // If a scene file has been provided
  62845. if (this._sceneFileToLoad) {
  62846. if (this._currentScene) {
  62847. if (BABYLON.Tools.errorsCount > 0) {
  62848. BABYLON.Tools.ClearLogCache();
  62849. }
  62850. this._engine.stopRenderLoop();
  62851. this._currentScene.dispose();
  62852. }
  62853. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62854. if (_this._progressCallback) {
  62855. _this._progressCallback(progress);
  62856. }
  62857. }).then(function (scene) {
  62858. _this._currentScene = scene;
  62859. if (_this._sceneLoadedCallback) {
  62860. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62861. }
  62862. // Wait for textures and shaders to be ready
  62863. _this._currentScene.executeWhenReady(function () {
  62864. _this._engine.runRenderLoop(function () {
  62865. _this.renderFunction();
  62866. });
  62867. });
  62868. }).catch(function (error) {
  62869. if (_this._errorCallback) {
  62870. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62871. }
  62872. });
  62873. }
  62874. else {
  62875. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62876. }
  62877. };
  62878. FilesInput.FilesToLoad = {};
  62879. return FilesInput;
  62880. }());
  62881. BABYLON.FilesInput = FilesInput;
  62882. })(BABYLON || (BABYLON = {}));
  62883. //# sourceMappingURL=babylon.filesInput.js.map
  62884. var BABYLON;
  62885. (function (BABYLON) {
  62886. /**
  62887. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62888. * The underlying implementation relies on an associative array to ensure the best performances.
  62889. * The value can be anything including 'null' but except 'undefined'
  62890. */
  62891. var StringDictionary = /** @class */ (function () {
  62892. function StringDictionary() {
  62893. this._count = 0;
  62894. this._data = {};
  62895. }
  62896. /**
  62897. * This will clear this dictionary and copy the content from the 'source' one.
  62898. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62899. * @param source the dictionary to take the content from and copy to this dictionary
  62900. */
  62901. StringDictionary.prototype.copyFrom = function (source) {
  62902. var _this = this;
  62903. this.clear();
  62904. source.forEach(function (t, v) { return _this.add(t, v); });
  62905. };
  62906. /**
  62907. * Get a value based from its key
  62908. * @param key the given key to get the matching value from
  62909. * @return the value if found, otherwise undefined is returned
  62910. */
  62911. StringDictionary.prototype.get = function (key) {
  62912. var val = this._data[key];
  62913. if (val !== undefined) {
  62914. return val;
  62915. }
  62916. return undefined;
  62917. };
  62918. /**
  62919. * Get a value from its key or add it if it doesn't exist.
  62920. * This method will ensure you that a given key/data will be present in the dictionary.
  62921. * @param key the given key to get the matching value from
  62922. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62923. * The factory will only be invoked if there's no data for the given key.
  62924. * @return the value corresponding to the key.
  62925. */
  62926. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62927. var val = this.get(key);
  62928. if (val !== undefined) {
  62929. return val;
  62930. }
  62931. val = factory(key);
  62932. if (val) {
  62933. this.add(key, val);
  62934. }
  62935. return val;
  62936. };
  62937. /**
  62938. * Get a value from its key if present in the dictionary otherwise add it
  62939. * @param key the key to get the value from
  62940. * @param val if there's no such key/value pair in the dictionary add it with this value
  62941. * @return the value corresponding to the key
  62942. */
  62943. StringDictionary.prototype.getOrAdd = function (key, val) {
  62944. var curVal = this.get(key);
  62945. if (curVal !== undefined) {
  62946. return curVal;
  62947. }
  62948. this.add(key, val);
  62949. return val;
  62950. };
  62951. /**
  62952. * Check if there's a given key in the dictionary
  62953. * @param key the key to check for
  62954. * @return true if the key is present, false otherwise
  62955. */
  62956. StringDictionary.prototype.contains = function (key) {
  62957. return this._data[key] !== undefined;
  62958. };
  62959. /**
  62960. * Add a new key and its corresponding value
  62961. * @param key the key to add
  62962. * @param value the value corresponding to the key
  62963. * @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
  62964. */
  62965. StringDictionary.prototype.add = function (key, value) {
  62966. if (this._data[key] !== undefined) {
  62967. return false;
  62968. }
  62969. this._data[key] = value;
  62970. ++this._count;
  62971. return true;
  62972. };
  62973. StringDictionary.prototype.set = function (key, value) {
  62974. if (this._data[key] === undefined) {
  62975. return false;
  62976. }
  62977. this._data[key] = value;
  62978. return true;
  62979. };
  62980. /**
  62981. * Get the element of the given key and remove it from the dictionary
  62982. * @param key
  62983. */
  62984. StringDictionary.prototype.getAndRemove = function (key) {
  62985. var val = this.get(key);
  62986. if (val !== undefined) {
  62987. delete this._data[key];
  62988. --this._count;
  62989. return val;
  62990. }
  62991. return null;
  62992. };
  62993. /**
  62994. * Remove a key/value from the dictionary.
  62995. * @param key the key to remove
  62996. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62997. */
  62998. StringDictionary.prototype.remove = function (key) {
  62999. if (this.contains(key)) {
  63000. delete this._data[key];
  63001. --this._count;
  63002. return true;
  63003. }
  63004. return false;
  63005. };
  63006. /**
  63007. * Clear the whole content of the dictionary
  63008. */
  63009. StringDictionary.prototype.clear = function () {
  63010. this._data = {};
  63011. this._count = 0;
  63012. };
  63013. Object.defineProperty(StringDictionary.prototype, "count", {
  63014. get: function () {
  63015. return this._count;
  63016. },
  63017. enumerable: true,
  63018. configurable: true
  63019. });
  63020. /**
  63021. * Execute a callback on each key/val of the dictionary.
  63022. * Note that you can remove any element in this dictionary in the callback implementation
  63023. * @param callback the callback to execute on a given key/value pair
  63024. */
  63025. StringDictionary.prototype.forEach = function (callback) {
  63026. for (var cur in this._data) {
  63027. var val = this._data[cur];
  63028. callback(cur, val);
  63029. }
  63030. };
  63031. /**
  63032. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63033. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63034. * Note that you can remove any element in this dictionary in the callback implementation
  63035. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63036. */
  63037. StringDictionary.prototype.first = function (callback) {
  63038. for (var cur in this._data) {
  63039. var val = this._data[cur];
  63040. var res = callback(cur, val);
  63041. if (res) {
  63042. return res;
  63043. }
  63044. }
  63045. return null;
  63046. };
  63047. return StringDictionary;
  63048. }());
  63049. BABYLON.StringDictionary = StringDictionary;
  63050. })(BABYLON || (BABYLON = {}));
  63051. //# sourceMappingURL=babylon.stringDictionary.js.map
  63052. var BABYLON;
  63053. (function (BABYLON) {
  63054. var Tags = /** @class */ (function () {
  63055. function Tags() {
  63056. }
  63057. Tags.EnableFor = function (obj) {
  63058. obj._tags = obj._tags || {};
  63059. obj.hasTags = function () {
  63060. return Tags.HasTags(obj);
  63061. };
  63062. obj.addTags = function (tagsString) {
  63063. return Tags.AddTagsTo(obj, tagsString);
  63064. };
  63065. obj.removeTags = function (tagsString) {
  63066. return Tags.RemoveTagsFrom(obj, tagsString);
  63067. };
  63068. obj.matchesTagsQuery = function (tagsQuery) {
  63069. return Tags.MatchesQuery(obj, tagsQuery);
  63070. };
  63071. };
  63072. Tags.DisableFor = function (obj) {
  63073. delete obj._tags;
  63074. delete obj.hasTags;
  63075. delete obj.addTags;
  63076. delete obj.removeTags;
  63077. delete obj.matchesTagsQuery;
  63078. };
  63079. Tags.HasTags = function (obj) {
  63080. if (!obj._tags) {
  63081. return false;
  63082. }
  63083. return !BABYLON.Tools.IsEmpty(obj._tags);
  63084. };
  63085. Tags.GetTags = function (obj, asString) {
  63086. if (asString === void 0) { asString = true; }
  63087. if (!obj._tags) {
  63088. return null;
  63089. }
  63090. if (asString) {
  63091. var tagsArray = [];
  63092. for (var tag in obj._tags) {
  63093. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63094. tagsArray.push(tag);
  63095. }
  63096. }
  63097. return tagsArray.join(" ");
  63098. }
  63099. else {
  63100. return obj._tags;
  63101. }
  63102. };
  63103. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63104. // a tag cannot start with '||', '&&', and '!'
  63105. // it cannot contain whitespaces
  63106. Tags.AddTagsTo = function (obj, tagsString) {
  63107. if (!tagsString) {
  63108. return;
  63109. }
  63110. if (typeof tagsString !== "string") {
  63111. return;
  63112. }
  63113. var tags = tagsString.split(" ");
  63114. tags.forEach(function (tag, index, array) {
  63115. Tags._AddTagTo(obj, tag);
  63116. });
  63117. };
  63118. Tags._AddTagTo = function (obj, tag) {
  63119. tag = tag.trim();
  63120. if (tag === "" || tag === "true" || tag === "false") {
  63121. return;
  63122. }
  63123. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63124. return;
  63125. }
  63126. Tags.EnableFor(obj);
  63127. obj._tags[tag] = true;
  63128. };
  63129. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63130. if (!Tags.HasTags(obj)) {
  63131. return;
  63132. }
  63133. var tags = tagsString.split(" ");
  63134. for (var t in tags) {
  63135. Tags._RemoveTagFrom(obj, tags[t]);
  63136. }
  63137. };
  63138. Tags._RemoveTagFrom = function (obj, tag) {
  63139. delete obj._tags[tag];
  63140. };
  63141. Tags.MatchesQuery = function (obj, tagsQuery) {
  63142. if (tagsQuery === undefined) {
  63143. return true;
  63144. }
  63145. if (tagsQuery === "") {
  63146. return Tags.HasTags(obj);
  63147. }
  63148. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63149. };
  63150. return Tags;
  63151. }());
  63152. BABYLON.Tags = Tags;
  63153. })(BABYLON || (BABYLON = {}));
  63154. //# sourceMappingURL=babylon.tags.js.map
  63155. var BABYLON;
  63156. (function (BABYLON) {
  63157. var AndOrNotEvaluator = /** @class */ (function () {
  63158. function AndOrNotEvaluator() {
  63159. }
  63160. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63161. if (!query.match(/\([^\(\)]*\)/g)) {
  63162. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63163. }
  63164. else {
  63165. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63166. // remove parenthesis
  63167. r = r.slice(1, r.length - 1);
  63168. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63169. });
  63170. }
  63171. if (query === "true") {
  63172. return true;
  63173. }
  63174. if (query === "false") {
  63175. return false;
  63176. }
  63177. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63178. };
  63179. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63180. evaluateCallback = evaluateCallback || (function (r) {
  63181. return r === "true" ? true : false;
  63182. });
  63183. var result;
  63184. var or = parenthesisContent.split("||");
  63185. for (var i in or) {
  63186. if (or.hasOwnProperty(i)) {
  63187. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63188. var and = ori.split("&&");
  63189. if (and.length > 1) {
  63190. for (var j = 0; j < and.length; ++j) {
  63191. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63192. if (andj !== "true" && andj !== "false") {
  63193. if (andj[0] === "!") {
  63194. result = !evaluateCallback(andj.substring(1));
  63195. }
  63196. else {
  63197. result = evaluateCallback(andj);
  63198. }
  63199. }
  63200. else {
  63201. result = andj === "true" ? true : false;
  63202. }
  63203. if (!result) {
  63204. ori = "false";
  63205. break;
  63206. }
  63207. }
  63208. }
  63209. if (result || ori === "true") {
  63210. result = true;
  63211. break;
  63212. }
  63213. // result equals false (or undefined)
  63214. if (ori !== "true" && ori !== "false") {
  63215. if (ori[0] === "!") {
  63216. result = !evaluateCallback(ori.substring(1));
  63217. }
  63218. else {
  63219. result = evaluateCallback(ori);
  63220. }
  63221. }
  63222. else {
  63223. result = ori === "true" ? true : false;
  63224. }
  63225. }
  63226. }
  63227. // the whole parenthesis scope is replaced by 'true' or 'false'
  63228. return result ? "true" : "false";
  63229. };
  63230. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63231. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63232. // remove whitespaces
  63233. r = r.replace(/[\s]/g, function () { return ""; });
  63234. return r.length % 2 ? "!" : "";
  63235. });
  63236. booleanString = booleanString.trim();
  63237. if (booleanString === "!true") {
  63238. booleanString = "false";
  63239. }
  63240. else if (booleanString === "!false") {
  63241. booleanString = "true";
  63242. }
  63243. return booleanString;
  63244. };
  63245. return AndOrNotEvaluator;
  63246. }());
  63247. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63248. })(BABYLON || (BABYLON = {}));
  63249. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63250. var BABYLON;
  63251. (function (BABYLON) {
  63252. var Database = /** @class */ (function () {
  63253. function Database(urlToScene, callbackManifestChecked) {
  63254. // Handling various flavors of prefixed version of IndexedDB
  63255. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63256. this.callbackManifestChecked = callbackManifestChecked;
  63257. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63258. this.db = null;
  63259. this._enableSceneOffline = false;
  63260. this._enableTexturesOffline = false;
  63261. this.manifestVersionFound = 0;
  63262. this.mustUpdateRessources = false;
  63263. this.hasReachedQuota = false;
  63264. if (!Database.IDBStorageEnabled) {
  63265. this.callbackManifestChecked(true);
  63266. }
  63267. else {
  63268. this.checkManifestFile();
  63269. }
  63270. }
  63271. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63272. get: function () {
  63273. return this._enableSceneOffline;
  63274. },
  63275. enumerable: true,
  63276. configurable: true
  63277. });
  63278. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63279. get: function () {
  63280. return this._enableTexturesOffline;
  63281. },
  63282. enumerable: true,
  63283. configurable: true
  63284. });
  63285. Database.prototype.checkManifestFile = function () {
  63286. var _this = this;
  63287. var noManifestFile = function () {
  63288. _this._enableSceneOffline = false;
  63289. _this._enableTexturesOffline = false;
  63290. _this.callbackManifestChecked(false);
  63291. };
  63292. var timeStampUsed = false;
  63293. var manifestURL = this.currentSceneUrl + ".manifest";
  63294. var xhr = new XMLHttpRequest();
  63295. if (navigator.onLine) {
  63296. // Adding a timestamp to by-pass browsers' cache
  63297. timeStampUsed = true;
  63298. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63299. }
  63300. xhr.open("GET", manifestURL, true);
  63301. xhr.addEventListener("load", function () {
  63302. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63303. try {
  63304. var manifestFile = JSON.parse(xhr.response);
  63305. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63306. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63307. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63308. _this.manifestVersionFound = manifestFile.version;
  63309. }
  63310. if (_this.callbackManifestChecked) {
  63311. _this.callbackManifestChecked(true);
  63312. }
  63313. }
  63314. catch (ex) {
  63315. noManifestFile();
  63316. }
  63317. }
  63318. else {
  63319. noManifestFile();
  63320. }
  63321. }, false);
  63322. xhr.addEventListener("error", function (event) {
  63323. if (timeStampUsed) {
  63324. timeStampUsed = false;
  63325. // Let's retry without the timeStamp
  63326. // It could fail when coupled with HTML5 Offline API
  63327. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63328. xhr.open("GET", retryManifestURL, true);
  63329. xhr.send();
  63330. }
  63331. else {
  63332. noManifestFile();
  63333. }
  63334. }, false);
  63335. try {
  63336. xhr.send();
  63337. }
  63338. catch (ex) {
  63339. BABYLON.Tools.Error("Error on XHR send request.");
  63340. this.callbackManifestChecked(false);
  63341. }
  63342. };
  63343. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63344. var _this = this;
  63345. var handleError = function () {
  63346. _this.isSupported = false;
  63347. if (errorCallback)
  63348. errorCallback();
  63349. };
  63350. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63351. // Your browser doesn't support IndexedDB
  63352. this.isSupported = false;
  63353. if (errorCallback)
  63354. errorCallback();
  63355. }
  63356. else {
  63357. // If the DB hasn't been opened or created yet
  63358. if (!this.db) {
  63359. this.hasReachedQuota = false;
  63360. this.isSupported = true;
  63361. var request = this.idbFactory.open("babylonjs", 1);
  63362. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63363. request.onerror = function (event) {
  63364. handleError();
  63365. };
  63366. // executes when a version change transaction cannot complete due to other active transactions
  63367. request.onblocked = function (event) {
  63368. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63369. handleError();
  63370. };
  63371. // DB has been opened successfully
  63372. request.onsuccess = function (event) {
  63373. _this.db = request.result;
  63374. successCallback();
  63375. };
  63376. // Initialization of the DB. Creating Scenes & Textures stores
  63377. request.onupgradeneeded = function (event) {
  63378. _this.db = (event.target).result;
  63379. if (_this.db) {
  63380. try {
  63381. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63382. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63383. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63384. }
  63385. catch (ex) {
  63386. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63387. handleError();
  63388. }
  63389. }
  63390. };
  63391. }
  63392. else {
  63393. if (successCallback)
  63394. successCallback();
  63395. }
  63396. }
  63397. };
  63398. Database.prototype.loadImageFromDB = function (url, image) {
  63399. var _this = this;
  63400. var completeURL = Database.ReturnFullUrlLocation(url);
  63401. var saveAndLoadImage = function () {
  63402. if (!_this.hasReachedQuota && _this.db !== null) {
  63403. // the texture is not yet in the DB, let's try to save it
  63404. _this._saveImageIntoDBAsync(completeURL, image);
  63405. }
  63406. else {
  63407. image.src = url;
  63408. }
  63409. };
  63410. if (!this.mustUpdateRessources) {
  63411. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63412. }
  63413. else {
  63414. saveAndLoadImage();
  63415. }
  63416. };
  63417. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63418. if (this.isSupported && this.db !== null) {
  63419. var texture;
  63420. var transaction = this.db.transaction(["textures"]);
  63421. transaction.onabort = function (event) {
  63422. image.src = url;
  63423. };
  63424. transaction.oncomplete = function (event) {
  63425. var blobTextureURL;
  63426. if (texture) {
  63427. var URL = window.URL || window.webkitURL;
  63428. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63429. image.onerror = function () {
  63430. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63431. image.src = url;
  63432. };
  63433. image.src = blobTextureURL;
  63434. }
  63435. else {
  63436. notInDBCallback();
  63437. }
  63438. };
  63439. var getRequest = transaction.objectStore("textures").get(url);
  63440. getRequest.onsuccess = function (event) {
  63441. texture = (event.target).result;
  63442. };
  63443. getRequest.onerror = function (event) {
  63444. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63445. image.src = url;
  63446. };
  63447. }
  63448. else {
  63449. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63450. image.src = url;
  63451. }
  63452. };
  63453. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63454. var _this = this;
  63455. if (this.isSupported) {
  63456. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63457. var generateBlobUrl = function () {
  63458. var blobTextureURL;
  63459. if (blob) {
  63460. var URL = window.URL || window.webkitURL;
  63461. try {
  63462. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63463. }
  63464. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63465. catch (ex) {
  63466. blobTextureURL = URL.createObjectURL(blob);
  63467. }
  63468. }
  63469. if (blobTextureURL) {
  63470. image.src = blobTextureURL;
  63471. }
  63472. };
  63473. if (Database.IsUASupportingBlobStorage) {
  63474. var xhr = new XMLHttpRequest(), blob;
  63475. xhr.open("GET", url, true);
  63476. xhr.responseType = "blob";
  63477. xhr.addEventListener("load", function () {
  63478. if (xhr.status === 200 && _this.db) {
  63479. // Blob as response (XHR2)
  63480. blob = xhr.response;
  63481. var transaction = _this.db.transaction(["textures"], "readwrite");
  63482. // the transaction could abort because of a QuotaExceededError error
  63483. transaction.onabort = function (event) {
  63484. try {
  63485. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63486. var srcElement = (event.srcElement || event.target);
  63487. var error = srcElement.error;
  63488. if (error && error.name === "QuotaExceededError") {
  63489. _this.hasReachedQuota = true;
  63490. }
  63491. }
  63492. catch (ex) { }
  63493. generateBlobUrl();
  63494. };
  63495. transaction.oncomplete = function (event) {
  63496. generateBlobUrl();
  63497. };
  63498. var newTexture = { textureUrl: url, data: blob };
  63499. try {
  63500. // Put the blob into the dabase
  63501. var addRequest = transaction.objectStore("textures").put(newTexture);
  63502. addRequest.onsuccess = function (event) {
  63503. };
  63504. addRequest.onerror = function (event) {
  63505. generateBlobUrl();
  63506. };
  63507. }
  63508. catch (ex) {
  63509. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63510. if (ex.code === 25) {
  63511. Database.IsUASupportingBlobStorage = false;
  63512. }
  63513. image.src = url;
  63514. }
  63515. }
  63516. else {
  63517. image.src = url;
  63518. }
  63519. }, false);
  63520. xhr.addEventListener("error", function (event) {
  63521. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63522. image.src = url;
  63523. }, false);
  63524. xhr.send();
  63525. }
  63526. else {
  63527. image.src = url;
  63528. }
  63529. }
  63530. else {
  63531. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63532. image.src = url;
  63533. }
  63534. };
  63535. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63536. var _this = this;
  63537. var updateVersion = function () {
  63538. // the version is not yet in the DB or we need to update it
  63539. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63540. };
  63541. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63542. };
  63543. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63544. var _this = this;
  63545. if (this.isSupported && this.db) {
  63546. var version;
  63547. try {
  63548. var transaction = this.db.transaction(["versions"]);
  63549. transaction.oncomplete = function (event) {
  63550. if (version) {
  63551. // If the version in the JSON file is > than the version in DB
  63552. if (_this.manifestVersionFound > version.data) {
  63553. _this.mustUpdateRessources = true;
  63554. updateInDBCallback();
  63555. }
  63556. else {
  63557. callback(version.data);
  63558. }
  63559. }
  63560. else {
  63561. _this.mustUpdateRessources = true;
  63562. updateInDBCallback();
  63563. }
  63564. };
  63565. transaction.onabort = function (event) {
  63566. callback(-1);
  63567. };
  63568. var getRequest = transaction.objectStore("versions").get(url);
  63569. getRequest.onsuccess = function (event) {
  63570. version = (event.target).result;
  63571. };
  63572. getRequest.onerror = function (event) {
  63573. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63574. callback(-1);
  63575. };
  63576. }
  63577. catch (ex) {
  63578. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63579. callback(-1);
  63580. }
  63581. }
  63582. else {
  63583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63584. callback(-1);
  63585. }
  63586. };
  63587. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63588. var _this = this;
  63589. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63590. try {
  63591. // Open a transaction to the database
  63592. var transaction = this.db.transaction(["versions"], "readwrite");
  63593. // the transaction could abort because of a QuotaExceededError error
  63594. transaction.onabort = function (event) {
  63595. try {
  63596. var error = event.srcElement['error'];
  63597. if (error && error.name === "QuotaExceededError") {
  63598. _this.hasReachedQuota = true;
  63599. }
  63600. }
  63601. catch (ex) { }
  63602. callback(-1);
  63603. };
  63604. transaction.oncomplete = function (event) {
  63605. callback(_this.manifestVersionFound);
  63606. };
  63607. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63608. // Put the scene into the database
  63609. var addRequest = transaction.objectStore("versions").put(newVersion);
  63610. addRequest.onsuccess = function (event) {
  63611. };
  63612. addRequest.onerror = function (event) {
  63613. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63614. };
  63615. }
  63616. catch (ex) {
  63617. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63618. callback(-1);
  63619. }
  63620. }
  63621. else {
  63622. callback(-1);
  63623. }
  63624. };
  63625. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63626. var _this = this;
  63627. var completeUrl = Database.ReturnFullUrlLocation(url);
  63628. var saveAndLoadFile = function () {
  63629. // the scene is not yet in the DB, let's try to save it
  63630. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63631. };
  63632. this._checkVersionFromDB(completeUrl, function (version) {
  63633. if (version !== -1) {
  63634. if (!_this.mustUpdateRessources) {
  63635. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63636. }
  63637. else {
  63638. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63639. }
  63640. }
  63641. else {
  63642. if (errorCallback) {
  63643. errorCallback();
  63644. }
  63645. }
  63646. });
  63647. };
  63648. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63649. if (this.isSupported && this.db) {
  63650. var targetStore;
  63651. if (url.indexOf(".babylon") !== -1) {
  63652. targetStore = "scenes";
  63653. }
  63654. else {
  63655. targetStore = "textures";
  63656. }
  63657. var file;
  63658. var transaction = this.db.transaction([targetStore]);
  63659. transaction.oncomplete = function (event) {
  63660. if (file) {
  63661. callback(file.data);
  63662. }
  63663. else {
  63664. notInDBCallback();
  63665. }
  63666. };
  63667. transaction.onabort = function (event) {
  63668. notInDBCallback();
  63669. };
  63670. var getRequest = transaction.objectStore(targetStore).get(url);
  63671. getRequest.onsuccess = function (event) {
  63672. file = (event.target).result;
  63673. };
  63674. getRequest.onerror = function (event) {
  63675. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63676. notInDBCallback();
  63677. };
  63678. }
  63679. else {
  63680. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63681. callback();
  63682. }
  63683. };
  63684. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63685. var _this = this;
  63686. if (this.isSupported) {
  63687. var targetStore;
  63688. if (url.indexOf(".babylon") !== -1) {
  63689. targetStore = "scenes";
  63690. }
  63691. else {
  63692. targetStore = "textures";
  63693. }
  63694. // Create XHR
  63695. var xhr = new XMLHttpRequest();
  63696. var fileData;
  63697. xhr.open("GET", url, true);
  63698. if (useArrayBuffer) {
  63699. xhr.responseType = "arraybuffer";
  63700. }
  63701. if (progressCallback) {
  63702. xhr.onprogress = progressCallback;
  63703. }
  63704. xhr.addEventListener("load", function () {
  63705. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63706. // Blob as response (XHR2)
  63707. //fileData = xhr.responseText;
  63708. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63709. if (!_this.hasReachedQuota && _this.db) {
  63710. // Open a transaction to the database
  63711. var transaction = _this.db.transaction([targetStore], "readwrite");
  63712. // the transaction could abort because of a QuotaExceededError error
  63713. transaction.onabort = function (event) {
  63714. try {
  63715. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63716. var error = event.srcElement['error'];
  63717. if (error && error.name === "QuotaExceededError") {
  63718. _this.hasReachedQuota = true;
  63719. }
  63720. }
  63721. catch (ex) { }
  63722. callback(fileData);
  63723. };
  63724. transaction.oncomplete = function (event) {
  63725. callback(fileData);
  63726. };
  63727. var newFile;
  63728. if (targetStore === "scenes") {
  63729. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63730. }
  63731. else {
  63732. newFile = { textureUrl: url, data: fileData };
  63733. }
  63734. try {
  63735. // Put the scene into the database
  63736. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63737. addRequest.onsuccess = function (event) {
  63738. };
  63739. addRequest.onerror = function (event) {
  63740. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63741. };
  63742. }
  63743. catch (ex) {
  63744. callback(fileData);
  63745. }
  63746. }
  63747. else {
  63748. callback(fileData);
  63749. }
  63750. }
  63751. else {
  63752. callback();
  63753. }
  63754. }, false);
  63755. xhr.addEventListener("error", function (event) {
  63756. BABYLON.Tools.Error("error on XHR request.");
  63757. callback();
  63758. }, false);
  63759. xhr.send();
  63760. }
  63761. else {
  63762. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63763. callback();
  63764. }
  63765. };
  63766. Database.IsUASupportingBlobStorage = true;
  63767. Database.IDBStorageEnabled = true;
  63768. Database.parseURL = function (url) {
  63769. var a = document.createElement('a');
  63770. a.href = url;
  63771. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63772. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63773. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63774. return absLocation;
  63775. };
  63776. Database.ReturnFullUrlLocation = function (url) {
  63777. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63778. return (Database.parseURL(window.location.href) + url);
  63779. }
  63780. else {
  63781. return url;
  63782. }
  63783. };
  63784. return Database;
  63785. }());
  63786. BABYLON.Database = Database;
  63787. })(BABYLON || (BABYLON = {}));
  63788. //# sourceMappingURL=babylon.database.js.map
  63789. var BABYLON;
  63790. (function (BABYLON) {
  63791. var FresnelParameters = /** @class */ (function () {
  63792. function FresnelParameters() {
  63793. this._isEnabled = true;
  63794. this.leftColor = BABYLON.Color3.White();
  63795. this.rightColor = BABYLON.Color3.Black();
  63796. this.bias = 0;
  63797. this.power = 1;
  63798. }
  63799. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63800. get: function () {
  63801. return this._isEnabled;
  63802. },
  63803. set: function (value) {
  63804. if (this._isEnabled === value) {
  63805. return;
  63806. }
  63807. this._isEnabled = value;
  63808. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63809. },
  63810. enumerable: true,
  63811. configurable: true
  63812. });
  63813. FresnelParameters.prototype.clone = function () {
  63814. var newFresnelParameters = new FresnelParameters();
  63815. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63816. return newFresnelParameters;
  63817. };
  63818. FresnelParameters.prototype.serialize = function () {
  63819. var serializationObject = {};
  63820. serializationObject.isEnabled = this.isEnabled;
  63821. serializationObject.leftColor = this.leftColor;
  63822. serializationObject.rightColor = this.rightColor;
  63823. serializationObject.bias = this.bias;
  63824. serializationObject.power = this.power;
  63825. return serializationObject;
  63826. };
  63827. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63828. var fresnelParameters = new FresnelParameters();
  63829. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63830. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63831. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63832. fresnelParameters.bias = parsedFresnelParameters.bias;
  63833. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63834. return fresnelParameters;
  63835. };
  63836. return FresnelParameters;
  63837. }());
  63838. BABYLON.FresnelParameters = FresnelParameters;
  63839. })(BABYLON || (BABYLON = {}));
  63840. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63841. var BABYLON;
  63842. (function (BABYLON) {
  63843. var MultiMaterial = /** @class */ (function (_super) {
  63844. __extends(MultiMaterial, _super);
  63845. function MultiMaterial(name, scene) {
  63846. var _this = _super.call(this, name, scene, true) || this;
  63847. scene.multiMaterials.push(_this);
  63848. _this.subMaterials = new Array();
  63849. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63850. return _this;
  63851. }
  63852. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63853. get: function () {
  63854. return this._subMaterials;
  63855. },
  63856. set: function (value) {
  63857. this._subMaterials = value;
  63858. this._hookArray(value);
  63859. },
  63860. enumerable: true,
  63861. configurable: true
  63862. });
  63863. MultiMaterial.prototype._hookArray = function (array) {
  63864. var _this = this;
  63865. var oldPush = array.push;
  63866. array.push = function () {
  63867. var items = [];
  63868. for (var _i = 0; _i < arguments.length; _i++) {
  63869. items[_i] = arguments[_i];
  63870. }
  63871. var result = oldPush.apply(array, items);
  63872. _this._markAllSubMeshesAsTexturesDirty();
  63873. return result;
  63874. };
  63875. var oldSplice = array.splice;
  63876. array.splice = function (index, deleteCount) {
  63877. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63878. _this._markAllSubMeshesAsTexturesDirty();
  63879. return deleted;
  63880. };
  63881. };
  63882. // Properties
  63883. MultiMaterial.prototype.getSubMaterial = function (index) {
  63884. if (index < 0 || index >= this.subMaterials.length) {
  63885. return this.getScene().defaultMaterial;
  63886. }
  63887. return this.subMaterials[index];
  63888. };
  63889. MultiMaterial.prototype.getActiveTextures = function () {
  63890. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63891. if (subMaterial) {
  63892. return subMaterial.getActiveTextures();
  63893. }
  63894. else {
  63895. return [];
  63896. }
  63897. }));
  63898. var _a;
  63899. };
  63900. // Methods
  63901. MultiMaterial.prototype.getClassName = function () {
  63902. return "MultiMaterial";
  63903. };
  63904. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63905. for (var index = 0; index < this.subMaterials.length; index++) {
  63906. var subMaterial = this.subMaterials[index];
  63907. if (subMaterial) {
  63908. if (subMaterial.storeEffectOnSubMeshes) {
  63909. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63910. return false;
  63911. }
  63912. continue;
  63913. }
  63914. if (!subMaterial.isReady(mesh)) {
  63915. return false;
  63916. }
  63917. }
  63918. }
  63919. return true;
  63920. };
  63921. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63922. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63923. for (var index = 0; index < this.subMaterials.length; index++) {
  63924. var subMaterial = null;
  63925. var current = this.subMaterials[index];
  63926. if (cloneChildren && current) {
  63927. subMaterial = current.clone(name + "-" + current.name);
  63928. }
  63929. else {
  63930. subMaterial = this.subMaterials[index];
  63931. }
  63932. newMultiMaterial.subMaterials.push(subMaterial);
  63933. }
  63934. return newMultiMaterial;
  63935. };
  63936. MultiMaterial.prototype.serialize = function () {
  63937. var serializationObject = {};
  63938. serializationObject.name = this.name;
  63939. serializationObject.id = this.id;
  63940. if (BABYLON.Tags) {
  63941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63942. }
  63943. serializationObject.materials = [];
  63944. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63945. var subMat = this.subMaterials[matIndex];
  63946. if (subMat) {
  63947. serializationObject.materials.push(subMat.id);
  63948. }
  63949. else {
  63950. serializationObject.materials.push(null);
  63951. }
  63952. }
  63953. return serializationObject;
  63954. };
  63955. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63956. var scene = this.getScene();
  63957. if (!scene) {
  63958. return;
  63959. }
  63960. var index = scene.multiMaterials.indexOf(this);
  63961. if (index >= 0) {
  63962. scene.multiMaterials.splice(index, 1);
  63963. }
  63964. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63965. };
  63966. return MultiMaterial;
  63967. }(BABYLON.Material));
  63968. BABYLON.MultiMaterial = MultiMaterial;
  63969. })(BABYLON || (BABYLON = {}));
  63970. //# sourceMappingURL=babylon.multiMaterial.js.map
  63971. var BABYLON;
  63972. (function (BABYLON) {
  63973. var FreeCameraTouchInput = /** @class */ (function () {
  63974. function FreeCameraTouchInput() {
  63975. this._offsetX = null;
  63976. this._offsetY = null;
  63977. this._pointerPressed = new Array();
  63978. this.touchAngularSensibility = 200000.0;
  63979. this.touchMoveSensibility = 250.0;
  63980. }
  63981. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63982. var _this = this;
  63983. var previousPosition = null;
  63984. if (this._pointerInput === undefined) {
  63985. this._onLostFocus = function (evt) {
  63986. _this._offsetX = null;
  63987. _this._offsetY = null;
  63988. };
  63989. this._pointerInput = function (p, s) {
  63990. var evt = p.event;
  63991. if (evt.pointerType === "mouse") {
  63992. return;
  63993. }
  63994. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63995. if (!noPreventDefault) {
  63996. evt.preventDefault();
  63997. }
  63998. _this._pointerPressed.push(evt.pointerId);
  63999. if (_this._pointerPressed.length !== 1) {
  64000. return;
  64001. }
  64002. previousPosition = {
  64003. x: evt.clientX,
  64004. y: evt.clientY
  64005. };
  64006. }
  64007. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64008. if (!noPreventDefault) {
  64009. evt.preventDefault();
  64010. }
  64011. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64012. if (index === -1) {
  64013. return;
  64014. }
  64015. _this._pointerPressed.splice(index, 1);
  64016. if (index != 0) {
  64017. return;
  64018. }
  64019. previousPosition = null;
  64020. _this._offsetX = null;
  64021. _this._offsetY = null;
  64022. }
  64023. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64024. if (!noPreventDefault) {
  64025. evt.preventDefault();
  64026. }
  64027. if (!previousPosition) {
  64028. return;
  64029. }
  64030. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64031. if (index != 0) {
  64032. return;
  64033. }
  64034. _this._offsetX = evt.clientX - previousPosition.x;
  64035. _this._offsetY = -(evt.clientY - previousPosition.y);
  64036. }
  64037. };
  64038. }
  64039. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64040. if (this._onLostFocus) {
  64041. element.addEventListener("blur", this._onLostFocus);
  64042. }
  64043. };
  64044. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64045. if (this._pointerInput && element) {
  64046. if (this._observer) {
  64047. this.camera.getScene().onPointerObservable.remove(this._observer);
  64048. this._observer = null;
  64049. }
  64050. if (this._onLostFocus) {
  64051. element.removeEventListener("blur", this._onLostFocus);
  64052. this._onLostFocus = null;
  64053. }
  64054. this._pointerPressed = [];
  64055. this._offsetX = null;
  64056. this._offsetY = null;
  64057. }
  64058. };
  64059. FreeCameraTouchInput.prototype.checkInputs = function () {
  64060. if (this._offsetX && this._offsetY) {
  64061. var camera = this.camera;
  64062. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64063. if (this._pointerPressed.length > 1) {
  64064. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64065. }
  64066. else {
  64067. var speed = camera._computeLocalCameraSpeed();
  64068. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64069. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64070. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64071. }
  64072. }
  64073. };
  64074. FreeCameraTouchInput.prototype.getClassName = function () {
  64075. return "FreeCameraTouchInput";
  64076. };
  64077. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64078. return "touch";
  64079. };
  64080. __decorate([
  64081. BABYLON.serialize()
  64082. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64083. __decorate([
  64084. BABYLON.serialize()
  64085. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64086. return FreeCameraTouchInput;
  64087. }());
  64088. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64089. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64090. })(BABYLON || (BABYLON = {}));
  64091. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64092. var BABYLON;
  64093. (function (BABYLON) {
  64094. // We're mainly based on the logic defined into the FreeCamera code
  64095. var TouchCamera = /** @class */ (function (_super) {
  64096. __extends(TouchCamera, _super);
  64097. //-- end properties for backward compatibility for inputs
  64098. function TouchCamera(name, position, scene) {
  64099. var _this = _super.call(this, name, position, scene) || this;
  64100. _this.inputs.addTouch();
  64101. _this._setupInputs();
  64102. return _this;
  64103. }
  64104. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64105. //-- Begin properties for backward compatibility for inputs
  64106. get: function () {
  64107. var touch = this.inputs.attached["touch"];
  64108. if (touch)
  64109. return touch.touchAngularSensibility;
  64110. return 0;
  64111. },
  64112. set: function (value) {
  64113. var touch = this.inputs.attached["touch"];
  64114. if (touch)
  64115. touch.touchAngularSensibility = value;
  64116. },
  64117. enumerable: true,
  64118. configurable: true
  64119. });
  64120. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64121. get: function () {
  64122. var touch = this.inputs.attached["touch"];
  64123. if (touch)
  64124. return touch.touchMoveSensibility;
  64125. return 0;
  64126. },
  64127. set: function (value) {
  64128. var touch = this.inputs.attached["touch"];
  64129. if (touch)
  64130. touch.touchMoveSensibility = value;
  64131. },
  64132. enumerable: true,
  64133. configurable: true
  64134. });
  64135. TouchCamera.prototype.getClassName = function () {
  64136. return "TouchCamera";
  64137. };
  64138. TouchCamera.prototype._setupInputs = function () {
  64139. var mouse = this.inputs.attached["mouse"];
  64140. if (mouse) {
  64141. mouse.touchEnabled = false;
  64142. }
  64143. };
  64144. return TouchCamera;
  64145. }(BABYLON.FreeCamera));
  64146. BABYLON.TouchCamera = TouchCamera;
  64147. })(BABYLON || (BABYLON = {}));
  64148. //# sourceMappingURL=babylon.touchCamera.js.map
  64149. var BABYLON;
  64150. (function (BABYLON) {
  64151. var ProceduralTexture = /** @class */ (function (_super) {
  64152. __extends(ProceduralTexture, _super);
  64153. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64154. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64155. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64156. if (isCube === void 0) { isCube = false; }
  64157. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64158. _this.isCube = isCube;
  64159. _this.isEnabled = true;
  64160. _this._currentRefreshId = -1;
  64161. _this._refreshRate = 1;
  64162. _this._vertexBuffers = {};
  64163. _this._uniforms = new Array();
  64164. _this._samplers = new Array();
  64165. _this._textures = {};
  64166. _this._floats = {};
  64167. _this._floatsArrays = {};
  64168. _this._colors3 = {};
  64169. _this._colors4 = {};
  64170. _this._vectors2 = {};
  64171. _this._vectors3 = {};
  64172. _this._matrices = {};
  64173. _this._fallbackTextureUsed = false;
  64174. scene._proceduralTextures.push(_this);
  64175. _this._engine = scene.getEngine();
  64176. _this.name = name;
  64177. _this.isRenderTarget = true;
  64178. _this._size = size;
  64179. _this._generateMipMaps = generateMipMaps;
  64180. _this.setFragment(fragment);
  64181. _this._fallbackTexture = fallbackTexture;
  64182. if (isCube) {
  64183. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64184. _this.setFloat("face", 0);
  64185. }
  64186. else {
  64187. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64188. }
  64189. // VBO
  64190. var vertices = [];
  64191. vertices.push(1, 1);
  64192. vertices.push(-1, 1);
  64193. vertices.push(-1, -1);
  64194. vertices.push(1, -1);
  64195. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64196. _this._createIndexBuffer();
  64197. return _this;
  64198. }
  64199. ProceduralTexture.prototype._createIndexBuffer = function () {
  64200. var engine = this._engine;
  64201. // Indices
  64202. var indices = [];
  64203. indices.push(0);
  64204. indices.push(1);
  64205. indices.push(2);
  64206. indices.push(0);
  64207. indices.push(2);
  64208. indices.push(3);
  64209. this._indexBuffer = engine.createIndexBuffer(indices);
  64210. };
  64211. ProceduralTexture.prototype._rebuild = function () {
  64212. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64213. if (vb) {
  64214. vb._rebuild();
  64215. }
  64216. this._createIndexBuffer();
  64217. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64218. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64219. }
  64220. };
  64221. ProceduralTexture.prototype.reset = function () {
  64222. if (this._effect === undefined) {
  64223. return;
  64224. }
  64225. var engine = this._engine;
  64226. engine._releaseEffect(this._effect);
  64227. };
  64228. ProceduralTexture.prototype.isReady = function () {
  64229. var _this = this;
  64230. var engine = this._engine;
  64231. var shaders;
  64232. if (!this._fragment) {
  64233. return false;
  64234. }
  64235. if (this._fallbackTextureUsed) {
  64236. return true;
  64237. }
  64238. if (this._fragment.fragmentElement !== undefined) {
  64239. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64240. }
  64241. else {
  64242. shaders = { vertex: "procedural", fragment: this._fragment };
  64243. }
  64244. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64245. _this.releaseInternalTexture();
  64246. if (_this._fallbackTexture) {
  64247. _this._texture = _this._fallbackTexture._texture;
  64248. if (_this._texture) {
  64249. _this._texture.incrementReferences();
  64250. }
  64251. }
  64252. _this._fallbackTextureUsed = true;
  64253. });
  64254. return this._effect.isReady();
  64255. };
  64256. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64257. this._currentRefreshId = -1;
  64258. };
  64259. ProceduralTexture.prototype.setFragment = function (fragment) {
  64260. this._fragment = fragment;
  64261. };
  64262. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64263. get: function () {
  64264. return this._refreshRate;
  64265. },
  64266. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64267. set: function (value) {
  64268. this._refreshRate = value;
  64269. this.resetRefreshCounter();
  64270. },
  64271. enumerable: true,
  64272. configurable: true
  64273. });
  64274. ProceduralTexture.prototype._shouldRender = function () {
  64275. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64276. return false;
  64277. }
  64278. if (this._fallbackTextureUsed) {
  64279. return false;
  64280. }
  64281. if (this._currentRefreshId === -1) {
  64282. this._currentRefreshId = 1;
  64283. return true;
  64284. }
  64285. if (this.refreshRate === this._currentRefreshId) {
  64286. this._currentRefreshId = 1;
  64287. return true;
  64288. }
  64289. this._currentRefreshId++;
  64290. return false;
  64291. };
  64292. ProceduralTexture.prototype.getRenderSize = function () {
  64293. return this._size;
  64294. };
  64295. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64296. if (this._fallbackTextureUsed) {
  64297. return;
  64298. }
  64299. this.releaseInternalTexture();
  64300. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64301. };
  64302. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64303. if (this._uniforms.indexOf(uniformName) === -1) {
  64304. this._uniforms.push(uniformName);
  64305. }
  64306. };
  64307. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64308. if (this._samplers.indexOf(name) === -1) {
  64309. this._samplers.push(name);
  64310. }
  64311. this._textures[name] = texture;
  64312. return this;
  64313. };
  64314. ProceduralTexture.prototype.setFloat = function (name, value) {
  64315. this._checkUniform(name);
  64316. this._floats[name] = value;
  64317. return this;
  64318. };
  64319. ProceduralTexture.prototype.setFloats = function (name, value) {
  64320. this._checkUniform(name);
  64321. this._floatsArrays[name] = value;
  64322. return this;
  64323. };
  64324. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64325. this._checkUniform(name);
  64326. this._colors3[name] = value;
  64327. return this;
  64328. };
  64329. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64330. this._checkUniform(name);
  64331. this._colors4[name] = value;
  64332. return this;
  64333. };
  64334. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64335. this._checkUniform(name);
  64336. this._vectors2[name] = value;
  64337. return this;
  64338. };
  64339. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64340. this._checkUniform(name);
  64341. this._vectors3[name] = value;
  64342. return this;
  64343. };
  64344. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64345. this._checkUniform(name);
  64346. this._matrices[name] = value;
  64347. return this;
  64348. };
  64349. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64350. var scene = this.getScene();
  64351. if (!scene) {
  64352. return;
  64353. }
  64354. var engine = this._engine;
  64355. // Render
  64356. engine.enableEffect(this._effect);
  64357. engine.setState(false);
  64358. // Texture
  64359. for (var name in this._textures) {
  64360. this._effect.setTexture(name, this._textures[name]);
  64361. }
  64362. // Float
  64363. for (name in this._floats) {
  64364. this._effect.setFloat(name, this._floats[name]);
  64365. }
  64366. // Floats
  64367. for (name in this._floatsArrays) {
  64368. this._effect.setArray(name, this._floatsArrays[name]);
  64369. }
  64370. // Color3
  64371. for (name in this._colors3) {
  64372. this._effect.setColor3(name, this._colors3[name]);
  64373. }
  64374. // Color4
  64375. for (name in this._colors4) {
  64376. var color = this._colors4[name];
  64377. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64378. }
  64379. // Vector2
  64380. for (name in this._vectors2) {
  64381. this._effect.setVector2(name, this._vectors2[name]);
  64382. }
  64383. // Vector3
  64384. for (name in this._vectors3) {
  64385. this._effect.setVector3(name, this._vectors3[name]);
  64386. }
  64387. // Matrix
  64388. for (name in this._matrices) {
  64389. this._effect.setMatrix(name, this._matrices[name]);
  64390. }
  64391. if (!this._texture) {
  64392. return;
  64393. }
  64394. if (this.isCube) {
  64395. for (var face = 0; face < 6; face++) {
  64396. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64397. // VBOs
  64398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64399. this._effect.setFloat("face", face);
  64400. // Clear
  64401. engine.clear(scene.clearColor, true, true, true);
  64402. // Draw order
  64403. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64404. // Mipmaps
  64405. if (face === 5) {
  64406. engine.generateMipMapsForCubemap(this._texture);
  64407. }
  64408. }
  64409. }
  64410. else {
  64411. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64412. // VBOs
  64413. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64414. // Clear
  64415. engine.clear(scene.clearColor, true, true, true);
  64416. // Draw order
  64417. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64418. }
  64419. // Unbind
  64420. engine.unBindFramebuffer(this._texture, this.isCube);
  64421. if (this.onGenerated) {
  64422. this.onGenerated();
  64423. }
  64424. };
  64425. ProceduralTexture.prototype.clone = function () {
  64426. var textureSize = this.getSize();
  64427. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64428. // Base texture
  64429. newTexture.hasAlpha = this.hasAlpha;
  64430. newTexture.level = this.level;
  64431. // RenderTarget Texture
  64432. newTexture.coordinatesMode = this.coordinatesMode;
  64433. return newTexture;
  64434. };
  64435. ProceduralTexture.prototype.dispose = function () {
  64436. var scene = this.getScene();
  64437. if (!scene) {
  64438. return;
  64439. }
  64440. var index = scene._proceduralTextures.indexOf(this);
  64441. if (index >= 0) {
  64442. scene._proceduralTextures.splice(index, 1);
  64443. }
  64444. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64445. if (vertexBuffer) {
  64446. vertexBuffer.dispose();
  64447. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64448. }
  64449. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64450. this._indexBuffer = null;
  64451. }
  64452. _super.prototype.dispose.call(this);
  64453. };
  64454. return ProceduralTexture;
  64455. }(BABYLON.Texture));
  64456. BABYLON.ProceduralTexture = ProceduralTexture;
  64457. })(BABYLON || (BABYLON = {}));
  64458. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64459. var BABYLON;
  64460. (function (BABYLON) {
  64461. var CustomProceduralTexture = /** @class */ (function (_super) {
  64462. __extends(CustomProceduralTexture, _super);
  64463. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64464. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64465. _this._animate = true;
  64466. _this._time = 0;
  64467. _this._texturePath = texturePath;
  64468. //Try to load json
  64469. _this.loadJson(texturePath);
  64470. _this.refreshRate = 1;
  64471. return _this;
  64472. }
  64473. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64474. var _this = this;
  64475. var noConfigFile = function () {
  64476. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64477. try {
  64478. _this.setFragment(_this._texturePath);
  64479. }
  64480. catch (ex) {
  64481. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64482. }
  64483. };
  64484. var configFileUrl = jsonUrl + "/config.json";
  64485. var xhr = new XMLHttpRequest();
  64486. xhr.open("GET", configFileUrl, true);
  64487. xhr.addEventListener("load", function () {
  64488. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64489. try {
  64490. _this._config = JSON.parse(xhr.response);
  64491. _this.updateShaderUniforms();
  64492. _this.updateTextures();
  64493. _this.setFragment(_this._texturePath + "/custom");
  64494. _this._animate = _this._config.animate;
  64495. _this.refreshRate = _this._config.refreshrate;
  64496. }
  64497. catch (ex) {
  64498. noConfigFile();
  64499. }
  64500. }
  64501. else {
  64502. noConfigFile();
  64503. }
  64504. }, false);
  64505. xhr.addEventListener("error", function () {
  64506. noConfigFile();
  64507. }, false);
  64508. try {
  64509. xhr.send();
  64510. }
  64511. catch (ex) {
  64512. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64513. }
  64514. };
  64515. CustomProceduralTexture.prototype.isReady = function () {
  64516. if (!_super.prototype.isReady.call(this)) {
  64517. return false;
  64518. }
  64519. for (var name in this._textures) {
  64520. var texture = this._textures[name];
  64521. if (!texture.isReady()) {
  64522. return false;
  64523. }
  64524. }
  64525. return true;
  64526. };
  64527. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64528. var scene = this.getScene();
  64529. if (this._animate && scene) {
  64530. this._time += scene.getAnimationRatio() * 0.03;
  64531. this.updateShaderUniforms();
  64532. }
  64533. _super.prototype.render.call(this, useCameraPostProcess);
  64534. };
  64535. CustomProceduralTexture.prototype.updateTextures = function () {
  64536. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64537. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64538. }
  64539. };
  64540. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64541. if (this._config) {
  64542. for (var j = 0; j < this._config.uniforms.length; j++) {
  64543. var uniform = this._config.uniforms[j];
  64544. switch (uniform.type) {
  64545. case "float":
  64546. this.setFloat(uniform.name, uniform.value);
  64547. break;
  64548. case "color3":
  64549. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64550. break;
  64551. case "color4":
  64552. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64553. break;
  64554. case "vector2":
  64555. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64556. break;
  64557. case "vector3":
  64558. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64559. break;
  64560. }
  64561. }
  64562. }
  64563. this.setFloat("time", this._time);
  64564. };
  64565. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64566. get: function () {
  64567. return this._animate;
  64568. },
  64569. set: function (value) {
  64570. this._animate = value;
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. return CustomProceduralTexture;
  64576. }(BABYLON.ProceduralTexture));
  64577. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64578. })(BABYLON || (BABYLON = {}));
  64579. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64580. var BABYLON;
  64581. (function (BABYLON) {
  64582. var FreeCameraGamepadInput = /** @class */ (function () {
  64583. function FreeCameraGamepadInput() {
  64584. this.gamepadAngularSensibility = 200;
  64585. this.gamepadMoveSensibility = 40;
  64586. // private members
  64587. this._cameraTransform = BABYLON.Matrix.Identity();
  64588. this._deltaTransform = BABYLON.Vector3.Zero();
  64589. this._vector3 = BABYLON.Vector3.Zero();
  64590. this._vector2 = BABYLON.Vector2.Zero();
  64591. }
  64592. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64593. var _this = this;
  64594. var manager = this.camera.getScene().gamepadManager;
  64595. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64596. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64597. // prioritize XBOX gamepads.
  64598. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64599. _this.gamepad = gamepad;
  64600. }
  64601. }
  64602. });
  64603. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64604. if (_this.gamepad === gamepad) {
  64605. _this.gamepad = null;
  64606. }
  64607. });
  64608. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64609. };
  64610. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64611. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64612. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64613. this.gamepad = null;
  64614. };
  64615. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64616. if (this.gamepad && this.gamepad.leftStick) {
  64617. var camera = this.camera;
  64618. var LSValues = this.gamepad.leftStick;
  64619. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64620. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64621. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64622. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64623. var RSValues = this.gamepad.rightStick;
  64624. if (RSValues) {
  64625. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64626. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64627. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64628. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64629. }
  64630. else {
  64631. RSValues = { x: 0, y: 0 };
  64632. }
  64633. if (!camera.rotationQuaternion) {
  64634. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64635. }
  64636. else {
  64637. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64638. }
  64639. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64640. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64641. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64642. camera.cameraDirection.addInPlace(this._deltaTransform);
  64643. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64644. camera.cameraRotation.addInPlace(this._vector2);
  64645. }
  64646. };
  64647. FreeCameraGamepadInput.prototype.getClassName = function () {
  64648. return "FreeCameraGamepadInput";
  64649. };
  64650. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64651. return "gamepad";
  64652. };
  64653. __decorate([
  64654. BABYLON.serialize()
  64655. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64656. __decorate([
  64657. BABYLON.serialize()
  64658. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64659. return FreeCameraGamepadInput;
  64660. }());
  64661. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64662. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64663. })(BABYLON || (BABYLON = {}));
  64664. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64665. var BABYLON;
  64666. (function (BABYLON) {
  64667. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64668. function ArcRotateCameraGamepadInput() {
  64669. this.gamepadRotationSensibility = 80;
  64670. this.gamepadMoveSensibility = 40;
  64671. }
  64672. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64673. var _this = this;
  64674. var manager = this.camera.getScene().gamepadManager;
  64675. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64676. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64677. // prioritize XBOX gamepads.
  64678. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64679. _this.gamepad = gamepad;
  64680. }
  64681. }
  64682. });
  64683. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64684. if (_this.gamepad === gamepad) {
  64685. _this.gamepad = null;
  64686. }
  64687. });
  64688. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64689. };
  64690. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64691. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64692. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64693. this.gamepad = null;
  64694. };
  64695. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64696. if (this.gamepad) {
  64697. var camera = this.camera;
  64698. var RSValues = this.gamepad.rightStick;
  64699. if (RSValues) {
  64700. if (RSValues.x != 0) {
  64701. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64702. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64703. camera.inertialAlphaOffset += normalizedRX;
  64704. }
  64705. }
  64706. if (RSValues.y != 0) {
  64707. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64708. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64709. camera.inertialBetaOffset += normalizedRY;
  64710. }
  64711. }
  64712. }
  64713. var LSValues = this.gamepad.leftStick;
  64714. if (LSValues && LSValues.y != 0) {
  64715. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64716. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64717. this.camera.inertialRadiusOffset -= normalizedLY;
  64718. }
  64719. }
  64720. }
  64721. };
  64722. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64723. return "ArcRotateCameraGamepadInput";
  64724. };
  64725. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64726. return "gamepad";
  64727. };
  64728. __decorate([
  64729. BABYLON.serialize()
  64730. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64731. __decorate([
  64732. BABYLON.serialize()
  64733. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64734. return ArcRotateCameraGamepadInput;
  64735. }());
  64736. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64737. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64738. })(BABYLON || (BABYLON = {}));
  64739. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64740. var BABYLON;
  64741. (function (BABYLON) {
  64742. var GamepadManager = /** @class */ (function () {
  64743. function GamepadManager(_scene) {
  64744. var _this = this;
  64745. this._scene = _scene;
  64746. this._babylonGamepads = [];
  64747. this._oneGamepadConnected = false;
  64748. this._isMonitoring = false;
  64749. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64750. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64751. this._gamepadEventSupported = false;
  64752. }
  64753. else {
  64754. this._gamepadEventSupported = 'GamepadEvent' in window;
  64755. this._gamepadSupport = (navigator.getGamepads ||
  64756. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64757. }
  64758. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64759. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64760. for (var i in _this._babylonGamepads) {
  64761. var gamepad = _this._babylonGamepads[i];
  64762. if (gamepad && gamepad._isConnected) {
  64763. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64764. }
  64765. }
  64766. });
  64767. this._onGamepadConnectedEvent = function (evt) {
  64768. var gamepad = evt.gamepad;
  64769. if (gamepad.index in _this._babylonGamepads) {
  64770. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64771. return;
  64772. }
  64773. }
  64774. var newGamepad;
  64775. if (_this._babylonGamepads[gamepad.index]) {
  64776. newGamepad = _this._babylonGamepads[gamepad.index];
  64777. newGamepad.browserGamepad = gamepad;
  64778. newGamepad._isConnected = true;
  64779. }
  64780. else {
  64781. newGamepad = _this._addNewGamepad(gamepad);
  64782. }
  64783. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64784. _this._startMonitoringGamepads();
  64785. };
  64786. this._onGamepadDisconnectedEvent = function (evt) {
  64787. var gamepad = evt.gamepad;
  64788. // Remove the gamepad from the list of gamepads to monitor.
  64789. for (var i in _this._babylonGamepads) {
  64790. if (_this._babylonGamepads[i].index === gamepad.index) {
  64791. var disconnectedGamepad = _this._babylonGamepads[i];
  64792. disconnectedGamepad._isConnected = false;
  64793. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64794. break;
  64795. }
  64796. }
  64797. };
  64798. if (this._gamepadSupport) {
  64799. //first add already-connected gamepads
  64800. this._updateGamepadObjects();
  64801. if (this._babylonGamepads.length) {
  64802. this._startMonitoringGamepads();
  64803. }
  64804. // Checking if the gamepad connected event is supported (like in Firefox)
  64805. if (this._gamepadEventSupported) {
  64806. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64807. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64808. }
  64809. else {
  64810. this._startMonitoringGamepads();
  64811. }
  64812. }
  64813. }
  64814. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64815. get: function () {
  64816. return this._babylonGamepads;
  64817. },
  64818. enumerable: true,
  64819. configurable: true
  64820. });
  64821. GamepadManager.prototype.getGamepadByType = function (type) {
  64822. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64823. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64824. var gamepad = _a[_i];
  64825. if (gamepad && gamepad.type === type) {
  64826. return gamepad;
  64827. }
  64828. }
  64829. return null;
  64830. };
  64831. GamepadManager.prototype.dispose = function () {
  64832. if (this._gamepadEventSupported) {
  64833. if (this._onGamepadConnectedEvent) {
  64834. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64835. }
  64836. if (this._onGamepadDisconnectedEvent) {
  64837. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64838. }
  64839. this._onGamepadConnectedEvent = null;
  64840. this._onGamepadDisconnectedEvent = null;
  64841. }
  64842. this._babylonGamepads.forEach(function (gamepad) {
  64843. gamepad.dispose();
  64844. });
  64845. this.onGamepadConnectedObservable.clear();
  64846. this.onGamepadDisconnectedObservable.clear();
  64847. this._oneGamepadConnected = false;
  64848. this._stopMonitoringGamepads();
  64849. this._babylonGamepads = [];
  64850. };
  64851. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64852. if (!this._oneGamepadConnected) {
  64853. this._oneGamepadConnected = true;
  64854. }
  64855. var newGamepad;
  64856. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64857. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64858. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64859. }
  64860. else if (gamepad.pose) {
  64861. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64862. }
  64863. else {
  64864. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64865. }
  64866. this._babylonGamepads[newGamepad.index] = newGamepad;
  64867. return newGamepad;
  64868. };
  64869. GamepadManager.prototype._startMonitoringGamepads = function () {
  64870. if (!this._isMonitoring) {
  64871. this._isMonitoring = true;
  64872. //back-comp
  64873. if (!this._scene) {
  64874. this._checkGamepadsStatus();
  64875. }
  64876. }
  64877. };
  64878. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64879. this._isMonitoring = false;
  64880. };
  64881. GamepadManager.prototype._checkGamepadsStatus = function () {
  64882. var _this = this;
  64883. // Hack to be compatible Chrome
  64884. this._updateGamepadObjects();
  64885. for (var i in this._babylonGamepads) {
  64886. var gamepad = this._babylonGamepads[i];
  64887. if (!gamepad || !gamepad.isConnected) {
  64888. continue;
  64889. }
  64890. gamepad.update();
  64891. }
  64892. if (this._isMonitoring && !this._scene) {
  64893. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64894. }
  64895. };
  64896. // This function is called only on Chrome, which does not properly support
  64897. // connection/disconnection events and forces you to recopy again the gamepad object
  64898. GamepadManager.prototype._updateGamepadObjects = function () {
  64899. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64900. for (var i = 0; i < gamepads.length; i++) {
  64901. if (gamepads[i]) {
  64902. if (!this._babylonGamepads[gamepads[i].index]) {
  64903. var newGamepad = this._addNewGamepad(gamepads[i]);
  64904. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64905. }
  64906. else {
  64907. // Forced to copy again this object for Chrome for unknown reason
  64908. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64909. if (!this._babylonGamepads[i].isConnected) {
  64910. this._babylonGamepads[i]._isConnected = true;
  64911. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64912. }
  64913. }
  64914. }
  64915. }
  64916. };
  64917. return GamepadManager;
  64918. }());
  64919. BABYLON.GamepadManager = GamepadManager;
  64920. })(BABYLON || (BABYLON = {}));
  64921. //# sourceMappingURL=babylon.gamepadManager.js.map
  64922. var BABYLON;
  64923. (function (BABYLON) {
  64924. var StickValues = /** @class */ (function () {
  64925. function StickValues(x, y) {
  64926. this.x = x;
  64927. this.y = y;
  64928. }
  64929. return StickValues;
  64930. }());
  64931. BABYLON.StickValues = StickValues;
  64932. var Gamepad = /** @class */ (function () {
  64933. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64934. if (leftStickX === void 0) { leftStickX = 0; }
  64935. if (leftStickY === void 0) { leftStickY = 1; }
  64936. if (rightStickX === void 0) { rightStickX = 2; }
  64937. if (rightStickY === void 0) { rightStickY = 3; }
  64938. this.id = id;
  64939. this.index = index;
  64940. this.browserGamepad = browserGamepad;
  64941. this._isConnected = true;
  64942. this._invertLeftStickY = false;
  64943. this.type = Gamepad.GAMEPAD;
  64944. this._leftStickAxisX = leftStickX;
  64945. this._leftStickAxisY = leftStickY;
  64946. this._rightStickAxisX = rightStickX;
  64947. this._rightStickAxisY = rightStickY;
  64948. if (this.browserGamepad.axes.length >= 2) {
  64949. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64950. }
  64951. if (this.browserGamepad.axes.length >= 4) {
  64952. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64953. }
  64954. }
  64955. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64956. get: function () {
  64957. return this._isConnected;
  64958. },
  64959. enumerable: true,
  64960. configurable: true
  64961. });
  64962. Gamepad.prototype.onleftstickchanged = function (callback) {
  64963. this._onleftstickchanged = callback;
  64964. };
  64965. Gamepad.prototype.onrightstickchanged = function (callback) {
  64966. this._onrightstickchanged = callback;
  64967. };
  64968. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64969. get: function () {
  64970. return this._leftStick;
  64971. },
  64972. set: function (newValues) {
  64973. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64974. this._onleftstickchanged(newValues);
  64975. }
  64976. this._leftStick = newValues;
  64977. },
  64978. enumerable: true,
  64979. configurable: true
  64980. });
  64981. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64982. get: function () {
  64983. return this._rightStick;
  64984. },
  64985. set: function (newValues) {
  64986. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64987. this._onrightstickchanged(newValues);
  64988. }
  64989. this._rightStick = newValues;
  64990. },
  64991. enumerable: true,
  64992. configurable: true
  64993. });
  64994. Gamepad.prototype.update = function () {
  64995. if (this._leftStick) {
  64996. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64997. if (this._invertLeftStickY) {
  64998. this.leftStick.y *= -1;
  64999. }
  65000. }
  65001. if (this._rightStick) {
  65002. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65003. }
  65004. };
  65005. Gamepad.prototype.dispose = function () {
  65006. };
  65007. Gamepad.GAMEPAD = 0;
  65008. Gamepad.GENERIC = 1;
  65009. Gamepad.XBOX = 2;
  65010. Gamepad.POSE_ENABLED = 3;
  65011. return Gamepad;
  65012. }());
  65013. BABYLON.Gamepad = Gamepad;
  65014. var GenericPad = /** @class */ (function (_super) {
  65015. __extends(GenericPad, _super);
  65016. function GenericPad(id, index, browserGamepad) {
  65017. var _this = _super.call(this, id, index, browserGamepad) || this;
  65018. _this.onButtonDownObservable = new BABYLON.Observable();
  65019. _this.onButtonUpObservable = new BABYLON.Observable();
  65020. _this.type = Gamepad.GENERIC;
  65021. _this._buttons = new Array(browserGamepad.buttons.length);
  65022. return _this;
  65023. }
  65024. GenericPad.prototype.onbuttondown = function (callback) {
  65025. this._onbuttondown = callback;
  65026. };
  65027. GenericPad.prototype.onbuttonup = function (callback) {
  65028. this._onbuttonup = callback;
  65029. };
  65030. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65031. if (newValue !== currentValue) {
  65032. if (newValue === 1) {
  65033. if (this._onbuttondown) {
  65034. this._onbuttondown(buttonIndex);
  65035. }
  65036. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65037. }
  65038. if (newValue === 0) {
  65039. if (this._onbuttonup) {
  65040. this._onbuttonup(buttonIndex);
  65041. }
  65042. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65043. }
  65044. }
  65045. return newValue;
  65046. };
  65047. GenericPad.prototype.update = function () {
  65048. _super.prototype.update.call(this);
  65049. for (var index = 0; index < this._buttons.length; index++) {
  65050. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65051. }
  65052. };
  65053. GenericPad.prototype.dispose = function () {
  65054. _super.prototype.dispose.call(this);
  65055. this.onButtonDownObservable.clear();
  65056. this.onButtonUpObservable.clear();
  65057. };
  65058. return GenericPad;
  65059. }(Gamepad));
  65060. BABYLON.GenericPad = GenericPad;
  65061. })(BABYLON || (BABYLON = {}));
  65062. //# sourceMappingURL=babylon.gamepad.js.map
  65063. var BABYLON;
  65064. (function (BABYLON) {
  65065. var Xbox360Button;
  65066. (function (Xbox360Button) {
  65067. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65068. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65069. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65070. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65071. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65072. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65073. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65074. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65075. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65076. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65077. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65078. var Xbox360Dpad;
  65079. (function (Xbox360Dpad) {
  65080. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65081. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65082. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65083. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65084. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65085. var Xbox360Pad = /** @class */ (function (_super) {
  65086. __extends(Xbox360Pad, _super);
  65087. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65088. if (xboxOne === void 0) { xboxOne = false; }
  65089. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65090. _this._leftTrigger = 0;
  65091. _this._rightTrigger = 0;
  65092. _this.onButtonDownObservable = new BABYLON.Observable();
  65093. _this.onButtonUpObservable = new BABYLON.Observable();
  65094. _this.onPadDownObservable = new BABYLON.Observable();
  65095. _this.onPadUpObservable = new BABYLON.Observable();
  65096. _this._buttonA = 0;
  65097. _this._buttonB = 0;
  65098. _this._buttonX = 0;
  65099. _this._buttonY = 0;
  65100. _this._buttonBack = 0;
  65101. _this._buttonStart = 0;
  65102. _this._buttonLB = 0;
  65103. _this._buttonRB = 0;
  65104. _this._buttonLeftStick = 0;
  65105. _this._buttonRightStick = 0;
  65106. _this._dPadUp = 0;
  65107. _this._dPadDown = 0;
  65108. _this._dPadLeft = 0;
  65109. _this._dPadRight = 0;
  65110. _this._isXboxOnePad = false;
  65111. _this.type = BABYLON.Gamepad.XBOX;
  65112. _this._isXboxOnePad = xboxOne;
  65113. return _this;
  65114. }
  65115. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65116. this._onlefttriggerchanged = callback;
  65117. };
  65118. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65119. this._onrighttriggerchanged = callback;
  65120. };
  65121. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65122. get: function () {
  65123. return this._leftTrigger;
  65124. },
  65125. set: function (newValue) {
  65126. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65127. this._onlefttriggerchanged(newValue);
  65128. }
  65129. this._leftTrigger = newValue;
  65130. },
  65131. enumerable: true,
  65132. configurable: true
  65133. });
  65134. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65135. get: function () {
  65136. return this._rightTrigger;
  65137. },
  65138. set: function (newValue) {
  65139. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65140. this._onrighttriggerchanged(newValue);
  65141. }
  65142. this._rightTrigger = newValue;
  65143. },
  65144. enumerable: true,
  65145. configurable: true
  65146. });
  65147. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65148. this._onbuttondown = callback;
  65149. };
  65150. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65151. this._onbuttonup = callback;
  65152. };
  65153. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65154. this._ondpaddown = callback;
  65155. };
  65156. Xbox360Pad.prototype.ondpadup = function (callback) {
  65157. this._ondpadup = callback;
  65158. };
  65159. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65160. if (newValue !== currentValue) {
  65161. if (newValue === 1) {
  65162. if (this._onbuttondown) {
  65163. this._onbuttondown(buttonType);
  65164. }
  65165. this.onButtonDownObservable.notifyObservers(buttonType);
  65166. }
  65167. if (newValue === 0) {
  65168. if (this._onbuttonup) {
  65169. this._onbuttonup(buttonType);
  65170. }
  65171. this.onButtonUpObservable.notifyObservers(buttonType);
  65172. }
  65173. }
  65174. return newValue;
  65175. };
  65176. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65177. if (newValue !== currentValue) {
  65178. if (newValue === 1) {
  65179. if (this._ondpaddown) {
  65180. this._ondpaddown(buttonType);
  65181. }
  65182. this.onPadDownObservable.notifyObservers(buttonType);
  65183. }
  65184. if (newValue === 0) {
  65185. if (this._ondpadup) {
  65186. this._ondpadup(buttonType);
  65187. }
  65188. this.onPadUpObservable.notifyObservers(buttonType);
  65189. }
  65190. }
  65191. return newValue;
  65192. };
  65193. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65194. get: function () {
  65195. return this._buttonA;
  65196. },
  65197. set: function (value) {
  65198. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65199. },
  65200. enumerable: true,
  65201. configurable: true
  65202. });
  65203. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65204. get: function () {
  65205. return this._buttonB;
  65206. },
  65207. set: function (value) {
  65208. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65214. get: function () {
  65215. return this._buttonX;
  65216. },
  65217. set: function (value) {
  65218. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65224. get: function () {
  65225. return this._buttonY;
  65226. },
  65227. set: function (value) {
  65228. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65229. },
  65230. enumerable: true,
  65231. configurable: true
  65232. });
  65233. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65234. get: function () {
  65235. return this._buttonStart;
  65236. },
  65237. set: function (value) {
  65238. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65239. },
  65240. enumerable: true,
  65241. configurable: true
  65242. });
  65243. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65244. get: function () {
  65245. return this._buttonBack;
  65246. },
  65247. set: function (value) {
  65248. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65249. },
  65250. enumerable: true,
  65251. configurable: true
  65252. });
  65253. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65254. get: function () {
  65255. return this._buttonLB;
  65256. },
  65257. set: function (value) {
  65258. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65259. },
  65260. enumerable: true,
  65261. configurable: true
  65262. });
  65263. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65264. get: function () {
  65265. return this._buttonRB;
  65266. },
  65267. set: function (value) {
  65268. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65269. },
  65270. enumerable: true,
  65271. configurable: true
  65272. });
  65273. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65274. get: function () {
  65275. return this._buttonLeftStick;
  65276. },
  65277. set: function (value) {
  65278. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65279. },
  65280. enumerable: true,
  65281. configurable: true
  65282. });
  65283. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65284. get: function () {
  65285. return this._buttonRightStick;
  65286. },
  65287. set: function (value) {
  65288. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65289. },
  65290. enumerable: true,
  65291. configurable: true
  65292. });
  65293. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65294. get: function () {
  65295. return this._dPadUp;
  65296. },
  65297. set: function (value) {
  65298. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65299. },
  65300. enumerable: true,
  65301. configurable: true
  65302. });
  65303. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65304. get: function () {
  65305. return this._dPadDown;
  65306. },
  65307. set: function (value) {
  65308. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65314. get: function () {
  65315. return this._dPadLeft;
  65316. },
  65317. set: function (value) {
  65318. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65319. },
  65320. enumerable: true,
  65321. configurable: true
  65322. });
  65323. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65324. get: function () {
  65325. return this._dPadRight;
  65326. },
  65327. set: function (value) {
  65328. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65329. },
  65330. enumerable: true,
  65331. configurable: true
  65332. });
  65333. Xbox360Pad.prototype.update = function () {
  65334. _super.prototype.update.call(this);
  65335. if (this._isXboxOnePad) {
  65336. this.buttonA = this.browserGamepad.buttons[0].value;
  65337. this.buttonB = this.browserGamepad.buttons[1].value;
  65338. this.buttonX = this.browserGamepad.buttons[2].value;
  65339. this.buttonY = this.browserGamepad.buttons[3].value;
  65340. this.buttonLB = this.browserGamepad.buttons[4].value;
  65341. this.buttonRB = this.browserGamepad.buttons[5].value;
  65342. this.leftTrigger = this.browserGamepad.axes[2];
  65343. this.rightTrigger = this.browserGamepad.axes[5];
  65344. this.buttonBack = this.browserGamepad.buttons[9].value;
  65345. this.buttonStart = this.browserGamepad.buttons[8].value;
  65346. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65347. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65348. this.dPadUp = this.browserGamepad.buttons[11].value;
  65349. this.dPadDown = this.browserGamepad.buttons[12].value;
  65350. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65351. this.dPadRight = this.browserGamepad.buttons[14].value;
  65352. }
  65353. else {
  65354. this.buttonA = this.browserGamepad.buttons[0].value;
  65355. this.buttonB = this.browserGamepad.buttons[1].value;
  65356. this.buttonX = this.browserGamepad.buttons[2].value;
  65357. this.buttonY = this.browserGamepad.buttons[3].value;
  65358. this.buttonLB = this.browserGamepad.buttons[4].value;
  65359. this.buttonRB = this.browserGamepad.buttons[5].value;
  65360. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65361. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65362. this.buttonBack = this.browserGamepad.buttons[8].value;
  65363. this.buttonStart = this.browserGamepad.buttons[9].value;
  65364. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65365. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65366. this.dPadUp = this.browserGamepad.buttons[12].value;
  65367. this.dPadDown = this.browserGamepad.buttons[13].value;
  65368. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65369. this.dPadRight = this.browserGamepad.buttons[15].value;
  65370. }
  65371. };
  65372. Xbox360Pad.prototype.dispose = function () {
  65373. _super.prototype.dispose.call(this);
  65374. this.onButtonDownObservable.clear();
  65375. this.onButtonUpObservable.clear();
  65376. this.onPadDownObservable.clear();
  65377. this.onPadUpObservable.clear();
  65378. };
  65379. return Xbox360Pad;
  65380. }(BABYLON.Gamepad));
  65381. BABYLON.Xbox360Pad = Xbox360Pad;
  65382. })(BABYLON || (BABYLON = {}));
  65383. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65384. var BABYLON;
  65385. (function (BABYLON) {
  65386. var PoseEnabledControllerType;
  65387. (function (PoseEnabledControllerType) {
  65388. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65389. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65390. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65391. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65392. /**
  65393. * Google Daydream
  65394. */
  65395. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65396. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65397. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65398. var PoseEnabledControllerHelper = /** @class */ (function () {
  65399. function PoseEnabledControllerHelper() {
  65400. }
  65401. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65402. // Oculus Touch
  65403. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65404. return new BABYLON.OculusTouchController(vrGamepad);
  65405. }
  65406. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65407. return new BABYLON.WindowsMotionController(vrGamepad);
  65408. }
  65409. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65410. return new BABYLON.ViveController(vrGamepad);
  65411. }
  65412. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65413. return new BABYLON.GearVRController(vrGamepad);
  65414. }
  65415. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65416. return new BABYLON.DaydreamController(vrGamepad);
  65417. }
  65418. else {
  65419. return new BABYLON.GenericController(vrGamepad);
  65420. }
  65421. };
  65422. return PoseEnabledControllerHelper;
  65423. }());
  65424. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65425. var PoseEnabledController = /** @class */ (function (_super) {
  65426. __extends(PoseEnabledController, _super);
  65427. function PoseEnabledController(browserGamepad) {
  65428. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65429. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65430. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65431. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65432. // Represents device position and rotation in babylon space
  65433. _this.devicePosition = BABYLON.Vector3.Zero();
  65434. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65435. _this.deviceScaleFactor = 1;
  65436. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65437. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65438. /**
  65439. * Node to be used when casting a ray from the controller
  65440. */
  65441. _this._pointingPoseNode = null;
  65442. _this._workingMatrix = BABYLON.Matrix.Identity();
  65443. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65444. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65445. _this.position = BABYLON.Vector3.Zero();
  65446. _this.rotationQuaternion = new BABYLON.Quaternion();
  65447. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65448. _this._calculatedRotation = new BABYLON.Quaternion();
  65449. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65450. return _this;
  65451. }
  65452. PoseEnabledController.prototype.update = function () {
  65453. _super.prototype.update.call(this);
  65454. var pose = this.browserGamepad.pose;
  65455. this.updateFromDevice(pose);
  65456. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65457. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65458. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65459. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65460. if (this._mesh) {
  65461. this._mesh.position.copyFrom(this.devicePosition);
  65462. if (this._mesh.rotationQuaternion) {
  65463. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65464. }
  65465. }
  65466. };
  65467. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65468. if (poseData) {
  65469. this.rawPose = poseData;
  65470. if (poseData.position) {
  65471. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65472. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65473. this._deviceRoomPosition.z *= -1;
  65474. }
  65475. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65476. this._calculatedPosition.addInPlace(this.position);
  65477. }
  65478. var pose = this.rawPose;
  65479. if (poseData.orientation && pose.orientation) {
  65480. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65481. if (this._mesh) {
  65482. if (this._mesh.getScene().useRightHandedSystem) {
  65483. this._deviceRoomRotationQuaternion.z *= -1;
  65484. this._deviceRoomRotationQuaternion.w *= -1;
  65485. }
  65486. else {
  65487. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65488. }
  65489. }
  65490. // if the camera is set, rotate to the camera's rotation
  65491. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65492. }
  65493. }
  65494. };
  65495. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65496. if (this._mesh) {
  65497. this._mesh.parent = null;
  65498. }
  65499. this._mesh = mesh;
  65500. if (this._poseControlledCamera) {
  65501. this._mesh.parent = this._poseControlledCamera;
  65502. }
  65503. if (!this._mesh.rotationQuaternion) {
  65504. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65505. }
  65506. };
  65507. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65508. this._poseControlledCamera = camera;
  65509. if (this._mesh) {
  65510. this._mesh.parent = this._poseControlledCamera;
  65511. }
  65512. };
  65513. PoseEnabledController.prototype.dispose = function () {
  65514. if (this._mesh) {
  65515. this._mesh.dispose();
  65516. }
  65517. this._mesh = null;
  65518. _super.prototype.dispose.call(this);
  65519. };
  65520. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65521. get: function () {
  65522. return this._mesh;
  65523. },
  65524. enumerable: true,
  65525. configurable: true
  65526. });
  65527. PoseEnabledController.prototype.getForwardRay = function (length) {
  65528. if (length === void 0) { length = 100; }
  65529. if (!this.mesh) {
  65530. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65531. }
  65532. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65533. var origin = m.getTranslation();
  65534. var forward = new BABYLON.Vector3(0, 0, -1);
  65535. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65536. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65537. return new BABYLON.Ray(origin, direction, length);
  65538. };
  65539. /**
  65540. * Name of the child mesh that can be used to cast a ray from the controller
  65541. */
  65542. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65543. return PoseEnabledController;
  65544. }(BABYLON.Gamepad));
  65545. BABYLON.PoseEnabledController = PoseEnabledController;
  65546. })(BABYLON || (BABYLON = {}));
  65547. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65548. var BABYLON;
  65549. (function (BABYLON) {
  65550. var WebVRController = /** @class */ (function (_super) {
  65551. __extends(WebVRController, _super);
  65552. function WebVRController(vrGamepad) {
  65553. var _this = _super.call(this, vrGamepad) || this;
  65554. // Observables
  65555. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65556. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65557. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65558. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65559. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65560. _this.pad = { x: 0, y: 0 };
  65561. // avoid GC, store state in a tmp object
  65562. _this._changes = {
  65563. pressChanged: false,
  65564. touchChanged: false,
  65565. valueChanged: false,
  65566. changed: false
  65567. };
  65568. _this._buttons = new Array(vrGamepad.buttons.length);
  65569. _this.hand = vrGamepad.hand;
  65570. return _this;
  65571. }
  65572. WebVRController.prototype.onButtonStateChange = function (callback) {
  65573. this._onButtonStateChange = callback;
  65574. };
  65575. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65576. get: function () {
  65577. return this._defaultModel;
  65578. },
  65579. enumerable: true,
  65580. configurable: true
  65581. });
  65582. WebVRController.prototype.update = function () {
  65583. _super.prototype.update.call(this);
  65584. for (var index = 0; index < this._buttons.length; index++) {
  65585. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65586. }
  65587. ;
  65588. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65589. this.pad.x = this.leftStick.x;
  65590. this.pad.y = this.leftStick.y;
  65591. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65592. }
  65593. };
  65594. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65595. if (!newState) {
  65596. newState = {
  65597. pressed: false,
  65598. touched: false,
  65599. value: 0
  65600. };
  65601. }
  65602. if (!currentState) {
  65603. this._buttons[buttonIndex] = {
  65604. pressed: newState.pressed,
  65605. touched: newState.touched,
  65606. value: newState.value
  65607. };
  65608. return;
  65609. }
  65610. this._checkChanges(newState, currentState);
  65611. if (this._changes.changed) {
  65612. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65613. this._handleButtonChange(buttonIndex, newState, this._changes);
  65614. }
  65615. this._buttons[buttonIndex].pressed = newState.pressed;
  65616. this._buttons[buttonIndex].touched = newState.touched;
  65617. // oculus triggers are never 0, thou not touched.
  65618. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65619. };
  65620. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65621. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65622. this._changes.touchChanged = newState.touched !== currentState.touched;
  65623. this._changes.valueChanged = newState.value !== currentState.value;
  65624. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65625. return this._changes;
  65626. };
  65627. WebVRController.prototype.dispose = function () {
  65628. _super.prototype.dispose.call(this);
  65629. this.onTriggerStateChangedObservable.clear();
  65630. this.onMainButtonStateChangedObservable.clear();
  65631. this.onSecondaryButtonStateChangedObservable.clear();
  65632. this.onPadStateChangedObservable.clear();
  65633. this.onPadValuesChangedObservable.clear();
  65634. };
  65635. return WebVRController;
  65636. }(BABYLON.PoseEnabledController));
  65637. BABYLON.WebVRController = WebVRController;
  65638. })(BABYLON || (BABYLON = {}));
  65639. //# sourceMappingURL=babylon.webVRController.js.map
  65640. var BABYLON;
  65641. (function (BABYLON) {
  65642. var OculusTouchController = /** @class */ (function (_super) {
  65643. __extends(OculusTouchController, _super);
  65644. function OculusTouchController(vrGamepad) {
  65645. var _this = _super.call(this, vrGamepad) || this;
  65646. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65647. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65648. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65649. return _this;
  65650. }
  65651. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65652. var _this = this;
  65653. var meshName;
  65654. // Hand
  65655. if (this.hand === 'left') {
  65656. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65657. }
  65658. else {
  65659. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65660. }
  65661. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65662. /*
  65663. Parent Mesh name: oculus_touch_left
  65664. - body
  65665. - trigger
  65666. - thumbstick
  65667. - grip
  65668. - button_y
  65669. - button_x
  65670. - button_enter
  65671. */
  65672. _this._defaultModel = newMeshes[1];
  65673. _this.attachToMesh(_this._defaultModel);
  65674. if (meshLoaded) {
  65675. meshLoaded(_this._defaultModel);
  65676. }
  65677. });
  65678. };
  65679. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65680. // helper getters for left and right hand.
  65681. get: function () {
  65682. if (this.hand === 'right') {
  65683. return this.onMainButtonStateChangedObservable;
  65684. }
  65685. else {
  65686. throw new Error('No A button on left hand');
  65687. }
  65688. },
  65689. enumerable: true,
  65690. configurable: true
  65691. });
  65692. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65693. get: function () {
  65694. if (this.hand === 'right') {
  65695. return this.onSecondaryButtonStateChangedObservable;
  65696. }
  65697. else {
  65698. throw new Error('No B button on left hand');
  65699. }
  65700. },
  65701. enumerable: true,
  65702. configurable: true
  65703. });
  65704. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65705. get: function () {
  65706. if (this.hand === 'left') {
  65707. return this.onMainButtonStateChangedObservable;
  65708. }
  65709. else {
  65710. throw new Error('No X button on right hand');
  65711. }
  65712. },
  65713. enumerable: true,
  65714. configurable: true
  65715. });
  65716. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65717. get: function () {
  65718. if (this.hand === 'left') {
  65719. return this.onSecondaryButtonStateChangedObservable;
  65720. }
  65721. else {
  65722. throw new Error('No Y button on right hand');
  65723. }
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. /*
  65729. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65730. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65731. 2) secondary trigger (same)
  65732. 3) A (right) X (left), touch, pressed = value
  65733. 4) B / Y
  65734. 5) thumb rest
  65735. */
  65736. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65737. var notifyObject = state; //{ state: state, changes: changes };
  65738. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65739. switch (buttonIdx) {
  65740. case 0:
  65741. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65742. return;
  65743. case 1:// index trigger
  65744. if (this._defaultModel) {
  65745. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65746. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65747. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65748. }
  65749. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65750. return;
  65751. case 2:// secondary trigger
  65752. if (this._defaultModel) {
  65753. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65754. }
  65755. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65756. return;
  65757. case 3:
  65758. if (this._defaultModel) {
  65759. if (notifyObject.pressed) {
  65760. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65761. }
  65762. else {
  65763. (this._defaultModel.getChildren()[1]).position.y = 0;
  65764. }
  65765. }
  65766. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65767. return;
  65768. case 4:
  65769. if (this._defaultModel) {
  65770. if (notifyObject.pressed) {
  65771. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65772. }
  65773. else {
  65774. (this._defaultModel.getChildren()[2]).position.y = 0;
  65775. }
  65776. }
  65777. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65778. return;
  65779. case 5:
  65780. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65781. return;
  65782. }
  65783. };
  65784. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65785. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65786. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65787. return OculusTouchController;
  65788. }(BABYLON.WebVRController));
  65789. BABYLON.OculusTouchController = OculusTouchController;
  65790. })(BABYLON || (BABYLON = {}));
  65791. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65792. var BABYLON;
  65793. (function (BABYLON) {
  65794. var ViveController = /** @class */ (function (_super) {
  65795. __extends(ViveController, _super);
  65796. function ViveController(vrGamepad) {
  65797. var _this = _super.call(this, vrGamepad) || this;
  65798. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65799. _this._invertLeftStickY = true;
  65800. return _this;
  65801. }
  65802. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65803. var _this = this;
  65804. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65805. /*
  65806. Parent Mesh name: ViveWand
  65807. - body
  65808. - r_gripper
  65809. - l_gripper
  65810. - menu_button
  65811. - system_button
  65812. - trackpad
  65813. - trigger
  65814. - LED
  65815. */
  65816. _this._defaultModel = newMeshes[1];
  65817. _this.attachToMesh(_this._defaultModel);
  65818. if (meshLoaded) {
  65819. meshLoaded(_this._defaultModel);
  65820. }
  65821. });
  65822. };
  65823. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65824. get: function () {
  65825. return this.onMainButtonStateChangedObservable;
  65826. },
  65827. enumerable: true,
  65828. configurable: true
  65829. });
  65830. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65831. get: function () {
  65832. return this.onMainButtonStateChangedObservable;
  65833. },
  65834. enumerable: true,
  65835. configurable: true
  65836. });
  65837. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65838. get: function () {
  65839. return this.onSecondaryButtonStateChangedObservable;
  65840. },
  65841. enumerable: true,
  65842. configurable: true
  65843. });
  65844. /**
  65845. * Vive mapping:
  65846. * 0: touchpad
  65847. * 1: trigger
  65848. * 2: left AND right buttons
  65849. * 3: menu button
  65850. */
  65851. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65852. var notifyObject = state; //{ state: state, changes: changes };
  65853. switch (buttonIdx) {
  65854. case 0:
  65855. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65856. return;
  65857. case 1:// index trigger
  65858. if (this._defaultModel) {
  65859. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65860. }
  65861. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65862. return;
  65863. case 2:// left AND right button
  65864. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65865. return;
  65866. case 3:
  65867. if (this._defaultModel) {
  65868. if (notifyObject.pressed) {
  65869. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65870. }
  65871. else {
  65872. (this._defaultModel.getChildren()[2]).position.y = 0;
  65873. }
  65874. }
  65875. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65876. return;
  65877. }
  65878. };
  65879. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65880. ViveController.MODEL_FILENAME = 'wand.babylon';
  65881. return ViveController;
  65882. }(BABYLON.WebVRController));
  65883. BABYLON.ViveController = ViveController;
  65884. })(BABYLON || (BABYLON = {}));
  65885. //# sourceMappingURL=babylon.viveController.js.map
  65886. var BABYLON;
  65887. (function (BABYLON) {
  65888. var GenericController = /** @class */ (function (_super) {
  65889. __extends(GenericController, _super);
  65890. function GenericController(vrGamepad) {
  65891. return _super.call(this, vrGamepad) || this;
  65892. }
  65893. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65894. var _this = this;
  65895. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65896. _this._defaultModel = newMeshes[1];
  65897. _this.attachToMesh(_this._defaultModel);
  65898. if (meshLoaded) {
  65899. meshLoaded(_this._defaultModel);
  65900. }
  65901. });
  65902. };
  65903. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65904. console.log("Button id: " + buttonIdx + "state: ");
  65905. console.dir(state);
  65906. };
  65907. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65908. GenericController.MODEL_FILENAME = 'generic.babylon';
  65909. return GenericController;
  65910. }(BABYLON.WebVRController));
  65911. BABYLON.GenericController = GenericController;
  65912. })(BABYLON || (BABYLON = {}));
  65913. //# sourceMappingURL=babylon.genericController.js.map
  65914. var BABYLON;
  65915. (function (BABYLON) {
  65916. var LoadedMeshInfo = /** @class */ (function () {
  65917. function LoadedMeshInfo() {
  65918. this.buttonMeshes = {};
  65919. this.axisMeshes = {};
  65920. }
  65921. return LoadedMeshInfo;
  65922. }());
  65923. var WindowsMotionController = /** @class */ (function (_super) {
  65924. __extends(WindowsMotionController, _super);
  65925. function WindowsMotionController(vrGamepad) {
  65926. var _this = _super.call(this, vrGamepad) || this;
  65927. _this._mapping = {
  65928. // Semantic button names
  65929. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65930. // A mapping of the button name to glTF model node name
  65931. // that should be transformed by button value.
  65932. buttonMeshNames: {
  65933. 'trigger': 'SELECT',
  65934. 'menu': 'MENU',
  65935. 'grip': 'GRASP',
  65936. 'thumbstick': 'THUMBSTICK_PRESS',
  65937. 'trackpad': 'TOUCHPAD_PRESS'
  65938. },
  65939. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65940. buttonObservableNames: {
  65941. 'trigger': 'onTriggerStateChangedObservable',
  65942. 'menu': 'onSecondaryButtonStateChangedObservable',
  65943. 'grip': 'onMainButtonStateChangedObservable',
  65944. 'thumbstick': 'onPadStateChangedObservable',
  65945. 'trackpad': 'onTrackpadChangedObservable'
  65946. },
  65947. // A mapping of the axis name to glTF model node name
  65948. // that should be transformed by axis value.
  65949. // This array mirrors the browserGamepad.axes array, such that
  65950. // the mesh corresponding to axis 0 is in this array index 0.
  65951. axisMeshNames: [
  65952. 'THUMBSTICK_X',
  65953. 'THUMBSTICK_Y',
  65954. 'TOUCHPAD_TOUCH_X',
  65955. 'TOUCHPAD_TOUCH_Y'
  65956. ],
  65957. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65958. };
  65959. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65960. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65961. _this.trackpad = { x: 0, y: 0 };
  65962. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65963. _this._loadedMeshInfo = null;
  65964. return _this;
  65965. }
  65966. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65967. get: function () {
  65968. return this.onTriggerStateChangedObservable;
  65969. },
  65970. enumerable: true,
  65971. configurable: true
  65972. });
  65973. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65974. get: function () {
  65975. return this.onSecondaryButtonStateChangedObservable;
  65976. },
  65977. enumerable: true,
  65978. configurable: true
  65979. });
  65980. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65981. get: function () {
  65982. return this.onMainButtonStateChangedObservable;
  65983. },
  65984. enumerable: true,
  65985. configurable: true
  65986. });
  65987. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65988. get: function () {
  65989. return this.onPadStateChangedObservable;
  65990. },
  65991. enumerable: true,
  65992. configurable: true
  65993. });
  65994. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65995. get: function () {
  65996. return this.onTrackpadChangedObservable;
  65997. },
  65998. enumerable: true,
  65999. configurable: true
  66000. });
  66001. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66002. get: function () {
  66003. return this.onTrackpadValuesChangedObservable;
  66004. },
  66005. enumerable: true,
  66006. configurable: true
  66007. });
  66008. /**
  66009. * Called once per frame by the engine.
  66010. */
  66011. WindowsMotionController.prototype.update = function () {
  66012. _super.prototype.update.call(this);
  66013. if (this.browserGamepad.axes) {
  66014. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66015. this.trackpad.x = this.browserGamepad["axes"][2];
  66016. this.trackpad.y = this.browserGamepad["axes"][3];
  66017. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66018. }
  66019. // Only need to animate axes if there is a loaded mesh
  66020. if (this._loadedMeshInfo) {
  66021. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66022. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66023. }
  66024. }
  66025. }
  66026. };
  66027. /**
  66028. * Called once for each button that changed state since the last frame
  66029. * @param buttonIdx Which button index changed
  66030. * @param state New state of the button
  66031. * @param changes Which properties on the state changed since last frame
  66032. */
  66033. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66034. var buttonName = this._mapping.buttons[buttonIdx];
  66035. if (!buttonName) {
  66036. return;
  66037. }
  66038. // Only emit events for buttons that we know how to map from index to name
  66039. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66040. if (observable) {
  66041. observable.notifyObservers(state);
  66042. }
  66043. this.lerpButtonTransform(buttonName, state.value);
  66044. };
  66045. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66046. // If there is no loaded mesh, there is nothing to transform.
  66047. if (!this._loadedMeshInfo) {
  66048. return;
  66049. }
  66050. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66051. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66052. return;
  66053. }
  66054. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66055. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66056. };
  66057. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66058. if (!this._loadedMeshInfo) {
  66059. return;
  66060. }
  66061. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66062. if (!meshInfo) {
  66063. return;
  66064. }
  66065. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66066. return;
  66067. }
  66068. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66069. var lerpValue = axisValue * 0.5 + 0.5;
  66070. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66071. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66072. };
  66073. /**
  66074. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66075. * @param scene scene in which to add meshes
  66076. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66077. */
  66078. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66079. var _this = this;
  66080. if (forceDefault === void 0) { forceDefault = false; }
  66081. var path;
  66082. var filename;
  66083. // Checking if GLB loader is present
  66084. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66085. // Determine the device specific folder based on the ID suffix
  66086. var device = 'default';
  66087. if (this.id && !forceDefault) {
  66088. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66089. device = ((match && match[0]) || device);
  66090. }
  66091. // Hand
  66092. if (this.hand === 'left') {
  66093. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66094. }
  66095. else {
  66096. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66097. }
  66098. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66099. }
  66100. else {
  66101. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66102. path = BABYLON.GenericController.MODEL_BASE_URL;
  66103. filename = BABYLON.GenericController.MODEL_FILENAME;
  66104. }
  66105. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66106. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66107. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66108. if (!_this._loadedMeshInfo) {
  66109. return;
  66110. }
  66111. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66112. _this.attachToMesh(_this._defaultModel);
  66113. if (meshLoaded) {
  66114. meshLoaded(_this._defaultModel);
  66115. }
  66116. }, null, function (scene, message) {
  66117. BABYLON.Tools.Log(message);
  66118. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66119. if (!forceDefault) {
  66120. _this.initControllerMesh(scene, meshLoaded, true);
  66121. }
  66122. });
  66123. };
  66124. /**
  66125. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66126. * can be transformed by button presses and axes values, based on this._mapping.
  66127. *
  66128. * @param scene scene in which the meshes exist
  66129. * @param meshes list of meshes that make up the controller model to process
  66130. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66131. */
  66132. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66133. var loadedMeshInfo = null;
  66134. // Create a new mesh to contain the glTF hierarchy
  66135. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66136. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66137. var childMesh = null;
  66138. for (var i = 0; i < meshes.length; i++) {
  66139. var mesh = meshes[i];
  66140. if (!mesh.parent) {
  66141. // Exclude controller meshes from picking results
  66142. mesh.isPickable = false;
  66143. // Handle root node, attach to the new parentMesh
  66144. childMesh = mesh;
  66145. break;
  66146. }
  66147. }
  66148. if (childMesh) {
  66149. childMesh.setParent(parentMesh);
  66150. // Create our mesh info. Note that this method will always return non-null.
  66151. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66152. }
  66153. else {
  66154. BABYLON.Tools.Warn('Could not find root node in model file.');
  66155. }
  66156. return loadedMeshInfo;
  66157. };
  66158. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66159. var loadedMeshInfo = new LoadedMeshInfo();
  66160. var i;
  66161. loadedMeshInfo.rootNode = rootNode;
  66162. // Reset the caches
  66163. loadedMeshInfo.buttonMeshes = {};
  66164. loadedMeshInfo.axisMeshes = {};
  66165. // Button Meshes
  66166. for (i = 0; i < this._mapping.buttons.length; i++) {
  66167. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66168. if (!buttonMeshName) {
  66169. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66170. continue;
  66171. }
  66172. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66173. if (!buttonMesh) {
  66174. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66175. continue;
  66176. }
  66177. var buttonMeshInfo = {
  66178. index: i,
  66179. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66180. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66181. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66182. };
  66183. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66184. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66185. }
  66186. else {
  66187. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66188. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66189. '(VALUE: ' + !!buttonMeshInfo.value +
  66190. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66191. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66192. ')');
  66193. }
  66194. }
  66195. // Axis Meshes
  66196. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66197. var axisMeshName = this._mapping.axisMeshNames[i];
  66198. if (!axisMeshName) {
  66199. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66200. continue;
  66201. }
  66202. var axisMesh = getChildByName(rootNode, axisMeshName);
  66203. if (!axisMesh) {
  66204. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66205. continue;
  66206. }
  66207. var axisMeshInfo = {
  66208. index: i,
  66209. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66210. min: getImmediateChildByName(axisMesh, 'MIN'),
  66211. max: getImmediateChildByName(axisMesh, 'MAX')
  66212. };
  66213. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66214. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66215. }
  66216. else {
  66217. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66218. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66219. '(VALUE: ' + !!axisMeshInfo.value +
  66220. ', MIN: ' + !!axisMeshInfo.min +
  66221. ', MAX:' + !!axisMeshInfo.max +
  66222. ')');
  66223. }
  66224. }
  66225. // Pointing Ray
  66226. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66227. if (!loadedMeshInfo.pointingPoseNode) {
  66228. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66229. }
  66230. return loadedMeshInfo;
  66231. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66232. function getChildByName(node, name) {
  66233. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66234. }
  66235. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66236. function getImmediateChildByName(node, name) {
  66237. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66238. }
  66239. };
  66240. WindowsMotionController.prototype.getForwardRay = function (length) {
  66241. if (length === void 0) { length = 100; }
  66242. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66243. return _super.prototype.getForwardRay.call(this, length);
  66244. }
  66245. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66246. var origin = m.getTranslation();
  66247. var forward = new BABYLON.Vector3(0, 0, -1);
  66248. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66249. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66250. return new BABYLON.Ray(origin, direction, length);
  66251. };
  66252. WindowsMotionController.prototype.dispose = function () {
  66253. _super.prototype.dispose.call(this);
  66254. this.onTrackpadChangedObservable.clear();
  66255. };
  66256. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66257. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66258. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66259. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66260. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66261. return WindowsMotionController;
  66262. }(BABYLON.WebVRController));
  66263. BABYLON.WindowsMotionController = WindowsMotionController;
  66264. })(BABYLON || (BABYLON = {}));
  66265. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66266. var BABYLON;
  66267. (function (BABYLON) {
  66268. var GearVRController = /** @class */ (function (_super) {
  66269. __extends(GearVRController, _super);
  66270. function GearVRController(vrGamepad) {
  66271. var _this = _super.call(this, vrGamepad) || this;
  66272. _this._buttonIndexToObservableNameMap = [
  66273. 'onTrackpadChangedObservable',
  66274. 'onTriggerStateChangedObservable' // Trigger
  66275. ];
  66276. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66277. return _this;
  66278. }
  66279. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66280. var _this = this;
  66281. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66282. _this._defaultModel = newMeshes[1];
  66283. _this.attachToMesh(_this._defaultModel);
  66284. if (meshLoaded) {
  66285. meshLoaded(_this._defaultModel);
  66286. }
  66287. });
  66288. };
  66289. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66290. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66291. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66292. // Only emit events for buttons that we know how to map from index to observable
  66293. var observable = this[observableName];
  66294. if (observable) {
  66295. observable.notifyObservers(state);
  66296. }
  66297. }
  66298. };
  66299. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66300. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66301. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66302. return GearVRController;
  66303. }(BABYLON.WebVRController));
  66304. BABYLON.GearVRController = GearVRController;
  66305. })(BABYLON || (BABYLON = {}));
  66306. //# sourceMappingURL=babylon.gearVRController.js.map
  66307. var BABYLON;
  66308. (function (BABYLON) {
  66309. /**
  66310. * Google Daydream controller
  66311. */
  66312. var DaydreamController = /** @class */ (function (_super) {
  66313. __extends(DaydreamController, _super);
  66314. function DaydreamController(vrGamepad) {
  66315. var _this = _super.call(this, vrGamepad) || this;
  66316. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66317. return _this;
  66318. }
  66319. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66320. var _this = this;
  66321. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66322. _this._defaultModel = newMeshes[1];
  66323. _this.attachToMesh(_this._defaultModel);
  66324. if (meshLoaded) {
  66325. meshLoaded(_this._defaultModel);
  66326. }
  66327. });
  66328. };
  66329. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66330. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66331. if (buttonIdx === 0) {
  66332. var observable = this.onTriggerStateChangedObservable;
  66333. if (observable) {
  66334. observable.notifyObservers(state);
  66335. }
  66336. }
  66337. else {
  66338. // If the app or home buttons are ever made available
  66339. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66340. }
  66341. };
  66342. /**
  66343. * Base Url for the controller model.
  66344. */
  66345. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66346. /**
  66347. * File name for the controller model.
  66348. */
  66349. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66350. /**
  66351. * Gamepad Id prefix used to identify Daydream Controller.
  66352. */
  66353. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66354. return DaydreamController;
  66355. }(BABYLON.WebVRController));
  66356. BABYLON.DaydreamController = DaydreamController;
  66357. })(BABYLON || (BABYLON = {}));
  66358. //# sourceMappingURL=babylon.daydreamController.js.map
  66359. var BABYLON;
  66360. (function (BABYLON) {
  66361. var FollowCamera = /** @class */ (function (_super) {
  66362. __extends(FollowCamera, _super);
  66363. function FollowCamera(name, position, scene, lockedTarget) {
  66364. if (lockedTarget === void 0) { lockedTarget = null; }
  66365. var _this = _super.call(this, name, position, scene) || this;
  66366. _this.radius = 12;
  66367. _this.rotationOffset = 0;
  66368. _this.heightOffset = 4;
  66369. _this.cameraAcceleration = 0.05;
  66370. _this.maxCameraSpeed = 20;
  66371. _this.lockedTarget = lockedTarget;
  66372. return _this;
  66373. }
  66374. FollowCamera.prototype.getRadians = function (degrees) {
  66375. return degrees * Math.PI / 180;
  66376. };
  66377. FollowCamera.prototype.follow = function (cameraTarget) {
  66378. if (!cameraTarget)
  66379. return;
  66380. var yRotation;
  66381. if (cameraTarget.rotationQuaternion) {
  66382. var rotMatrix = new BABYLON.Matrix();
  66383. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66384. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66385. }
  66386. else {
  66387. yRotation = cameraTarget.rotation.y;
  66388. }
  66389. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66390. var targetPosition = cameraTarget.getAbsolutePosition();
  66391. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66392. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66393. var dx = targetX - this.position.x;
  66394. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66395. var dz = (targetZ) - this.position.z;
  66396. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66397. var vy = dy * this.cameraAcceleration;
  66398. var vz = dz * this.cameraAcceleration * 2;
  66399. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66400. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66401. }
  66402. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66403. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66404. }
  66405. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66406. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66407. }
  66408. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66409. this.setTarget(targetPosition);
  66410. };
  66411. FollowCamera.prototype._checkInputs = function () {
  66412. _super.prototype._checkInputs.call(this);
  66413. if (this.lockedTarget) {
  66414. this.follow(this.lockedTarget);
  66415. }
  66416. };
  66417. FollowCamera.prototype.getClassName = function () {
  66418. return "FollowCamera";
  66419. };
  66420. __decorate([
  66421. BABYLON.serialize()
  66422. ], FollowCamera.prototype, "radius", void 0);
  66423. __decorate([
  66424. BABYLON.serialize()
  66425. ], FollowCamera.prototype, "rotationOffset", void 0);
  66426. __decorate([
  66427. BABYLON.serialize()
  66428. ], FollowCamera.prototype, "heightOffset", void 0);
  66429. __decorate([
  66430. BABYLON.serialize()
  66431. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66432. __decorate([
  66433. BABYLON.serialize()
  66434. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66435. __decorate([
  66436. BABYLON.serializeAsMeshReference("lockedTargetId")
  66437. ], FollowCamera.prototype, "lockedTarget", void 0);
  66438. return FollowCamera;
  66439. }(BABYLON.TargetCamera));
  66440. BABYLON.FollowCamera = FollowCamera;
  66441. var ArcFollowCamera = /** @class */ (function (_super) {
  66442. __extends(ArcFollowCamera, _super);
  66443. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66444. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66445. _this.alpha = alpha;
  66446. _this.beta = beta;
  66447. _this.radius = radius;
  66448. _this.target = target;
  66449. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66450. _this.follow();
  66451. return _this;
  66452. }
  66453. ArcFollowCamera.prototype.follow = function () {
  66454. if (!this.target) {
  66455. return;
  66456. }
  66457. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66458. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66459. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66460. var targetPosition = this.target.getAbsolutePosition();
  66461. this.position = targetPosition.add(this._cartesianCoordinates);
  66462. this.setTarget(targetPosition);
  66463. };
  66464. ArcFollowCamera.prototype._checkInputs = function () {
  66465. _super.prototype._checkInputs.call(this);
  66466. this.follow();
  66467. };
  66468. ArcFollowCamera.prototype.getClassName = function () {
  66469. return "ArcFollowCamera";
  66470. };
  66471. return ArcFollowCamera;
  66472. }(BABYLON.TargetCamera));
  66473. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66474. })(BABYLON || (BABYLON = {}));
  66475. //# sourceMappingURL=babylon.followCamera.js.map
  66476. var BABYLON;
  66477. (function (BABYLON) {
  66478. // We're mainly based on the logic defined into the FreeCamera code
  66479. var UniversalCamera = /** @class */ (function (_super) {
  66480. __extends(UniversalCamera, _super);
  66481. //-- end properties for backward compatibility for inputs
  66482. function UniversalCamera(name, position, scene) {
  66483. var _this = _super.call(this, name, position, scene) || this;
  66484. _this.inputs.addGamepad();
  66485. return _this;
  66486. }
  66487. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66488. //-- Begin properties for backward compatibility for inputs
  66489. get: function () {
  66490. var gamepad = this.inputs.attached["gamepad"];
  66491. if (gamepad)
  66492. return gamepad.gamepadAngularSensibility;
  66493. return 0;
  66494. },
  66495. set: function (value) {
  66496. var gamepad = this.inputs.attached["gamepad"];
  66497. if (gamepad)
  66498. gamepad.gamepadAngularSensibility = value;
  66499. },
  66500. enumerable: true,
  66501. configurable: true
  66502. });
  66503. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66504. get: function () {
  66505. var gamepad = this.inputs.attached["gamepad"];
  66506. if (gamepad)
  66507. return gamepad.gamepadMoveSensibility;
  66508. return 0;
  66509. },
  66510. set: function (value) {
  66511. var gamepad = this.inputs.attached["gamepad"];
  66512. if (gamepad)
  66513. gamepad.gamepadMoveSensibility = value;
  66514. },
  66515. enumerable: true,
  66516. configurable: true
  66517. });
  66518. UniversalCamera.prototype.getClassName = function () {
  66519. return "UniversalCamera";
  66520. };
  66521. return UniversalCamera;
  66522. }(BABYLON.TouchCamera));
  66523. BABYLON.UniversalCamera = UniversalCamera;
  66524. })(BABYLON || (BABYLON = {}));
  66525. //# sourceMappingURL=babylon.universalCamera.js.map
  66526. var BABYLON;
  66527. (function (BABYLON) {
  66528. // We're mainly based on the logic defined into the FreeCamera code
  66529. var GamepadCamera = /** @class */ (function (_super) {
  66530. __extends(GamepadCamera, _super);
  66531. //-- end properties for backward compatibility for inputs
  66532. function GamepadCamera(name, position, scene) {
  66533. return _super.call(this, name, position, scene) || this;
  66534. }
  66535. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66536. //-- Begin properties for backward compatibility for inputs
  66537. get: function () {
  66538. var gamepad = this.inputs.attached["gamepad"];
  66539. if (gamepad)
  66540. return gamepad.gamepadAngularSensibility;
  66541. return 0;
  66542. },
  66543. set: function (value) {
  66544. var gamepad = this.inputs.attached["gamepad"];
  66545. if (gamepad)
  66546. gamepad.gamepadAngularSensibility = value;
  66547. },
  66548. enumerable: true,
  66549. configurable: true
  66550. });
  66551. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66552. get: function () {
  66553. var gamepad = this.inputs.attached["gamepad"];
  66554. if (gamepad)
  66555. return gamepad.gamepadMoveSensibility;
  66556. return 0;
  66557. },
  66558. set: function (value) {
  66559. var gamepad = this.inputs.attached["gamepad"];
  66560. if (gamepad)
  66561. gamepad.gamepadMoveSensibility = value;
  66562. },
  66563. enumerable: true,
  66564. configurable: true
  66565. });
  66566. GamepadCamera.prototype.getClassName = function () {
  66567. return "GamepadCamera";
  66568. };
  66569. return GamepadCamera;
  66570. }(BABYLON.UniversalCamera));
  66571. BABYLON.GamepadCamera = GamepadCamera;
  66572. })(BABYLON || (BABYLON = {}));
  66573. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66574. var BABYLON;
  66575. (function (BABYLON) {
  66576. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66577. function PostProcessRenderPipelineManager() {
  66578. this._renderPipelines = {};
  66579. }
  66580. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66581. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66582. };
  66583. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66584. if (unique === void 0) { unique = false; }
  66585. var renderPipeline = this._renderPipelines[renderPipelineName];
  66586. if (!renderPipeline) {
  66587. return;
  66588. }
  66589. renderPipeline._attachCameras(cameras, unique);
  66590. };
  66591. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66592. var renderPipeline = this._renderPipelines[renderPipelineName];
  66593. if (!renderPipeline) {
  66594. return;
  66595. }
  66596. renderPipeline._detachCameras(cameras);
  66597. };
  66598. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66599. var renderPipeline = this._renderPipelines[renderPipelineName];
  66600. if (!renderPipeline) {
  66601. return;
  66602. }
  66603. renderPipeline._enableEffect(renderEffectName, cameras);
  66604. };
  66605. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66606. var renderPipeline = this._renderPipelines[renderPipelineName];
  66607. if (!renderPipeline) {
  66608. return;
  66609. }
  66610. renderPipeline._disableEffect(renderEffectName, cameras);
  66611. };
  66612. PostProcessRenderPipelineManager.prototype.update = function () {
  66613. for (var renderPipelineName in this._renderPipelines) {
  66614. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66615. var pipeline = this._renderPipelines[renderPipelineName];
  66616. if (!pipeline.isSupported) {
  66617. pipeline.dispose();
  66618. delete this._renderPipelines[renderPipelineName];
  66619. }
  66620. else {
  66621. pipeline._update();
  66622. }
  66623. }
  66624. }
  66625. };
  66626. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66627. for (var renderPipelineName in this._renderPipelines) {
  66628. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66629. var pipeline = this._renderPipelines[renderPipelineName];
  66630. pipeline._rebuild();
  66631. }
  66632. }
  66633. };
  66634. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66635. for (var renderPipelineName in this._renderPipelines) {
  66636. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66637. var pipeline = this._renderPipelines[renderPipelineName];
  66638. pipeline.dispose();
  66639. }
  66640. }
  66641. };
  66642. return PostProcessRenderPipelineManager;
  66643. }());
  66644. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66645. })(BABYLON || (BABYLON = {}));
  66646. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66647. var BABYLON;
  66648. (function (BABYLON) {
  66649. /**
  66650. * This represents a set of one or more post processes in Babylon.
  66651. * A post process can be used to apply a shader to a texture after it is rendered.
  66652. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66653. */
  66654. var PostProcessRenderEffect = /** @class */ (function () {
  66655. /**
  66656. * Instantiates a post process render effect.
  66657. * A post process can be used to apply a shader to a texture after it is rendered.
  66658. * @param engine The engine the effect is tied to
  66659. * @param name The name of the effect
  66660. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66661. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66662. */
  66663. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66664. this._name = name;
  66665. this._singleInstance = singleInstance || true;
  66666. this._getPostProcesses = getPostProcesses;
  66667. this._cameras = {};
  66668. this._indicesForCamera = {};
  66669. this._postProcesses = {};
  66670. }
  66671. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66672. /**
  66673. * Checks if all the post processes in the effect are supported.
  66674. */
  66675. get: function () {
  66676. for (var index in this._postProcesses) {
  66677. for (var ppIndex in this._postProcesses[index]) {
  66678. if (!this._postProcesses[index][ppIndex].isSupported) {
  66679. return false;
  66680. }
  66681. }
  66682. }
  66683. return true;
  66684. },
  66685. enumerable: true,
  66686. configurable: true
  66687. });
  66688. /**
  66689. * Updates the current state of the effect
  66690. */
  66691. PostProcessRenderEffect.prototype._update = function () {
  66692. };
  66693. /**
  66694. * Attaches the effect on cameras
  66695. * @param cameras The camera to attach to.
  66696. */
  66697. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66698. var _this = this;
  66699. var cameraKey;
  66700. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66701. if (!cams) {
  66702. return;
  66703. }
  66704. for (var i = 0; i < cams.length; i++) {
  66705. var camera = cams[i];
  66706. var cameraName = camera.name;
  66707. if (this._singleInstance) {
  66708. cameraKey = 0;
  66709. }
  66710. else {
  66711. cameraKey = cameraName;
  66712. }
  66713. if (!this._postProcesses[cameraKey]) {
  66714. var postProcess = this._getPostProcesses();
  66715. if (postProcess) {
  66716. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66717. }
  66718. }
  66719. if (!this._indicesForCamera[cameraName]) {
  66720. this._indicesForCamera[cameraName] = [];
  66721. }
  66722. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66723. var index = camera.attachPostProcess(postProcess);
  66724. _this._indicesForCamera[cameraName].push(index);
  66725. });
  66726. if (!this._cameras[cameraName]) {
  66727. this._cameras[cameraName] = camera;
  66728. }
  66729. }
  66730. };
  66731. /**
  66732. * Detatches the effect on cameras
  66733. * @param cameras The camera to detatch from.
  66734. */
  66735. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66736. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66737. if (!cams) {
  66738. return;
  66739. }
  66740. for (var i = 0; i < cams.length; i++) {
  66741. var camera = cams[i];
  66742. var cameraName = camera.name;
  66743. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66744. camera.detachPostProcess(postProcess);
  66745. });
  66746. if (this._cameras[cameraName]) {
  66747. //this._indicesForCamera.splice(index, 1);
  66748. this._cameras[cameraName] = null;
  66749. }
  66750. }
  66751. };
  66752. /**
  66753. * Enables the effect on given cameras
  66754. * @param cameras The camera to enable.
  66755. */
  66756. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66757. var _this = this;
  66758. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66759. if (!cams) {
  66760. return;
  66761. }
  66762. for (var i = 0; i < cams.length; i++) {
  66763. var camera = cams[i];
  66764. var cameraName = camera.name;
  66765. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66766. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66767. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66768. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66769. });
  66770. }
  66771. }
  66772. }
  66773. };
  66774. /**
  66775. * Disables the effect on the given cameras
  66776. * @param cameras The camera to disable.
  66777. */
  66778. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66779. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66780. if (!cams) {
  66781. return;
  66782. }
  66783. for (var i = 0; i < cams.length; i++) {
  66784. var camera = cams[i];
  66785. var cameraName = camera.name;
  66786. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66787. camera.detachPostProcess(postProcess);
  66788. });
  66789. }
  66790. };
  66791. /**
  66792. * Gets a list of the post processes contained in the effect.
  66793. * @param camera The camera to get the post processes on.
  66794. * @returns The list of the post processes in the effect.
  66795. */
  66796. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66797. if (this._singleInstance) {
  66798. return this._postProcesses[0];
  66799. }
  66800. else {
  66801. if (!camera) {
  66802. return null;
  66803. }
  66804. return this._postProcesses[camera.name];
  66805. }
  66806. };
  66807. return PostProcessRenderEffect;
  66808. }());
  66809. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66810. })(BABYLON || (BABYLON = {}));
  66811. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66812. var BABYLON;
  66813. (function (BABYLON) {
  66814. var PostProcessRenderPipeline = /** @class */ (function () {
  66815. function PostProcessRenderPipeline(engine, name) {
  66816. this.engine = engine;
  66817. this._name = name;
  66818. this._renderEffects = {};
  66819. this._renderEffectsForIsolatedPass = new Array();
  66820. this._cameras = [];
  66821. }
  66822. PostProcessRenderPipeline.prototype.getClassName = function () {
  66823. return "PostProcessRenderPipeline";
  66824. };
  66825. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66826. get: function () {
  66827. for (var renderEffectName in this._renderEffects) {
  66828. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66829. if (!this._renderEffects[renderEffectName].isSupported) {
  66830. return false;
  66831. }
  66832. }
  66833. }
  66834. return true;
  66835. },
  66836. enumerable: true,
  66837. configurable: true
  66838. });
  66839. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66840. this._renderEffects[renderEffect._name] = renderEffect;
  66841. };
  66842. // private
  66843. PostProcessRenderPipeline.prototype._rebuild = function () {
  66844. };
  66845. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66846. var renderEffects = this._renderEffects[renderEffectName];
  66847. if (!renderEffects) {
  66848. return;
  66849. }
  66850. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66851. };
  66852. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66853. var renderEffects = this._renderEffects[renderEffectName];
  66854. if (!renderEffects) {
  66855. return;
  66856. }
  66857. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66858. };
  66859. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66860. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66861. if (!cams) {
  66862. return;
  66863. }
  66864. var indicesToDelete = [];
  66865. var i;
  66866. for (i = 0; i < cams.length; i++) {
  66867. var camera = cams[i];
  66868. var cameraName = camera.name;
  66869. if (this._cameras.indexOf(camera) === -1) {
  66870. this._cameras[cameraName] = camera;
  66871. }
  66872. else if (unique) {
  66873. indicesToDelete.push(i);
  66874. }
  66875. }
  66876. for (i = 0; i < indicesToDelete.length; i++) {
  66877. cameras.splice(indicesToDelete[i], 1);
  66878. }
  66879. for (var renderEffectName in this._renderEffects) {
  66880. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66881. this._renderEffects[renderEffectName]._attachCameras(cams);
  66882. }
  66883. }
  66884. };
  66885. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66886. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66887. if (!cams) {
  66888. return;
  66889. }
  66890. for (var renderEffectName in this._renderEffects) {
  66891. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66892. this._renderEffects[renderEffectName]._detachCameras(cams);
  66893. }
  66894. }
  66895. for (var i = 0; i < cams.length; i++) {
  66896. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66897. }
  66898. };
  66899. PostProcessRenderPipeline.prototype._update = function () {
  66900. for (var renderEffectName in this._renderEffects) {
  66901. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66902. this._renderEffects[renderEffectName]._update();
  66903. }
  66904. }
  66905. for (var i = 0; i < this._cameras.length; i++) {
  66906. var cameraName = this._cameras[i].name;
  66907. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66908. this._renderEffectsForIsolatedPass[cameraName]._update();
  66909. }
  66910. }
  66911. };
  66912. PostProcessRenderPipeline.prototype._reset = function () {
  66913. this._renderEffects = {};
  66914. this._renderEffectsForIsolatedPass = new Array();
  66915. };
  66916. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66917. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  66918. var effectKeys = Object.keys(this._renderEffects);
  66919. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66920. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66921. if (postProcesses) {
  66922. postProcesses[0].samples = 4;
  66923. return true;
  66924. }
  66925. }
  66926. return false;
  66927. };
  66928. PostProcessRenderPipeline.prototype.dispose = function () {
  66929. // Must be implemented by children
  66930. };
  66931. __decorate([
  66932. BABYLON.serialize()
  66933. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66934. return PostProcessRenderPipeline;
  66935. }());
  66936. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66937. })(BABYLON || (BABYLON = {}));
  66938. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66939. var BABYLON;
  66940. (function (BABYLON) {
  66941. /**
  66942. * This represents a depth renderer in Babylon.
  66943. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66944. */
  66945. var DepthRenderer = /** @class */ (function () {
  66946. /**
  66947. * Instantiates a depth renderer
  66948. * @param scene The scene the renderer belongs to
  66949. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66950. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66951. */
  66952. function DepthRenderer(scene, type, camera) {
  66953. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66954. if (camera === void 0) { camera = null; }
  66955. var _this = this;
  66956. this._scene = scene;
  66957. this._camera = camera;
  66958. var engine = scene.getEngine();
  66959. // Render target
  66960. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66961. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66962. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66963. this._depthMap.refreshRate = 1;
  66964. this._depthMap.renderParticles = false;
  66965. this._depthMap.renderList = null;
  66966. // Camera to get depth map from to support multiple concurrent cameras
  66967. this._depthMap.activeCamera = this._camera;
  66968. this._depthMap.ignoreCameraViewport = true;
  66969. this._depthMap.useCameraPostProcesses = false;
  66970. // set default depth value to 1.0 (far away)
  66971. this._depthMap.onClearObservable.add(function (engine) {
  66972. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66973. });
  66974. // Custom render function
  66975. var renderSubMesh = function (subMesh) {
  66976. var mesh = subMesh.getRenderingMesh();
  66977. var scene = _this._scene;
  66978. var engine = scene.getEngine();
  66979. var material = subMesh.getMaterial();
  66980. if (!material) {
  66981. return;
  66982. }
  66983. // Culling and reverse (right handed system)
  66984. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66985. // Managing instances
  66986. var batch = mesh._getInstancesRenderList(subMesh._id);
  66987. if (batch.mustReturn) {
  66988. return;
  66989. }
  66990. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66991. var camera = _this._camera || scene.activeCamera;
  66992. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66993. engine.enableEffect(_this._effect);
  66994. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66995. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66996. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66997. // Alpha test
  66998. if (material && material.needAlphaTesting()) {
  66999. var alphaTexture = material.getAlphaTestTexture();
  67000. if (alphaTexture) {
  67001. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67002. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67003. }
  67004. }
  67005. // Bones
  67006. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67007. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67008. }
  67009. // Draw
  67010. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67011. }
  67012. };
  67013. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67014. var index;
  67015. if (depthOnlySubMeshes.length) {
  67016. engine.setColorWrite(false);
  67017. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67018. renderSubMesh(depthOnlySubMeshes.data[index]);
  67019. }
  67020. engine.setColorWrite(true);
  67021. }
  67022. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67023. renderSubMesh(opaqueSubMeshes.data[index]);
  67024. }
  67025. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67026. renderSubMesh(alphaTestSubMeshes.data[index]);
  67027. }
  67028. };
  67029. }
  67030. /**
  67031. * Creates the depth rendering effect and checks if the effect is ready.
  67032. * @param subMesh The submesh to be used to render the depth map of
  67033. * @param useInstances If multiple world instances should be used
  67034. * @returns if the depth renderer is ready to render the depth map
  67035. */
  67036. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67037. var material = subMesh.getMaterial();
  67038. if (material.disableDepthWrite) {
  67039. return false;
  67040. }
  67041. var defines = [];
  67042. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67043. var mesh = subMesh.getMesh();
  67044. // Alpha test
  67045. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67046. defines.push("#define ALPHATEST");
  67047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67048. attribs.push(BABYLON.VertexBuffer.UVKind);
  67049. defines.push("#define UV1");
  67050. }
  67051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67053. defines.push("#define UV2");
  67054. }
  67055. }
  67056. // Bones
  67057. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67060. if (mesh.numBoneInfluencers > 4) {
  67061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67063. }
  67064. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67065. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67066. }
  67067. else {
  67068. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67069. }
  67070. // Instances
  67071. if (useInstances) {
  67072. defines.push("#define INSTANCES");
  67073. attribs.push("world0");
  67074. attribs.push("world1");
  67075. attribs.push("world2");
  67076. attribs.push("world3");
  67077. }
  67078. // Get correct effect
  67079. var join = defines.join("\n");
  67080. if (this._cachedDefines !== join) {
  67081. this._cachedDefines = join;
  67082. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67083. }
  67084. return this._effect.isReady();
  67085. };
  67086. /**
  67087. * Gets the texture which the depth map will be written to.
  67088. * @returns The depth map texture
  67089. */
  67090. DepthRenderer.prototype.getDepthMap = function () {
  67091. return this._depthMap;
  67092. };
  67093. /**
  67094. * Disposes of the depth renderer.
  67095. */
  67096. DepthRenderer.prototype.dispose = function () {
  67097. this._depthMap.dispose();
  67098. };
  67099. return DepthRenderer;
  67100. }());
  67101. BABYLON.DepthRenderer = DepthRenderer;
  67102. })(BABYLON || (BABYLON = {}));
  67103. //# sourceMappingURL=babylon.depthRenderer.js.map
  67104. var BABYLON;
  67105. (function (BABYLON) {
  67106. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67107. __extends(SSAORenderingPipeline, _super);
  67108. /**
  67109. * @constructor
  67110. * @param {string} name - The rendering pipeline name
  67111. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67112. * @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 }
  67113. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67114. */
  67115. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67116. var _this = _super.call(this, scene.getEngine(), name) || this;
  67117. // Members
  67118. /**
  67119. * The PassPostProcess id in the pipeline that contains the original scene color
  67120. * @type {string}
  67121. */
  67122. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67123. /**
  67124. * The SSAO PostProcess id in the pipeline
  67125. * @type {string}
  67126. */
  67127. _this.SSAORenderEffect = "SSAORenderEffect";
  67128. /**
  67129. * The horizontal blur PostProcess id in the pipeline
  67130. * @type {string}
  67131. */
  67132. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67133. /**
  67134. * The vertical blur PostProcess id in the pipeline
  67135. * @type {string}
  67136. */
  67137. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67138. /**
  67139. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67140. * @type {string}
  67141. */
  67142. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67143. /**
  67144. * The output strength of the SSAO post-process. Default value is 1.0.
  67145. * @type {number}
  67146. */
  67147. _this.totalStrength = 1.0;
  67148. /**
  67149. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67150. * @type {number}
  67151. */
  67152. _this.radius = 0.0001;
  67153. /**
  67154. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67155. * Must not be equal to fallOff and superior to fallOff.
  67156. * Default value is 0.975
  67157. * @type {number}
  67158. */
  67159. _this.area = 0.0075;
  67160. /**
  67161. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67162. * Must not be equal to area and inferior to area.
  67163. * Default value is 0.0
  67164. * @type {number}
  67165. */
  67166. _this.fallOff = 0.000001;
  67167. /**
  67168. * The base color of the SSAO post-process
  67169. * The final result is "base + ssao" between [0, 1]
  67170. * @type {number}
  67171. */
  67172. _this.base = 0.5;
  67173. _this._firstUpdate = true;
  67174. _this._scene = scene;
  67175. // Set up assets
  67176. _this._createRandomTexture();
  67177. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67178. var ssaoRatio = ratio.ssaoRatio || ratio;
  67179. var combineRatio = ratio.combineRatio || ratio;
  67180. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67181. _this._createSSAOPostProcess(ssaoRatio);
  67182. _this._createBlurPostProcess(ssaoRatio);
  67183. _this._createSSAOCombinePostProcess(combineRatio);
  67184. // Set up pipeline
  67185. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67186. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67187. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67188. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67189. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67190. // Finish
  67191. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67192. if (cameras)
  67193. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67194. return _this;
  67195. }
  67196. // Public Methods
  67197. /**
  67198. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67199. */
  67200. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67201. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67202. for (var i = 0; i < this._scene.cameras.length; i++) {
  67203. var camera = this._scene.cameras[i];
  67204. this._originalColorPostProcess.dispose(camera);
  67205. this._ssaoPostProcess.dispose(camera);
  67206. this._blurHPostProcess.dispose(camera);
  67207. this._blurVPostProcess.dispose(camera);
  67208. this._ssaoCombinePostProcess.dispose(camera);
  67209. }
  67210. this._randomTexture.dispose();
  67211. if (disableDepthRender)
  67212. this._scene.disableDepthRenderer();
  67213. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67214. _super.prototype.dispose.call(this);
  67215. };
  67216. // Private Methods
  67217. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67218. var _this = this;
  67219. var size = 16;
  67220. 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);
  67221. 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);
  67222. this._blurHPostProcess.onActivateObservable.add(function () {
  67223. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67224. _this._blurHPostProcess.kernel = size * dw;
  67225. });
  67226. this._blurVPostProcess.onActivateObservable.add(function () {
  67227. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67228. _this._blurVPostProcess.kernel = size * dw;
  67229. });
  67230. };
  67231. SSAORenderingPipeline.prototype._rebuild = function () {
  67232. this._firstUpdate = true;
  67233. _super.prototype._rebuild.call(this);
  67234. };
  67235. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67236. var _this = this;
  67237. var numSamples = 16;
  67238. var sampleSphere = [
  67239. 0.5381, 0.1856, -0.4319,
  67240. 0.1379, 0.2486, 0.4430,
  67241. 0.3371, 0.5679, -0.0057,
  67242. -0.6999, -0.0451, -0.0019,
  67243. 0.0689, -0.1598, -0.8547,
  67244. 0.0560, 0.0069, -0.1843,
  67245. -0.0146, 0.1402, 0.0762,
  67246. 0.0100, -0.1924, -0.0344,
  67247. -0.3577, -0.5301, -0.4358,
  67248. -0.3169, 0.1063, 0.0158,
  67249. 0.0103, -0.5869, 0.0046,
  67250. -0.0897, -0.4940, 0.3287,
  67251. 0.7119, -0.0154, -0.0918,
  67252. -0.0533, 0.0596, -0.5411,
  67253. 0.0352, -0.0631, 0.5460,
  67254. -0.4776, 0.2847, -0.0271
  67255. ];
  67256. var samplesFactor = 1.0 / numSamples;
  67257. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67258. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67259. "area", "fallOff", "base", "range", "viewport"
  67260. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67261. this._ssaoPostProcess.onApply = function (effect) {
  67262. if (_this._firstUpdate) {
  67263. effect.setArray3("sampleSphere", sampleSphere);
  67264. effect.setFloat("samplesFactor", samplesFactor);
  67265. effect.setFloat("randTextureTiles", 4.0);
  67266. }
  67267. effect.setFloat("totalStrength", _this.totalStrength);
  67268. effect.setFloat("radius", _this.radius);
  67269. effect.setFloat("area", _this.area);
  67270. effect.setFloat("fallOff", _this.fallOff);
  67271. effect.setFloat("base", _this.base);
  67272. effect.setTexture("textureSampler", _this._depthTexture);
  67273. effect.setTexture("randomSampler", _this._randomTexture);
  67274. };
  67275. };
  67276. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67277. var _this = this;
  67278. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67279. this._ssaoCombinePostProcess.onApply = function (effect) {
  67280. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67281. };
  67282. };
  67283. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67284. var size = 512;
  67285. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67286. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67287. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67288. var context = this._randomTexture.getContext();
  67289. var rand = function (min, max) {
  67290. return Math.random() * (max - min) + min;
  67291. };
  67292. var randVector = BABYLON.Vector3.Zero();
  67293. for (var x = 0; x < size; x++) {
  67294. for (var y = 0; y < size; y++) {
  67295. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67296. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67297. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67298. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67299. context.fillRect(x, y, 1, 1);
  67300. }
  67301. }
  67302. this._randomTexture.update(false);
  67303. };
  67304. __decorate([
  67305. BABYLON.serialize()
  67306. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67307. __decorate([
  67308. BABYLON.serialize()
  67309. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67310. __decorate([
  67311. BABYLON.serialize()
  67312. ], SSAORenderingPipeline.prototype, "area", void 0);
  67313. __decorate([
  67314. BABYLON.serialize()
  67315. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67316. __decorate([
  67317. BABYLON.serialize()
  67318. ], SSAORenderingPipeline.prototype, "base", void 0);
  67319. return SSAORenderingPipeline;
  67320. }(BABYLON.PostProcessRenderPipeline));
  67321. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67322. })(BABYLON || (BABYLON = {}));
  67323. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67324. var BABYLON;
  67325. (function (BABYLON) {
  67326. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67327. __extends(SSAO2RenderingPipeline, _super);
  67328. /**
  67329. * @constructor
  67330. * @param {string} name - The rendering pipeline name
  67331. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67332. * @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 }
  67333. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67334. */
  67335. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67336. var _this = _super.call(this, scene.getEngine(), name) || this;
  67337. // Members
  67338. /**
  67339. * The PassPostProcess id in the pipeline that contains the original scene color
  67340. * @type {string}
  67341. */
  67342. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67343. /**
  67344. * The SSAO PostProcess id in the pipeline
  67345. * @type {string}
  67346. */
  67347. _this.SSAORenderEffect = "SSAORenderEffect";
  67348. /**
  67349. * The horizontal blur PostProcess id in the pipeline
  67350. * @type {string}
  67351. */
  67352. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67353. /**
  67354. * The vertical blur PostProcess id in the pipeline
  67355. * @type {string}
  67356. */
  67357. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67358. /**
  67359. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67360. * @type {string}
  67361. */
  67362. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67363. /**
  67364. * The output strength of the SSAO post-process. Default value is 1.0.
  67365. * @type {number}
  67366. */
  67367. _this.totalStrength = 1.0;
  67368. /**
  67369. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67370. * @type {number}
  67371. */
  67372. _this.maxZ = 100.0;
  67373. /**
  67374. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67375. * @type {number}
  67376. */
  67377. _this.minZAspect = 0.2;
  67378. /**
  67379. * Number of samples used for the SSAO calculations. Default value is 8
  67380. * @type {number}
  67381. */
  67382. _this._samples = 8;
  67383. /**
  67384. * Are we using bilateral blur ?
  67385. * @type {boolean}
  67386. */
  67387. _this._expensiveBlur = true;
  67388. /**
  67389. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67390. * @type {number}
  67391. */
  67392. _this.radius = 2.0;
  67393. /**
  67394. * The base color of the SSAO post-process
  67395. * The final result is "base + ssao" between [0, 1]
  67396. * @type {number}
  67397. */
  67398. _this.base = 0.1;
  67399. _this._firstUpdate = true;
  67400. _this._scene = scene;
  67401. if (!_this.isSupported) {
  67402. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67403. return _this;
  67404. }
  67405. var ssaoRatio = ratio.ssaoRatio || ratio;
  67406. var blurRatio = ratio.blurRatio || ratio;
  67407. // Set up assets
  67408. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67409. _this._createRandomTexture();
  67410. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67411. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67412. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67413. _this._createSSAOPostProcess(1.0);
  67414. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67415. _this._createSSAOCombinePostProcess(blurRatio);
  67416. // Set up pipeline
  67417. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67418. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67419. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67420. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67421. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67422. // Finish
  67423. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67424. if (cameras)
  67425. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67426. return _this;
  67427. }
  67428. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67429. get: function () {
  67430. return this._samples;
  67431. },
  67432. set: function (n) {
  67433. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67434. this._samples = n;
  67435. this._sampleSphere = this._generateHemisphere();
  67436. this._firstUpdate = true;
  67437. },
  67438. enumerable: true,
  67439. configurable: true
  67440. });
  67441. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67442. get: function () {
  67443. return this._expensiveBlur;
  67444. },
  67445. set: function (b) {
  67446. 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"]);
  67447. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67448. this._expensiveBlur = b;
  67449. this._firstUpdate = true;
  67450. },
  67451. enumerable: true,
  67452. configurable: true
  67453. });
  67454. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67455. /**
  67456. * Support test.
  67457. * @type {boolean}
  67458. */
  67459. get: function () {
  67460. var engine = BABYLON.Engine.LastCreatedEngine;
  67461. if (!engine) {
  67462. return false;
  67463. }
  67464. return engine.getCaps().drawBuffersExtension;
  67465. },
  67466. enumerable: true,
  67467. configurable: true
  67468. });
  67469. // Public Methods
  67470. /**
  67471. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67472. */
  67473. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67474. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67475. for (var i = 0; i < this._scene.cameras.length; i++) {
  67476. var camera = this._scene.cameras[i];
  67477. this._originalColorPostProcess.dispose(camera);
  67478. this._ssaoPostProcess.dispose(camera);
  67479. this._blurHPostProcess.dispose(camera);
  67480. this._blurVPostProcess.dispose(camera);
  67481. this._ssaoCombinePostProcess.dispose(camera);
  67482. }
  67483. this._randomTexture.dispose();
  67484. if (disableGeometryBufferRenderer)
  67485. this._scene.disableGeometryBufferRenderer();
  67486. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67487. _super.prototype.dispose.call(this);
  67488. };
  67489. // Private Methods
  67490. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67491. var _this = this;
  67492. this._samplerOffsets = [];
  67493. var expensive = this.expensiveBlur;
  67494. for (var i = -8; i < 8; i++) {
  67495. this._samplerOffsets.push(i * 2 + 0.5);
  67496. }
  67497. 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");
  67498. this._blurHPostProcess.onApply = function (effect) {
  67499. if (!_this._scene.activeCamera) {
  67500. return;
  67501. }
  67502. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67503. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67504. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67505. effect.setFloat("radius", _this.radius);
  67506. effect.setTexture("depthSampler", _this._depthTexture);
  67507. if (_this._firstUpdate) {
  67508. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67509. }
  67510. };
  67511. 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");
  67512. this._blurVPostProcess.onApply = function (effect) {
  67513. if (!_this._scene.activeCamera) {
  67514. return;
  67515. }
  67516. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67517. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67518. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67519. effect.setFloat("radius", _this.radius);
  67520. effect.setTexture("depthSampler", _this._depthTexture);
  67521. if (_this._firstUpdate) {
  67522. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67523. _this._firstUpdate = false;
  67524. }
  67525. };
  67526. };
  67527. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67528. this._firstUpdate = true;
  67529. _super.prototype._rebuild.call(this);
  67530. };
  67531. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67532. var numSamples = this.samples;
  67533. var result = [];
  67534. var vector, scale;
  67535. var rand = function (min, max) {
  67536. return Math.random() * (max - min) + min;
  67537. };
  67538. var i = 0;
  67539. while (i < numSamples) {
  67540. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67541. vector.normalize();
  67542. scale = i / numSamples;
  67543. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67544. vector.scaleInPlace(scale);
  67545. result.push(vector.x, vector.y, vector.z);
  67546. i++;
  67547. }
  67548. return result;
  67549. };
  67550. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67551. var _this = this;
  67552. var numSamples = this.samples;
  67553. this._sampleSphere = this._generateHemisphere();
  67554. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67555. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67556. "base", "range", "projection", "near", "far", "texelSize",
  67557. "xViewport", "yViewport", "maxZ", "minZAspect"
  67558. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67559. this._ssaoPostProcess.onApply = function (effect) {
  67560. if (_this._firstUpdate) {
  67561. effect.setArray3("sampleSphere", _this._sampleSphere);
  67562. effect.setFloat("randTextureTiles", 4.0);
  67563. }
  67564. if (!_this._scene.activeCamera) {
  67565. return;
  67566. }
  67567. effect.setFloat("samplesFactor", 1 / _this.samples);
  67568. effect.setFloat("totalStrength", _this.totalStrength);
  67569. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67570. effect.setFloat("radius", _this.radius);
  67571. effect.setFloat("maxZ", _this.maxZ);
  67572. effect.setFloat("minZAspect", _this.minZAspect);
  67573. effect.setFloat("base", _this.base);
  67574. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67575. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67576. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67577. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67578. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67579. effect.setTexture("textureSampler", _this._depthTexture);
  67580. effect.setTexture("normalSampler", _this._normalTexture);
  67581. effect.setTexture("randomSampler", _this._randomTexture);
  67582. };
  67583. };
  67584. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67585. var _this = this;
  67586. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67587. this._ssaoCombinePostProcess.onApply = function (effect) {
  67588. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67589. };
  67590. };
  67591. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67592. var size = 512;
  67593. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67594. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67595. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67596. var context = this._randomTexture.getContext();
  67597. var rand = function (min, max) {
  67598. return Math.random() * (max - min) + min;
  67599. };
  67600. var randVector = BABYLON.Vector3.Zero();
  67601. for (var x = 0; x < size; x++) {
  67602. for (var y = 0; y < size; y++) {
  67603. randVector.x = rand(0.0, 1.0);
  67604. randVector.y = rand(0.0, 1.0);
  67605. randVector.z = 0.0;
  67606. randVector.normalize();
  67607. randVector.scaleInPlace(255);
  67608. randVector.x = Math.floor(randVector.x);
  67609. randVector.y = Math.floor(randVector.y);
  67610. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67611. context.fillRect(x, y, 1, 1);
  67612. }
  67613. }
  67614. this._randomTexture.update(false);
  67615. };
  67616. __decorate([
  67617. BABYLON.serialize()
  67618. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67619. __decorate([
  67620. BABYLON.serialize()
  67621. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67622. __decorate([
  67623. BABYLON.serialize()
  67624. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67625. __decorate([
  67626. BABYLON.serialize("samples")
  67627. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67628. __decorate([
  67629. BABYLON.serialize("expensiveBlur")
  67630. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67631. __decorate([
  67632. BABYLON.serialize()
  67633. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67634. __decorate([
  67635. BABYLON.serialize()
  67636. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67637. return SSAO2RenderingPipeline;
  67638. }(BABYLON.PostProcessRenderPipeline));
  67639. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67640. })(BABYLON || (BABYLON = {}));
  67641. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67642. // BABYLON.JS Chromatic Aberration GLSL Shader
  67643. // Author: Olivier Guyot
  67644. // Separates very slightly R, G and B colors on the edges of the screen
  67645. // Inspired by Francois Tarlier & Martins Upitis
  67646. var BABYLON;
  67647. (function (BABYLON) {
  67648. var LensRenderingPipeline = /** @class */ (function (_super) {
  67649. __extends(LensRenderingPipeline, _super);
  67650. /**
  67651. * @constructor
  67652. *
  67653. * Effect parameters are as follow:
  67654. * {
  67655. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67656. * edge_blur: number; // from 0 to x (1 for realism)
  67657. * distortion: number; // from 0 to x (1 for realism)
  67658. * grain_amount: number; // from 0 to 1
  67659. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67660. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67661. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67662. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67663. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67664. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67665. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67666. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67667. * }
  67668. * Note: if an effect parameter is unset, effect is disabled
  67669. *
  67670. * @param {string} name - The rendering pipeline name
  67671. * @param {object} parameters - An object containing all parameters (see above)
  67672. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67673. * @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)
  67674. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67675. */
  67676. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67677. if (ratio === void 0) { ratio = 1.0; }
  67678. var _this = _super.call(this, scene.getEngine(), name) || this;
  67679. // Lens effects can be of the following:
  67680. // - chromatic aberration (slight shift of RGB colors)
  67681. // - blur on the edge of the lens
  67682. // - lens distortion
  67683. // - depth-of-field blur & highlights enhancing
  67684. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67685. // - grain effect (noise or custom texture)
  67686. // Two additional texture samplers are needed:
  67687. // - depth map (for depth-of-field)
  67688. // - grain texture
  67689. /**
  67690. * The chromatic aberration PostProcess id in the pipeline
  67691. * @type {string}
  67692. */
  67693. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67694. /**
  67695. * The highlights enhancing PostProcess id in the pipeline
  67696. * @type {string}
  67697. */
  67698. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67699. /**
  67700. * The depth-of-field PostProcess id in the pipeline
  67701. * @type {string}
  67702. */
  67703. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67704. _this._scene = scene;
  67705. // Fetch texture samplers
  67706. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67707. if (parameters.grain_texture) {
  67708. _this._grainTexture = parameters.grain_texture;
  67709. }
  67710. else {
  67711. _this._createGrainTexture();
  67712. }
  67713. // save parameters
  67714. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67715. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67716. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67717. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67718. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67719. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67720. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67721. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67722. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67723. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67724. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67725. // Create effects
  67726. _this._createChromaticAberrationPostProcess(ratio);
  67727. _this._createHighlightsPostProcess(ratio);
  67728. _this._createDepthOfFieldPostProcess(ratio / 4);
  67729. // Set up pipeline
  67730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67731. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67732. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67733. if (_this._highlightsGain === -1) {
  67734. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67735. }
  67736. // Finish
  67737. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67738. if (cameras) {
  67739. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67740. }
  67741. return _this;
  67742. }
  67743. // public methods (self explanatory)
  67744. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67745. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67746. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67747. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67748. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67749. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67750. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67751. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67752. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67753. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67754. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67755. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67756. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67757. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67758. };
  67759. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67760. this._highlightsPostProcess.updateEffect();
  67761. };
  67762. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67763. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67764. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67765. this._highlightsGain = amount;
  67766. };
  67767. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67768. if (this._highlightsGain === -1) {
  67769. this._highlightsGain = 1.0;
  67770. }
  67771. this._highlightsThreshold = amount;
  67772. };
  67773. LensRenderingPipeline.prototype.disableHighlights = function () {
  67774. this._highlightsGain = -1;
  67775. };
  67776. /**
  67777. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67778. */
  67779. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67780. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67781. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67782. this._chromaticAberrationPostProcess = null;
  67783. this._highlightsPostProcess = null;
  67784. this._depthOfFieldPostProcess = null;
  67785. this._grainTexture.dispose();
  67786. if (disableDepthRender)
  67787. this._scene.disableDepthRenderer();
  67788. };
  67789. // colors shifting and distortion
  67790. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67791. var _this = this;
  67792. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67793. [], // samplers
  67794. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67795. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67796. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67797. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67798. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67799. effect.setFloat('radialIntensity', 1);
  67800. effect.setFloat2('direction', 17, 17);
  67801. effect.setFloat2('centerPosition', 0.5, 0.5);
  67802. };
  67803. };
  67804. // highlights enhancing
  67805. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67806. var _this = this;
  67807. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67808. [], // samplers
  67809. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67810. this._highlightsPostProcess.onApply = function (effect) {
  67811. effect.setFloat('gain', _this._highlightsGain);
  67812. effect.setFloat('threshold', _this._highlightsThreshold);
  67813. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67814. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67815. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67816. };
  67817. };
  67818. // colors shifting and distortion
  67819. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67820. var _this = this;
  67821. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67822. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67823. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67824. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67825. this._depthOfFieldPostProcess.onApply = function (effect) {
  67826. effect.setTexture("depthSampler", _this._depthTexture);
  67827. effect.setTexture("grainSampler", _this._grainTexture);
  67828. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67829. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67830. effect.setFloat('grain_amount', _this._grainAmount);
  67831. effect.setBool('blur_noise', _this._blurNoise);
  67832. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67833. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67834. effect.setFloat('distortion', _this._distortion);
  67835. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67836. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67837. effect.setFloat('aperture', _this._dofAperture);
  67838. effect.setFloat('darken', _this._dofDarken);
  67839. effect.setFloat('edge_blur', _this._edgeBlur);
  67840. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67841. if (_this._scene.activeCamera) {
  67842. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67843. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67844. }
  67845. };
  67846. };
  67847. // creates a black and white random noise texture, 512x512
  67848. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67849. var size = 512;
  67850. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67851. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67852. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67853. var context = this._grainTexture.getContext();
  67854. var rand = function (min, max) {
  67855. return Math.random() * (max - min) + min;
  67856. };
  67857. var value;
  67858. for (var x = 0; x < size; x++) {
  67859. for (var y = 0; y < size; y++) {
  67860. value = Math.floor(rand(0.42, 0.58) * 255);
  67861. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67862. context.fillRect(x, y, 1, 1);
  67863. }
  67864. }
  67865. this._grainTexture.update(false);
  67866. };
  67867. return LensRenderingPipeline;
  67868. }(BABYLON.PostProcessRenderPipeline));
  67869. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67870. })(BABYLON || (BABYLON = {}));
  67871. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67872. var BABYLON;
  67873. (function (BABYLON) {
  67874. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67875. __extends(StandardRenderingPipeline, _super);
  67876. /**
  67877. * @constructor
  67878. * @param {string} name - The rendering pipeline name
  67879. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67880. * @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)
  67881. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67882. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67883. */
  67884. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67885. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67886. var _this = _super.call(this, scene.getEngine(), name) || this;
  67887. _this.downSampleX4PostProcess = null;
  67888. _this.brightPassPostProcess = null;
  67889. _this.blurHPostProcesses = [];
  67890. _this.blurVPostProcesses = [];
  67891. _this.textureAdderPostProcess = null;
  67892. _this.volumetricLightPostProcess = null;
  67893. _this.volumetricLightSmoothXPostProcess = null;
  67894. _this.volumetricLightSmoothYPostProcess = null;
  67895. _this.volumetricLightMergePostProces = null;
  67896. _this.volumetricLightFinalPostProcess = null;
  67897. _this.luminancePostProcess = null;
  67898. _this.luminanceDownSamplePostProcesses = [];
  67899. _this.hdrPostProcess = null;
  67900. _this.textureAdderFinalPostProcess = null;
  67901. _this.lensFlareFinalPostProcess = null;
  67902. _this.hdrFinalPostProcess = null;
  67903. _this.lensFlarePostProcess = null;
  67904. _this.lensFlareComposePostProcess = null;
  67905. _this.motionBlurPostProcess = null;
  67906. _this.depthOfFieldPostProcess = null;
  67907. // Values
  67908. _this.brightThreshold = 1.0;
  67909. _this.blurWidth = 512.0;
  67910. _this.horizontalBlur = false;
  67911. _this.exposure = 1.0;
  67912. _this.lensTexture = null;
  67913. _this.volumetricLightCoefficient = 0.2;
  67914. _this.volumetricLightPower = 4.0;
  67915. _this.volumetricLightBlurScale = 64.0;
  67916. _this.sourceLight = null;
  67917. _this.hdrMinimumLuminance = 1.0;
  67918. _this.hdrDecreaseRate = 0.5;
  67919. _this.hdrIncreaseRate = 0.5;
  67920. _this.lensColorTexture = null;
  67921. _this.lensFlareStrength = 20.0;
  67922. _this.lensFlareGhostDispersal = 1.4;
  67923. _this.lensFlareHaloWidth = 0.7;
  67924. _this.lensFlareDistortionStrength = 16.0;
  67925. _this.lensStarTexture = null;
  67926. _this.lensFlareDirtTexture = null;
  67927. _this.depthOfFieldDistance = 10.0;
  67928. _this.depthOfFieldBlurWidth = 64.0;
  67929. _this.motionStrength = 1.0;
  67930. // IAnimatable
  67931. _this.animations = [];
  67932. _this._currentDepthOfFieldSource = null;
  67933. _this._hdrCurrentLuminance = 1.0;
  67934. // Getters and setters
  67935. _this._bloomEnabled = true;
  67936. _this._depthOfFieldEnabled = false;
  67937. _this._vlsEnabled = false;
  67938. _this._lensFlareEnabled = false;
  67939. _this._hdrEnabled = false;
  67940. _this._motionBlurEnabled = false;
  67941. _this._motionBlurSamples = 64.0;
  67942. _this._volumetricLightStepsCount = 50.0;
  67943. _this._cameras = cameras || [];
  67944. // Initialize
  67945. _this._scene = scene;
  67946. _this._basePostProcess = originalPostProcess;
  67947. _this._ratio = ratio;
  67948. // Misc
  67949. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67950. // Finish
  67951. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67952. _this._buildPipeline();
  67953. return _this;
  67954. }
  67955. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67956. get: function () {
  67957. return this._bloomEnabled;
  67958. },
  67959. set: function (enabled) {
  67960. if (this._bloomEnabled === enabled) {
  67961. return;
  67962. }
  67963. this._bloomEnabled = enabled;
  67964. this._buildPipeline();
  67965. },
  67966. enumerable: true,
  67967. configurable: true
  67968. });
  67969. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67970. get: function () {
  67971. return this._depthOfFieldEnabled;
  67972. },
  67973. set: function (enabled) {
  67974. if (this._depthOfFieldEnabled === enabled) {
  67975. return;
  67976. }
  67977. this._depthOfFieldEnabled = enabled;
  67978. this._buildPipeline();
  67979. },
  67980. enumerable: true,
  67981. configurable: true
  67982. });
  67983. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67984. get: function () {
  67985. return this._lensFlareEnabled;
  67986. },
  67987. set: function (enabled) {
  67988. if (this._lensFlareEnabled === enabled) {
  67989. return;
  67990. }
  67991. this._lensFlareEnabled = enabled;
  67992. this._buildPipeline();
  67993. },
  67994. enumerable: true,
  67995. configurable: true
  67996. });
  67997. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67998. get: function () {
  67999. return this._hdrEnabled;
  68000. },
  68001. set: function (enabled) {
  68002. if (this._hdrEnabled === enabled) {
  68003. return;
  68004. }
  68005. this._hdrEnabled = enabled;
  68006. this._buildPipeline();
  68007. },
  68008. enumerable: true,
  68009. configurable: true
  68010. });
  68011. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68012. get: function () {
  68013. return this._vlsEnabled;
  68014. },
  68015. set: function (enabled) {
  68016. if (this._vlsEnabled === enabled) {
  68017. return;
  68018. }
  68019. if (enabled) {
  68020. var geometry = this._scene.enableGeometryBufferRenderer();
  68021. if (!geometry) {
  68022. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68023. return;
  68024. }
  68025. }
  68026. this._vlsEnabled = enabled;
  68027. this._buildPipeline();
  68028. },
  68029. enumerable: true,
  68030. configurable: true
  68031. });
  68032. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68033. get: function () {
  68034. return this._motionBlurEnabled;
  68035. },
  68036. set: function (enabled) {
  68037. if (this._motionBlurEnabled === enabled) {
  68038. return;
  68039. }
  68040. this._motionBlurEnabled = enabled;
  68041. this._buildPipeline();
  68042. },
  68043. enumerable: true,
  68044. configurable: true
  68045. });
  68046. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68047. get: function () {
  68048. return this._volumetricLightStepsCount;
  68049. },
  68050. set: function (count) {
  68051. if (this.volumetricLightPostProcess) {
  68052. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68053. }
  68054. this._volumetricLightStepsCount = count;
  68055. },
  68056. enumerable: true,
  68057. configurable: true
  68058. });
  68059. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68060. get: function () {
  68061. return this._motionBlurSamples;
  68062. },
  68063. set: function (samples) {
  68064. if (this.motionBlurPostProcess) {
  68065. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68066. }
  68067. this._motionBlurSamples = samples;
  68068. },
  68069. enumerable: true,
  68070. configurable: true
  68071. });
  68072. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68073. var _this = this;
  68074. var ratio = this._ratio;
  68075. var scene = this._scene;
  68076. this._disposePostProcesses();
  68077. this._reset();
  68078. // Create pass post-process
  68079. if (!this._basePostProcess) {
  68080. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68081. this.originalPostProcess.onApply = function (effect) {
  68082. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68083. };
  68084. }
  68085. else {
  68086. this.originalPostProcess = this._basePostProcess;
  68087. }
  68088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68089. this._currentDepthOfFieldSource = this.originalPostProcess;
  68090. if (this._vlsEnabled) {
  68091. // Create volumetric light
  68092. this._createVolumetricLightPostProcess(scene, ratio);
  68093. // Create volumetric light final post-process
  68094. 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);
  68095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68096. }
  68097. if (this._bloomEnabled) {
  68098. // Create down sample X4 post-process
  68099. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68100. // Create bright pass post-process
  68101. this._createBrightPassPostProcess(scene, ratio / 2);
  68102. // Create gaussian blur post-processes (down sampling blurs)
  68103. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68104. // Create texture adder post-process
  68105. this._createTextureAdderPostProcess(scene, ratio);
  68106. // Create depth-of-field source post-process
  68107. 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);
  68108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68109. }
  68110. if (this._lensFlareEnabled) {
  68111. // Create lens flare post-process
  68112. this._createLensFlarePostProcess(scene, ratio);
  68113. // Create depth-of-field source post-process post lens-flare and disable it now
  68114. 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);
  68115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68116. }
  68117. if (this._hdrEnabled) {
  68118. // Create luminance
  68119. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68120. // Create HDR
  68121. this._createHdrPostProcess(scene, ratio);
  68122. // Create depth-of-field source post-process post hdr and disable it now
  68123. 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);
  68124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68125. }
  68126. if (this._depthOfFieldEnabled) {
  68127. // Create gaussian blur used by depth-of-field
  68128. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68129. // Create depth-of-field post-process
  68130. this._createDepthOfFieldPostProcess(scene, ratio);
  68131. }
  68132. if (this._motionBlurEnabled) {
  68133. // Create motion blur post-process
  68134. this._createMotionBlurPostProcess(scene, ratio);
  68135. }
  68136. if (this._cameras !== null) {
  68137. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68138. }
  68139. };
  68140. // Down Sample X4 Post-Processs
  68141. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68142. var _this = this;
  68143. var downSampleX4Offsets = new Array(32);
  68144. 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);
  68145. this.downSampleX4PostProcess.onApply = function (effect) {
  68146. var id = 0;
  68147. var width = _this.downSampleX4PostProcess.width;
  68148. var height = _this.downSampleX4PostProcess.height;
  68149. for (var i = -2; i < 2; i++) {
  68150. for (var j = -2; j < 2; j++) {
  68151. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68152. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68153. id += 2;
  68154. }
  68155. }
  68156. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68157. };
  68158. // Add to pipeline
  68159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68160. };
  68161. // Brightpass Post-Process
  68162. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68163. var _this = this;
  68164. var brightOffsets = new Array(8);
  68165. 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);
  68166. this.brightPassPostProcess.onApply = function (effect) {
  68167. var sU = (1.0 / _this.brightPassPostProcess.width);
  68168. var sV = (1.0 / _this.brightPassPostProcess.height);
  68169. brightOffsets[0] = -0.5 * sU;
  68170. brightOffsets[1] = 0.5 * sV;
  68171. brightOffsets[2] = 0.5 * sU;
  68172. brightOffsets[3] = 0.5 * sV;
  68173. brightOffsets[4] = -0.5 * sU;
  68174. brightOffsets[5] = -0.5 * sV;
  68175. brightOffsets[6] = 0.5 * sU;
  68176. brightOffsets[7] = -0.5 * sV;
  68177. effect.setArray2("dsOffsets", brightOffsets);
  68178. effect.setFloat("brightThreshold", _this.brightThreshold);
  68179. };
  68180. // Add to pipeline
  68181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68182. };
  68183. // Create blur H&V post-processes
  68184. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68185. var _this = this;
  68186. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68187. var engine = scene.getEngine();
  68188. 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);
  68189. 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);
  68190. blurX.onActivateObservable.add(function () {
  68191. var dw = blurX.width / engine.getRenderWidth();
  68192. blurX.kernel = _this[blurWidthKey] * dw;
  68193. });
  68194. blurY.onActivateObservable.add(function () {
  68195. var dw = blurY.height / engine.getRenderHeight();
  68196. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68197. });
  68198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68200. this.blurHPostProcesses.push(blurX);
  68201. this.blurVPostProcesses.push(blurY);
  68202. };
  68203. // Create texture adder post-process
  68204. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68205. var _this = this;
  68206. 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);
  68207. this.textureAdderPostProcess.onApply = function (effect) {
  68208. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68209. effect.setTexture("lensSampler", _this.lensTexture);
  68210. effect.setFloat("exposure", _this.exposure);
  68211. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68212. };
  68213. // Add to pipeline
  68214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68215. };
  68216. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68217. var _this = this;
  68218. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68219. geometryRenderer.enablePosition = true;
  68220. var geometry = geometryRenderer.getGBuffer();
  68221. // Base post-process
  68222. 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));
  68223. var depthValues = BABYLON.Vector2.Zero();
  68224. this.volumetricLightPostProcess.onApply = function (effect) {
  68225. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68226. var generator = _this.sourceLight.getShadowGenerator();
  68227. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68228. effect.setTexture("positionSampler", geometry.textures[2]);
  68229. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68230. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68231. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68232. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68233. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68234. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68235. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68236. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68237. effect.setVector2("depthValues", depthValues);
  68238. }
  68239. };
  68240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68241. // Smooth
  68242. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68243. // Merge
  68244. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68245. this.volumetricLightMergePostProces.onApply = function (effect) {
  68246. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68247. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68248. };
  68249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68250. };
  68251. // Create luminance
  68252. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68253. var _this = this;
  68254. // Create luminance
  68255. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68256. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68257. var offsets = [];
  68258. this.luminancePostProcess.onApply = function (effect) {
  68259. var sU = (1.0 / _this.luminancePostProcess.width);
  68260. var sV = (1.0 / _this.luminancePostProcess.height);
  68261. offsets[0] = -0.5 * sU;
  68262. offsets[1] = 0.5 * sV;
  68263. offsets[2] = 0.5 * sU;
  68264. offsets[3] = 0.5 * sV;
  68265. offsets[4] = -0.5 * sU;
  68266. offsets[5] = -0.5 * sV;
  68267. offsets[6] = 0.5 * sU;
  68268. offsets[7] = -0.5 * sV;
  68269. effect.setArray2("lumOffsets", offsets);
  68270. };
  68271. // Add to pipeline
  68272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68273. // Create down sample luminance
  68274. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68275. var size = Math.pow(3, i);
  68276. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68277. if (i === 0) {
  68278. defines += "#define FINAL_DOWN_SAMPLER";
  68279. }
  68280. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68281. this.luminanceDownSamplePostProcesses.push(postProcess);
  68282. }
  68283. // Create callbacks and add effects
  68284. var lastLuminance = this.luminancePostProcess;
  68285. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68286. var downSampleOffsets = new Array(18);
  68287. pp.onApply = function (effect) {
  68288. if (!lastLuminance) {
  68289. return;
  68290. }
  68291. var id = 0;
  68292. for (var x = -1; x < 2; x++) {
  68293. for (var y = -1; y < 2; y++) {
  68294. downSampleOffsets[id] = x / lastLuminance.width;
  68295. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68296. id += 2;
  68297. }
  68298. }
  68299. effect.setArray2("dsOffsets", downSampleOffsets);
  68300. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68301. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68302. lastLuminance = _this.luminancePostProcess;
  68303. }
  68304. else {
  68305. lastLuminance = pp;
  68306. }
  68307. };
  68308. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68309. pp.onAfterRender = function (effect) {
  68310. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68311. 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);
  68312. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68313. };
  68314. }
  68315. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68316. });
  68317. };
  68318. // Create HDR post-process
  68319. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68320. var _this = this;
  68321. 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);
  68322. var outputLiminance = 1;
  68323. var time = 0;
  68324. var lastTime = 0;
  68325. this.hdrPostProcess.onApply = function (effect) {
  68326. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68327. time += scene.getEngine().getDeltaTime();
  68328. if (outputLiminance < 0) {
  68329. outputLiminance = _this._hdrCurrentLuminance;
  68330. }
  68331. else {
  68332. var dt = (lastTime - time) / 1000.0;
  68333. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68334. outputLiminance += _this.hdrDecreaseRate * dt;
  68335. }
  68336. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68337. outputLiminance -= _this.hdrIncreaseRate * dt;
  68338. }
  68339. else {
  68340. outputLiminance = _this._hdrCurrentLuminance;
  68341. }
  68342. }
  68343. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68344. effect.setFloat("averageLuminance", outputLiminance);
  68345. lastTime = time;
  68346. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68347. };
  68348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68349. };
  68350. // Create lens flare post-process
  68351. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68352. var _this = this;
  68353. 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);
  68354. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68355. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68356. 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);
  68357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68358. var resolution = new BABYLON.Vector2(0, 0);
  68359. // Lens flare
  68360. this.lensFlarePostProcess.onApply = function (effect) {
  68361. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68362. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68363. effect.setFloat("strength", _this.lensFlareStrength);
  68364. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68365. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68366. // Shift
  68367. resolution.x = _this.lensFlarePostProcess.width;
  68368. resolution.y = _this.lensFlarePostProcess.height;
  68369. effect.setVector2("resolution", resolution);
  68370. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68371. };
  68372. // Compose
  68373. 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);
  68374. 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);
  68375. this.lensFlareComposePostProcess.onApply = function (effect) {
  68376. if (!_this._scene.activeCamera) {
  68377. return;
  68378. }
  68379. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68380. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68381. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68382. // Lens start rotation matrix
  68383. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68384. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68385. 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));
  68386. camRot *= 4.0;
  68387. 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);
  68388. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68389. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68390. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68391. };
  68392. };
  68393. // Create depth-of-field post-process
  68394. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68395. var _this = this;
  68396. 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);
  68397. this.depthOfFieldPostProcess.onApply = function (effect) {
  68398. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68399. effect.setTexture("depthSampler", _this._getDepthTexture());
  68400. effect.setFloat("distance", _this.depthOfFieldDistance);
  68401. };
  68402. // Add to pipeline
  68403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68404. };
  68405. // Create motion blur post-process
  68406. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68407. var _this = this;
  68408. 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);
  68409. var motionScale = 0;
  68410. var prevViewProjection = BABYLON.Matrix.Identity();
  68411. var invViewProjection = BABYLON.Matrix.Identity();
  68412. var viewProjection = BABYLON.Matrix.Identity();
  68413. var screenSize = BABYLON.Vector2.Zero();
  68414. this.motionBlurPostProcess.onApply = function (effect) {
  68415. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68416. viewProjection.invertToRef(invViewProjection);
  68417. effect.setMatrix("inverseViewProjection", invViewProjection);
  68418. effect.setMatrix("prevViewProjection", prevViewProjection);
  68419. prevViewProjection = viewProjection;
  68420. screenSize.x = _this.motionBlurPostProcess.width;
  68421. screenSize.y = _this.motionBlurPostProcess.height;
  68422. effect.setVector2("screenSize", screenSize);
  68423. motionScale = scene.getEngine().getFps() / 60.0;
  68424. effect.setFloat("motionScale", motionScale);
  68425. effect.setFloat("motionStrength", _this.motionStrength);
  68426. effect.setTexture("depthSampler", _this._getDepthTexture());
  68427. };
  68428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68429. };
  68430. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68431. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68432. var renderer = this._scene.enableGeometryBufferRenderer();
  68433. return renderer.getGBuffer().textures[0];
  68434. }
  68435. return this._scene.enableDepthRenderer().getDepthMap();
  68436. };
  68437. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68438. for (var i = 0; i < this._cameras.length; i++) {
  68439. var camera = this._cameras[i];
  68440. if (this.originalPostProcess) {
  68441. this.originalPostProcess.dispose(camera);
  68442. }
  68443. if (this.downSampleX4PostProcess) {
  68444. this.downSampleX4PostProcess.dispose(camera);
  68445. }
  68446. if (this.brightPassPostProcess) {
  68447. this.brightPassPostProcess.dispose(camera);
  68448. }
  68449. if (this.textureAdderPostProcess) {
  68450. this.textureAdderPostProcess.dispose(camera);
  68451. }
  68452. if (this.textureAdderFinalPostProcess) {
  68453. this.textureAdderFinalPostProcess.dispose(camera);
  68454. }
  68455. if (this.volumetricLightPostProcess) {
  68456. this.volumetricLightPostProcess.dispose(camera);
  68457. }
  68458. if (this.volumetricLightSmoothXPostProcess) {
  68459. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68460. }
  68461. if (this.volumetricLightSmoothYPostProcess) {
  68462. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68463. }
  68464. if (this.volumetricLightMergePostProces) {
  68465. this.volumetricLightMergePostProces.dispose(camera);
  68466. }
  68467. if (this.volumetricLightFinalPostProcess) {
  68468. this.volumetricLightFinalPostProcess.dispose(camera);
  68469. }
  68470. if (this.lensFlarePostProcess) {
  68471. this.lensFlarePostProcess.dispose(camera);
  68472. }
  68473. if (this.lensFlareComposePostProcess) {
  68474. this.lensFlareComposePostProcess.dispose(camera);
  68475. }
  68476. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68477. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68478. }
  68479. if (this.luminancePostProcess) {
  68480. this.luminancePostProcess.dispose(camera);
  68481. }
  68482. if (this.hdrPostProcess) {
  68483. this.hdrPostProcess.dispose(camera);
  68484. }
  68485. if (this.hdrFinalPostProcess) {
  68486. this.hdrFinalPostProcess.dispose(camera);
  68487. }
  68488. if (this.depthOfFieldPostProcess) {
  68489. this.depthOfFieldPostProcess.dispose(camera);
  68490. }
  68491. if (this.motionBlurPostProcess) {
  68492. this.motionBlurPostProcess.dispose(camera);
  68493. }
  68494. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68495. this.blurHPostProcesses[j].dispose(camera);
  68496. }
  68497. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68498. this.blurVPostProcesses[j].dispose(camera);
  68499. }
  68500. }
  68501. this.originalPostProcess = null;
  68502. this.downSampleX4PostProcess = null;
  68503. this.brightPassPostProcess = null;
  68504. this.textureAdderPostProcess = null;
  68505. this.textureAdderFinalPostProcess = null;
  68506. this.volumetricLightPostProcess = null;
  68507. this.volumetricLightSmoothXPostProcess = null;
  68508. this.volumetricLightSmoothYPostProcess = null;
  68509. this.volumetricLightMergePostProces = null;
  68510. this.volumetricLightFinalPostProcess = null;
  68511. this.lensFlarePostProcess = null;
  68512. this.lensFlareComposePostProcess = null;
  68513. this.luminancePostProcess = null;
  68514. this.hdrPostProcess = null;
  68515. this.hdrFinalPostProcess = null;
  68516. this.depthOfFieldPostProcess = null;
  68517. this.motionBlurPostProcess = null;
  68518. this.luminanceDownSamplePostProcesses = [];
  68519. this.blurHPostProcesses = [];
  68520. this.blurVPostProcesses = [];
  68521. };
  68522. // Dispose
  68523. StandardRenderingPipeline.prototype.dispose = function () {
  68524. this._disposePostProcesses();
  68525. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68526. _super.prototype.dispose.call(this);
  68527. };
  68528. // Serialize rendering pipeline
  68529. StandardRenderingPipeline.prototype.serialize = function () {
  68530. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68531. serializationObject.customType = "StandardRenderingPipeline";
  68532. return serializationObject;
  68533. };
  68534. /**
  68535. * Static members
  68536. */
  68537. // Parse serialized pipeline
  68538. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68539. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68540. };
  68541. // Luminance steps
  68542. StandardRenderingPipeline.LuminanceSteps = 6;
  68543. __decorate([
  68544. BABYLON.serialize()
  68545. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68546. __decorate([
  68547. BABYLON.serialize()
  68548. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68549. __decorate([
  68550. BABYLON.serialize()
  68551. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68552. __decorate([
  68553. BABYLON.serialize()
  68554. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68555. __decorate([
  68556. BABYLON.serializeAsTexture("lensTexture")
  68557. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68558. __decorate([
  68559. BABYLON.serialize()
  68560. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68561. __decorate([
  68562. BABYLON.serialize()
  68563. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68564. __decorate([
  68565. BABYLON.serialize()
  68566. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68567. __decorate([
  68568. BABYLON.serialize()
  68569. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68570. __decorate([
  68571. BABYLON.serialize()
  68572. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68573. __decorate([
  68574. BABYLON.serialize()
  68575. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68576. __decorate([
  68577. BABYLON.serializeAsTexture("lensColorTexture")
  68578. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68579. __decorate([
  68580. BABYLON.serialize()
  68581. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68582. __decorate([
  68583. BABYLON.serialize()
  68584. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68585. __decorate([
  68586. BABYLON.serialize()
  68587. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68588. __decorate([
  68589. BABYLON.serialize()
  68590. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68591. __decorate([
  68592. BABYLON.serializeAsTexture("lensStarTexture")
  68593. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68594. __decorate([
  68595. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68596. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68597. __decorate([
  68598. BABYLON.serialize()
  68599. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68600. __decorate([
  68601. BABYLON.serialize()
  68602. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68603. __decorate([
  68604. BABYLON.serialize()
  68605. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68606. __decorate([
  68607. BABYLON.serialize()
  68608. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68609. __decorate([
  68610. BABYLON.serialize()
  68611. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68612. __decorate([
  68613. BABYLON.serialize()
  68614. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68615. __decorate([
  68616. BABYLON.serialize()
  68617. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68618. __decorate([
  68619. BABYLON.serialize()
  68620. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68621. __decorate([
  68622. BABYLON.serialize()
  68623. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68624. __decorate([
  68625. BABYLON.serialize()
  68626. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68627. __decorate([
  68628. BABYLON.serialize()
  68629. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68630. __decorate([
  68631. BABYLON.serialize()
  68632. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68633. return StandardRenderingPipeline;
  68634. }(BABYLON.PostProcessRenderPipeline));
  68635. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68636. })(BABYLON || (BABYLON = {}));
  68637. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68638. var BABYLON;
  68639. (function (BABYLON) {
  68640. var FxaaPostProcess = /** @class */ (function (_super) {
  68641. __extends(FxaaPostProcess, _super);
  68642. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68643. if (camera === void 0) { camera = null; }
  68644. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68645. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68646. _this.onApplyObservable.add(function (effect) {
  68647. var texelSize = _this.texelSize;
  68648. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68649. });
  68650. return _this;
  68651. }
  68652. return FxaaPostProcess;
  68653. }(BABYLON.PostProcess));
  68654. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68655. })(BABYLON || (BABYLON = {}));
  68656. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68657. var BABYLON;
  68658. (function (BABYLON) {
  68659. /**
  68660. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68661. */
  68662. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68663. __extends(ChromaticAberrationPostProcess, _super);
  68664. /**
  68665. * Creates a new instance of @see ChromaticAberrationPostProcess
  68666. * @param name The name of the effect.
  68667. * @param screenWidth The width of the screen to apply the effect on.
  68668. * @param screenHeight The height of the screen to apply the effect on.
  68669. * @param options The required width/height ratio to downsize to before computing the render pass.
  68670. * @param camera The camera to apply the render pass to.
  68671. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68672. * @param engine The engine which the post process will be applied. (default: current engine)
  68673. * @param reusable If the post process can be reused on the same frame. (default: false)
  68674. * @param textureType Type of textures used when performing the post process. (default: 0)
  68675. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68676. */
  68677. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68678. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68679. if (blockCompilation === void 0) { blockCompilation = false; }
  68680. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68681. /**
  68682. * The amount of seperation of rgb channels (default: 0)
  68683. */
  68684. _this.aberrationAmount = 0;
  68685. /**
  68686. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68687. */
  68688. _this.radialIntensity = 0;
  68689. /**
  68690. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  68691. */
  68692. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68693. /**
  68694. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  68695. */
  68696. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68697. _this.onApplyObservable.add(function (effect) {
  68698. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68699. effect.setFloat('screen_width', screenWidth);
  68700. effect.setFloat('screen_height', screenHeight);
  68701. effect.setFloat('radialIntensity', _this.radialIntensity);
  68702. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68703. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68704. });
  68705. return _this;
  68706. }
  68707. return ChromaticAberrationPostProcess;
  68708. }(BABYLON.PostProcess));
  68709. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68710. })(BABYLON || (BABYLON = {}));
  68711. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68712. var BABYLON;
  68713. (function (BABYLON) {
  68714. /**
  68715. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68716. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68717. */
  68718. var SharpenPostProcess = /** @class */ (function (_super) {
  68719. __extends(SharpenPostProcess, _super);
  68720. /**
  68721. * Creates a new instance of @see ConvolutionPostProcess
  68722. * @param name The name of the effect.
  68723. * @param options The required width/height ratio to downsize to before computing the render pass.
  68724. * @param camera The camera to apply the render pass to.
  68725. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68726. * @param engine The engine which the post process will be applied. (default: current engine)
  68727. * @param reusable If the post process can be reused on the same frame. (default: false)
  68728. * @param textureType Type of textures used when performing the post process. (default: 0)
  68729. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68730. */
  68731. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68733. if (blockCompilation === void 0) { blockCompilation = false; }
  68734. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68735. /**
  68736. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68737. */
  68738. _this.colorAmount = 1.0;
  68739. /**
  68740. * How much sharpness should be applied (default: 0.3)
  68741. */
  68742. _this.edgeAmount = 0.3;
  68743. _this.onApply = function (effect) {
  68744. effect.setFloat2("screenSize", _this.width, _this.height);
  68745. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68746. };
  68747. return _this;
  68748. }
  68749. return SharpenPostProcess;
  68750. }(BABYLON.PostProcess));
  68751. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68752. })(BABYLON || (BABYLON = {}));
  68753. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68754. var BABYLON;
  68755. (function (BABYLON) {
  68756. /**
  68757. * The Blur Post Process which blurs an image based on a kernel and direction.
  68758. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68759. */
  68760. var BlurPostProcess = /** @class */ (function (_super) {
  68761. __extends(BlurPostProcess, _super);
  68762. /**
  68763. * Creates a new instance of @see BlurPostProcess
  68764. * @param name The name of the effect.
  68765. * @param direction The direction in which to blur the image.
  68766. * @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.
  68767. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68768. * @param camera The camera to apply the render pass to.
  68769. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68770. * @param engine The engine which the post process will be applied. (default: current engine)
  68771. * @param reusable If the post process can be reused on the same frame. (default: false)
  68772. * @param textureType Type of textures used when performing the post process. (default: 0)
  68773. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68774. */
  68775. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68777. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68778. if (defines === void 0) { defines = ""; }
  68779. if (blockCompilation === void 0) { blockCompilation = false; }
  68780. 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;
  68781. _this.direction = direction;
  68782. _this.blockCompilation = blockCompilation;
  68783. _this._packedFloat = false;
  68784. _this._staticDefines = "";
  68785. _this._staticDefines = defines;
  68786. _this.onApplyObservable.add(function (effect) {
  68787. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68788. });
  68789. _this.kernel = kernel;
  68790. return _this;
  68791. }
  68792. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68793. /**
  68794. * Gets the length in pixels of the blur sample region
  68795. */
  68796. get: function () {
  68797. return this._idealKernel;
  68798. },
  68799. /**
  68800. * Sets the length in pixels of the blur sample region
  68801. */
  68802. set: function (v) {
  68803. if (this._idealKernel === v) {
  68804. return;
  68805. }
  68806. v = Math.max(v, 1);
  68807. this._idealKernel = v;
  68808. this._kernel = this._nearestBestKernel(v);
  68809. if (!this.blockCompilation) {
  68810. this._updateParameters();
  68811. }
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68817. /**
  68818. * Gets wether or not the blur is unpacking/repacking floats
  68819. */
  68820. get: function () {
  68821. return this._packedFloat;
  68822. },
  68823. /**
  68824. * Sets wether or not the blur needs to unpack/repack floats
  68825. */
  68826. set: function (v) {
  68827. if (this._packedFloat === v) {
  68828. return;
  68829. }
  68830. this._packedFloat = v;
  68831. if (!this.blockCompilation) {
  68832. this._updateParameters();
  68833. }
  68834. },
  68835. enumerable: true,
  68836. configurable: true
  68837. });
  68838. /**
  68839. * Updates the effect with the current post process compile time values and recompiles the shader.
  68840. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68841. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68842. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68843. * @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
  68844. * @param onCompiled Called when the shader has been compiled.
  68845. * @param onError Called if there is an error when compiling a shader.
  68846. */
  68847. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68848. if (defines === void 0) { defines = null; }
  68849. if (uniforms === void 0) { uniforms = null; }
  68850. if (samplers === void 0) { samplers = null; }
  68851. this._updateParameters(onCompiled, onError);
  68852. };
  68853. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68854. // Generate sampling offsets and weights
  68855. var N = this._kernel;
  68856. var centerIndex = (N - 1) / 2;
  68857. // Generate Gaussian sampling weights over kernel
  68858. var offsets = [];
  68859. var weights = [];
  68860. var totalWeight = 0;
  68861. for (var i = 0; i < N; i++) {
  68862. var u = i / (N - 1);
  68863. var w = this._gaussianWeight(u * 2.0 - 1);
  68864. offsets[i] = (i - centerIndex);
  68865. weights[i] = w;
  68866. totalWeight += w;
  68867. }
  68868. // Normalize weights
  68869. for (var i = 0; i < weights.length; i++) {
  68870. weights[i] /= totalWeight;
  68871. }
  68872. // Optimize: combine samples to take advantage of hardware linear sampling
  68873. // Walk from left to center, combining pairs (symmetrically)
  68874. var linearSamplingWeights = [];
  68875. var linearSamplingOffsets = [];
  68876. var linearSamplingMap = [];
  68877. for (var i = 0; i <= centerIndex; i += 2) {
  68878. var j = Math.min(i + 1, Math.floor(centerIndex));
  68879. var singleCenterSample = i === j;
  68880. if (singleCenterSample) {
  68881. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68882. }
  68883. else {
  68884. var sharedCell = j === centerIndex;
  68885. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68886. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68887. if (offsetLinear === 0) {
  68888. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68889. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68890. }
  68891. else {
  68892. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68893. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68894. }
  68895. }
  68896. }
  68897. for (var i = 0; i < linearSamplingMap.length; i++) {
  68898. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68899. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68900. }
  68901. // Replace with optimized
  68902. offsets = linearSamplingOffsets;
  68903. weights = linearSamplingWeights;
  68904. // Generate shaders
  68905. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68906. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68907. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68908. var defines = "";
  68909. defines += this._staticDefines;
  68910. for (var i = 0; i < varyingCount; i++) {
  68911. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68912. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68913. }
  68914. var depCount = 0;
  68915. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68916. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68917. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68918. depCount++;
  68919. }
  68920. if (this.packedFloat) {
  68921. defines += "#define PACKEDFLOAT 1";
  68922. }
  68923. _super.prototype.updateEffect.call(this, defines, null, null, {
  68924. varyingCount: varyingCount,
  68925. depCount: depCount
  68926. }, onCompiled, onError);
  68927. };
  68928. /**
  68929. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68930. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68931. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68932. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68933. * The gaps between physical kernels are compensated for in the weighting of the samples
  68934. * @param idealKernel Ideal blur kernel.
  68935. * @return Nearest best kernel.
  68936. */
  68937. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68938. var v = Math.round(idealKernel);
  68939. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68940. var k = _a[_i];
  68941. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68942. return Math.max(k, 3);
  68943. }
  68944. }
  68945. return Math.max(v, 3);
  68946. };
  68947. /**
  68948. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68949. * @param x The point on the Gaussian distribution to sample.
  68950. * @return the value of the Gaussian function at x.
  68951. */
  68952. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68953. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68954. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68955. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68956. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68957. // truncated at around 1.3% of peak strength.
  68958. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68959. var sigma = (1 / 3);
  68960. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68961. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68962. var weight = (1.0 / denominator) * Math.exp(exponent);
  68963. return weight;
  68964. };
  68965. /**
  68966. * Generates a string that can be used as a floating point number in GLSL.
  68967. * @param x Value to print.
  68968. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68969. * @return GLSL float string.
  68970. */
  68971. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68972. if (decimalFigures === void 0) { decimalFigures = 8; }
  68973. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68974. };
  68975. return BlurPostProcess;
  68976. }(BABYLON.PostProcess));
  68977. BABYLON.BlurPostProcess = BlurPostProcess;
  68978. })(BABYLON || (BABYLON = {}));
  68979. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68980. var BABYLON;
  68981. (function (BABYLON) {
  68982. /**
  68983. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68984. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68985. * based on samples that have a large difference in distance than the center pixel.
  68986. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68987. */
  68988. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68989. __extends(DepthOfFieldBlurPostProcess, _super);
  68990. /**
  68991. * Creates a new instance of @see CircleOfConfusionPostProcess
  68992. * @param name The name of the effect.
  68993. * @param scene The scene the effect belongs to.
  68994. * @param direction The direction the blur should be applied.
  68995. * @param kernel The size of the kernel used to blur.
  68996. * @param options The required width/height ratio to downsize to before computing the render pass.
  68997. * @param camera The camera to apply the render pass to.
  68998. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68999. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69000. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69001. * @param engine The engine which the post process will be applied. (default: current engine)
  69002. * @param reusable If the post process can be reused on the same frame. (default: false)
  69003. * @param textureType Type of textures used when performing the post process. (default: 0)
  69004. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69005. */
  69006. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69007. if (imageToBlur === void 0) { imageToBlur = null; }
  69008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69009. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69010. if (blockCompilation === void 0) { blockCompilation = false; }
  69011. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69012. _this.direction = direction;
  69013. _this.onApplyObservable.add(function (effect) {
  69014. if (imageToBlur != null) {
  69015. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69016. }
  69017. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69018. if (scene.activeCamera) {
  69019. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69020. }
  69021. });
  69022. return _this;
  69023. }
  69024. return DepthOfFieldBlurPostProcess;
  69025. }(BABYLON.BlurPostProcess));
  69026. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69027. })(BABYLON || (BABYLON = {}));
  69028. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69029. var BABYLON;
  69030. (function (BABYLON) {
  69031. /**
  69032. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69033. */
  69034. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69035. __extends(DepthOfFieldMergePostProcess, _super);
  69036. /**
  69037. * Creates a new instance of @see CircleOfConfusionPostProcess
  69038. * @param name The name of the effect.
  69039. * @param original The non-blurred image to be modified
  69040. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69041. * @param blurSteps Incrimental bluring post processes.
  69042. * @param options The required width/height ratio to downsize to before computing the render pass.
  69043. * @param camera The camera to apply the render pass to.
  69044. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69045. * @param engine The engine which the post process will be applied. (default: current engine)
  69046. * @param reusable If the post process can be reused on the same frame. (default: false)
  69047. * @param textureType Type of textures used when performing the post process. (default: 0)
  69048. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69049. */
  69050. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69052. if (blockCompilation === void 0) { blockCompilation = false; }
  69053. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69054. _this.blurSteps = blurSteps;
  69055. _this.onApplyObservable.add(function (effect) {
  69056. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69057. effect.setTextureFromPostProcess("originalSampler", original);
  69058. blurSteps.forEach(function (step, index) {
  69059. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69060. });
  69061. });
  69062. if (!blockCompilation) {
  69063. _this.updateEffect();
  69064. }
  69065. return _this;
  69066. }
  69067. /**
  69068. * Updates the effect with the current post process compile time values and recompiles the shader.
  69069. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69070. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69071. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69072. * @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
  69073. * @param onCompiled Called when the shader has been compiled.
  69074. * @param onError Called if there is an error when compiling a shader.
  69075. */
  69076. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69077. if (defines === void 0) { defines = null; }
  69078. if (uniforms === void 0) { uniforms = null; }
  69079. if (samplers === void 0) { samplers = null; }
  69080. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69081. };
  69082. return DepthOfFieldMergePostProcess;
  69083. }(BABYLON.PostProcess));
  69084. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69085. })(BABYLON || (BABYLON = {}));
  69086. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69087. var BABYLON;
  69088. (function (BABYLON) {
  69089. /**
  69090. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69091. */
  69092. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69093. __extends(CircleOfConfusionPostProcess, _super);
  69094. /**
  69095. * Creates a new instance of @see CircleOfConfusionPostProcess
  69096. * @param name The name of the effect.
  69097. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69098. * @param options The required width/height ratio to downsize to before computing the render pass.
  69099. * @param camera The camera to apply the render pass to.
  69100. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69101. * @param engine The engine which the post process will be applied. (default: current engine)
  69102. * @param reusable If the post process can be reused on the same frame. (default: false)
  69103. * @param textureType Type of textures used when performing the post process. (default: 0)
  69104. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69105. */
  69106. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69107. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69108. if (blockCompilation === void 0) { blockCompilation = false; }
  69109. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69110. /**
  69111. * 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.
  69112. */
  69113. _this.lensSize = 50;
  69114. /**
  69115. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69116. */
  69117. _this.fStop = 1.4;
  69118. /**
  69119. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69120. */
  69121. _this.focusDistance = 2000;
  69122. /**
  69123. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69124. */
  69125. _this.focalLength = 50;
  69126. _this._depthTexture = null;
  69127. _this._depthTexture = depthTexture;
  69128. _this.onApplyObservable.add(function (effect) {
  69129. if (!_this._depthTexture) {
  69130. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69131. return;
  69132. }
  69133. effect.setTexture("depthSampler", _this._depthTexture);
  69134. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69135. var aperture = _this.lensSize / _this.fStop;
  69136. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69137. effect.setFloat('focusDistance', _this.focusDistance);
  69138. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69139. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69140. });
  69141. return _this;
  69142. }
  69143. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69144. /**
  69145. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69146. */
  69147. set: function (value) {
  69148. this._depthTexture = value;
  69149. },
  69150. enumerable: true,
  69151. configurable: true
  69152. });
  69153. return CircleOfConfusionPostProcess;
  69154. }(BABYLON.PostProcess));
  69155. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69156. })(BABYLON || (BABYLON = {}));
  69157. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69158. var BABYLON;
  69159. (function (BABYLON) {
  69160. /**
  69161. * Specifies the level of max blur that should be applied when using the depth of field effect
  69162. */
  69163. var DepthOfFieldEffectBlurLevel;
  69164. (function (DepthOfFieldEffectBlurLevel) {
  69165. /**
  69166. * Subtle blur
  69167. */
  69168. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69169. /**
  69170. * Medium blur
  69171. */
  69172. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69173. /**
  69174. * Large blur
  69175. */
  69176. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69177. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69178. ;
  69179. /**
  69180. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69181. */
  69182. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69183. __extends(DepthOfFieldEffect, _super);
  69184. /**
  69185. * Creates a new instance of @see DepthOfFieldEffect
  69186. * @param scene The scene the effect belongs to.
  69187. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69188. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69189. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69190. */
  69191. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69192. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69193. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69194. if (blockCompilation === void 0) { blockCompilation = false; }
  69195. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69196. return _this._effects;
  69197. }, true) || this;
  69198. _this._effects = [];
  69199. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69200. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69201. // Capture circle of confusion texture
  69202. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69203. _this._depthOfFieldPass.autoClear = false;
  69204. // 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)
  69205. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69206. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69207. _this._depthOfFieldBlurY = [];
  69208. _this._depthOfFieldBlurX = [];
  69209. var blurCount = 1;
  69210. var kernelSize = 15;
  69211. switch (blurLevel) {
  69212. case DepthOfFieldEffectBlurLevel.High: {
  69213. blurCount = 3;
  69214. kernelSize = 51;
  69215. break;
  69216. }
  69217. case DepthOfFieldEffectBlurLevel.Medium: {
  69218. blurCount = 2;
  69219. kernelSize = 31;
  69220. break;
  69221. }
  69222. default: {
  69223. kernelSize = 15;
  69224. blurCount = 1;
  69225. break;
  69226. }
  69227. }
  69228. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69229. for (var i = 0; i < blurCount; i++) {
  69230. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69231. blurY.autoClear = false;
  69232. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69233. blurX.autoClear = false;
  69234. _this._depthOfFieldBlurY.push(blurY);
  69235. _this._depthOfFieldBlurX.push(blurX);
  69236. }
  69237. // Merge blurred images with original image based on circleOfConfusion
  69238. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69239. _this._depthOfFieldMerge.autoClear = false;
  69240. // Set all post processes on the effect.
  69241. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69242. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69243. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69244. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69245. }
  69246. _this._effects.push(_this._depthOfFieldMerge);
  69247. return _this;
  69248. }
  69249. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69250. get: function () {
  69251. return this._circleOfConfusion.focalLength;
  69252. },
  69253. /**
  69254. * The focal the length of the camera used in the effect
  69255. */
  69256. set: function (value) {
  69257. this._circleOfConfusion.focalLength = value;
  69258. },
  69259. enumerable: true,
  69260. configurable: true
  69261. });
  69262. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69263. get: function () {
  69264. return this._circleOfConfusion.fStop;
  69265. },
  69266. /**
  69267. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69268. */
  69269. set: function (value) {
  69270. this._circleOfConfusion.fStop = value;
  69271. },
  69272. enumerable: true,
  69273. configurable: true
  69274. });
  69275. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69276. get: function () {
  69277. return this._circleOfConfusion.focusDistance;
  69278. },
  69279. /**
  69280. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69281. */
  69282. set: function (value) {
  69283. this._circleOfConfusion.focusDistance = value;
  69284. },
  69285. enumerable: true,
  69286. configurable: true
  69287. });
  69288. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69289. get: function () {
  69290. return this._circleOfConfusion.lensSize;
  69291. },
  69292. /**
  69293. * 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.
  69294. */
  69295. set: function (value) {
  69296. this._circleOfConfusion.lensSize = value;
  69297. },
  69298. enumerable: true,
  69299. configurable: true
  69300. });
  69301. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69302. /**
  69303. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69304. */
  69305. set: function (value) {
  69306. this._circleOfConfusion.depthTexture = value;
  69307. },
  69308. enumerable: true,
  69309. configurable: true
  69310. });
  69311. /**
  69312. * Disposes each of the internal effects for a given camera.
  69313. * @param camera The camera to dispose the effect on.
  69314. */
  69315. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69316. this._depthOfFieldPass.dispose(camera);
  69317. this._circleOfConfusion.dispose(camera);
  69318. this._depthOfFieldBlurX.forEach(function (element) {
  69319. element.dispose(camera);
  69320. });
  69321. this._depthOfFieldBlurY.forEach(function (element) {
  69322. element.dispose(camera);
  69323. });
  69324. this._depthOfFieldMerge.dispose(camera);
  69325. };
  69326. /**
  69327. * Internal
  69328. */
  69329. DepthOfFieldEffect.prototype._updateEffects = function () {
  69330. for (var effect in this._effects) {
  69331. this._effects[effect].updateEffect();
  69332. }
  69333. };
  69334. /**
  69335. * Internal
  69336. * @returns if all the contained post processes are ready.
  69337. */
  69338. DepthOfFieldEffect.prototype._isReady = function () {
  69339. for (var effect in this._effects) {
  69340. if (!this._effects[effect].isReady()) {
  69341. return false;
  69342. }
  69343. }
  69344. return true;
  69345. };
  69346. return DepthOfFieldEffect;
  69347. }(BABYLON.PostProcessRenderEffect));
  69348. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69349. })(BABYLON || (BABYLON = {}));
  69350. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69351. var BABYLON;
  69352. (function (BABYLON) {
  69353. /**
  69354. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69355. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69356. */
  69357. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69358. __extends(DefaultRenderingPipeline, _super);
  69359. /**
  69360. * @constructor
  69361. * @param {string} name - The rendering pipeline name
  69362. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69363. * @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)
  69364. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69365. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69366. */
  69367. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69368. if (automaticBuild === void 0) { automaticBuild = true; }
  69369. var _this = _super.call(this, scene.getEngine(), name) || this;
  69370. _this._originalCameras = [];
  69371. /**
  69372. * ID of the sharpen post process,
  69373. */
  69374. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69375. /**
  69376. * ID of the pass post process used for bloom,
  69377. */
  69378. _this.PassPostProcessId = "PassPostProcessEffect";
  69379. /**
  69380. * ID of the highlight post process used for bloom,
  69381. */
  69382. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69383. /**
  69384. * ID of the blurX post process used for bloom,
  69385. */
  69386. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69387. /**
  69388. * ID of the blurY post process used for bloom,
  69389. */
  69390. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69391. /**
  69392. * ID of the copy back post process used for bloom,
  69393. */
  69394. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69395. /**
  69396. * ID of the image processing post process;
  69397. */
  69398. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69399. /**
  69400. * ID of the Fast Approximate Anti-Aliasing post process;
  69401. */
  69402. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69403. /**
  69404. * ID of the final merge post process;
  69405. */
  69406. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69407. /**
  69408. * ID of the chromatic aberration post process,
  69409. */
  69410. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69411. /**
  69412. * Animations which can be used to tweak settings over a period of time
  69413. */
  69414. _this.animations = [];
  69415. // Values
  69416. _this._sharpenEnabled = false;
  69417. _this._bloomEnabled = false;
  69418. _this._depthOfFieldEnabled = false;
  69419. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69420. _this._fxaaEnabled = false;
  69421. _this._msaaEnabled = false;
  69422. _this._imageProcessingEnabled = true;
  69423. _this._bloomScale = 0.6;
  69424. _this._chromaticAberrationEnabled = false;
  69425. _this._buildAllowed = true;
  69426. /**
  69427. * Specifies the size of the bloom blur kernel, relative to the final output size
  69428. */
  69429. _this.bloomKernel = 64;
  69430. /**
  69431. * Specifies the weight of the bloom in the final rendering
  69432. */
  69433. _this._bloomWeight = 0.15;
  69434. _this._prevPostProcess = null;
  69435. _this._prevPrevPostProcess = null;
  69436. _this._cameras = cameras || [];
  69437. _this._originalCameras = _this._cameras.slice();
  69438. _this._buildAllowed = automaticBuild;
  69439. // Initialize
  69440. _this._scene = scene;
  69441. var caps = _this._scene.getEngine().getCaps();
  69442. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69443. // Misc
  69444. if (_this._hdr) {
  69445. if (caps.textureHalfFloatRender) {
  69446. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69447. }
  69448. else if (caps.textureFloatRender) {
  69449. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69450. }
  69451. }
  69452. else {
  69453. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69454. }
  69455. // Attach
  69456. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69457. var engine = _this._scene.getEngine();
  69458. // Create post processes before hand so they can be modified before enabled.
  69459. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69460. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69461. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69462. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69463. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69464. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69465. _this._buildPipeline();
  69466. return _this;
  69467. }
  69468. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69469. get: function () {
  69470. return this._sharpenEnabled;
  69471. },
  69472. /**
  69473. * Enable or disable the sharpen process from the pipeline
  69474. */
  69475. set: function (enabled) {
  69476. if (this._sharpenEnabled === enabled) {
  69477. return;
  69478. }
  69479. this._sharpenEnabled = enabled;
  69480. this._buildPipeline();
  69481. },
  69482. enumerable: true,
  69483. configurable: true
  69484. });
  69485. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69486. get: function () {
  69487. return this._bloomWeight;
  69488. },
  69489. /**
  69490. * The strength of the bloom.
  69491. */
  69492. set: function (value) {
  69493. if (this._bloomWeight === value) {
  69494. return;
  69495. }
  69496. this._bloomWeight = value;
  69497. if (this._hdr && this.copyBack) {
  69498. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69499. }
  69500. },
  69501. enumerable: true,
  69502. configurable: true
  69503. });
  69504. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69505. get: function () {
  69506. return this._bloomScale;
  69507. },
  69508. /**
  69509. * The scale of the bloom, lower value will provide better performance.
  69510. */
  69511. set: function (value) {
  69512. if (this._bloomScale === value) {
  69513. return;
  69514. }
  69515. this._bloomScale = value;
  69516. this._buildPipeline();
  69517. },
  69518. enumerable: true,
  69519. configurable: true
  69520. });
  69521. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69522. get: function () {
  69523. return this._bloomEnabled;
  69524. },
  69525. /**
  69526. * Enable or disable the bloom from the pipeline
  69527. */
  69528. set: function (enabled) {
  69529. if (this._bloomEnabled === enabled) {
  69530. return;
  69531. }
  69532. this._bloomEnabled = enabled;
  69533. this._buildPipeline();
  69534. },
  69535. enumerable: true,
  69536. configurable: true
  69537. });
  69538. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69539. /**
  69540. * If the depth of field is enabled.
  69541. */
  69542. get: function () {
  69543. return this._depthOfFieldEnabled;
  69544. },
  69545. set: function (enabled) {
  69546. if (this._depthOfFieldEnabled === enabled) {
  69547. return;
  69548. }
  69549. this._depthOfFieldEnabled = enabled;
  69550. this._buildPipeline();
  69551. },
  69552. enumerable: true,
  69553. configurable: true
  69554. });
  69555. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69556. /**
  69557. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69558. */
  69559. get: function () {
  69560. return this._depthOfFieldBlurLevel;
  69561. },
  69562. set: function (value) {
  69563. if (this._depthOfFieldBlurLevel === value) {
  69564. return;
  69565. }
  69566. this._depthOfFieldBlurLevel = value;
  69567. // recreate dof and dispose old as this setting is not dynamic
  69568. var oldDof = this.depthOfField;
  69569. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69570. this.depthOfField.focalLength = oldDof.focalLength;
  69571. this.depthOfField.focusDistance = oldDof.focusDistance;
  69572. this.depthOfField.fStop = oldDof.fStop;
  69573. this.depthOfField.lensSize = oldDof.lensSize;
  69574. for (var i = 0; i < this._cameras.length; i++) {
  69575. oldDof.disposeEffects(this._cameras[i]);
  69576. }
  69577. this._buildPipeline();
  69578. },
  69579. enumerable: true,
  69580. configurable: true
  69581. });
  69582. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69583. get: function () {
  69584. return this._fxaaEnabled;
  69585. },
  69586. /**
  69587. * If the anti aliasing is enabled.
  69588. */
  69589. set: function (enabled) {
  69590. if (this._fxaaEnabled === enabled) {
  69591. return;
  69592. }
  69593. this._fxaaEnabled = enabled;
  69594. this._buildPipeline();
  69595. },
  69596. enumerable: true,
  69597. configurable: true
  69598. });
  69599. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69600. get: function () {
  69601. return this._msaaEnabled;
  69602. },
  69603. /**
  69604. * If the multisample anti-aliasing is enabled.
  69605. */
  69606. set: function (enabled) {
  69607. if (this._msaaEnabled === enabled) {
  69608. return;
  69609. }
  69610. this._msaaEnabled = enabled;
  69611. this._buildPipeline();
  69612. },
  69613. enumerable: true,
  69614. configurable: true
  69615. });
  69616. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69617. get: function () {
  69618. return this._imageProcessingEnabled;
  69619. },
  69620. /**
  69621. * If image processing is enabled.
  69622. */
  69623. set: function (enabled) {
  69624. if (this._imageProcessingEnabled === enabled) {
  69625. return;
  69626. }
  69627. this._imageProcessingEnabled = enabled;
  69628. this._buildPipeline();
  69629. },
  69630. enumerable: true,
  69631. configurable: true
  69632. });
  69633. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69634. get: function () {
  69635. return this._chromaticAberrationEnabled;
  69636. },
  69637. /**
  69638. * Enable or disable the chromaticAberration process from the pipeline
  69639. */
  69640. set: function (enabled) {
  69641. if (this._chromaticAberrationEnabled === enabled) {
  69642. return;
  69643. }
  69644. this._chromaticAberrationEnabled = enabled;
  69645. this._buildPipeline();
  69646. },
  69647. enumerable: true,
  69648. configurable: true
  69649. });
  69650. /**
  69651. * Force the compilation of the entire pipeline.
  69652. */
  69653. DefaultRenderingPipeline.prototype.prepare = function () {
  69654. var previousState = this._buildAllowed;
  69655. this._buildAllowed = true;
  69656. this._buildPipeline();
  69657. this._buildAllowed = previousState;
  69658. };
  69659. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69660. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69661. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69662. postProcess.autoClear = false;
  69663. }
  69664. else {
  69665. postProcess.autoClear = true;
  69666. }
  69667. if (!skipTextureSharing) {
  69668. if (this._prevPrevPostProcess) {
  69669. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69670. }
  69671. else {
  69672. postProcess.useOwnOutput();
  69673. }
  69674. if (this._prevPostProcess) {
  69675. this._prevPrevPostProcess = this._prevPostProcess;
  69676. }
  69677. this._prevPostProcess = postProcess;
  69678. }
  69679. };
  69680. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69681. var _this = this;
  69682. if (!this._buildAllowed) {
  69683. return;
  69684. }
  69685. var engine = this._scene.getEngine();
  69686. this._disposePostProcesses();
  69687. if (this._cameras !== null) {
  69688. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69689. // get back cameras to be used to reattach pipeline
  69690. this._cameras = this._originalCameras.slice();
  69691. }
  69692. this._reset();
  69693. this._prevPostProcess = null;
  69694. this._prevPrevPostProcess = null;
  69695. if (this.sharpenEnabled) {
  69696. if (!this.sharpen.isReady()) {
  69697. this.sharpen.updateEffect();
  69698. }
  69699. this.addEffect(this._sharpenEffect);
  69700. this._setAutoClearAndTextureSharing(this.sharpen);
  69701. }
  69702. if (this.depthOfFieldEnabled) {
  69703. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69704. this.depthOfField.depthTexture = depthTexture;
  69705. if (!this.depthOfField._isReady()) {
  69706. this.depthOfField._updateEffects();
  69707. }
  69708. this.addEffect(this.depthOfField);
  69709. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69710. }
  69711. if (this.bloomEnabled) {
  69712. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69713. this._setAutoClearAndTextureSharing(this.pass, true);
  69714. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69715. if (!this._hdr) {
  69716. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69717. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69718. this.highlights.autoClear = false;
  69719. this.highlights.alwaysForcePOT = true;
  69720. }
  69721. 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);
  69722. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69723. this.blurX.alwaysForcePOT = true;
  69724. this.blurX.autoClear = false;
  69725. this.blurX.onActivateObservable.add(function () {
  69726. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69727. _this.blurX.kernel = _this.bloomKernel * dw;
  69728. });
  69729. 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);
  69730. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69731. this.blurY.alwaysForcePOT = true;
  69732. this.blurY.autoClear = false;
  69733. this.blurY.onActivateObservable.add(function () {
  69734. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69735. _this.blurY.kernel = _this.bloomKernel * dh;
  69736. });
  69737. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69738. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69739. this.copyBack.alwaysForcePOT = true;
  69740. if (this._hdr) {
  69741. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69742. var w = this.bloomWeight;
  69743. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69744. }
  69745. else {
  69746. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69747. }
  69748. this.copyBack.autoClear = false;
  69749. }
  69750. if (this._imageProcessingEnabled) {
  69751. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69752. if (this._hdr) {
  69753. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69754. }
  69755. else {
  69756. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69757. }
  69758. }
  69759. if (this._hdr && this.imageProcessing) {
  69760. this.finalMerge = this.imageProcessing;
  69761. }
  69762. else {
  69763. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69764. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69765. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69766. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69767. }
  69768. if (this.bloomEnabled) {
  69769. if (this._hdr) {
  69770. this.copyBack.shareOutputWith(this.blurX);
  69771. if (this.imageProcessing) {
  69772. this.imageProcessing.shareOutputWith(this.pass);
  69773. this.imageProcessing.autoClear = false;
  69774. }
  69775. else {
  69776. this.finalMerge.shareOutputWith(this.pass);
  69777. }
  69778. }
  69779. else {
  69780. this.finalMerge.shareOutputWith(this.pass);
  69781. }
  69782. }
  69783. if (this.fxaaEnabled) {
  69784. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69785. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69786. this._setAutoClearAndTextureSharing(this.fxaa);
  69787. }
  69788. if (this.chromaticAberrationEnabled) {
  69789. if (!this.chromaticAberration.isReady()) {
  69790. this.chromaticAberration.updateEffect();
  69791. }
  69792. this.addEffect(this._chromaticAberrationEffect);
  69793. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69794. }
  69795. if (this._cameras !== null) {
  69796. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69797. }
  69798. if (this.msaaEnabled) {
  69799. if (!this._enableMSAAOnFirstPostProcess()) {
  69800. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69801. }
  69802. }
  69803. };
  69804. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69805. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69806. for (var i = 0; i < this._cameras.length; i++) {
  69807. var camera = this._cameras[i];
  69808. if (this.pass) {
  69809. this.pass.dispose(camera);
  69810. }
  69811. if (this.highlights) {
  69812. this.highlights.dispose(camera);
  69813. }
  69814. if (this.blurX) {
  69815. this.blurX.dispose(camera);
  69816. }
  69817. if (this.blurY) {
  69818. this.blurY.dispose(camera);
  69819. }
  69820. if (this.copyBack) {
  69821. this.copyBack.dispose(camera);
  69822. }
  69823. if (this.imageProcessing) {
  69824. this.imageProcessing.dispose(camera);
  69825. }
  69826. if (this.fxaa) {
  69827. this.fxaa.dispose(camera);
  69828. }
  69829. if (this.finalMerge) {
  69830. this.finalMerge.dispose(camera);
  69831. }
  69832. // These are created in the constructor and should not be disposed on every pipeline change
  69833. if (disposeNonRecreated) {
  69834. if (this.sharpen) {
  69835. this.sharpen.dispose(camera);
  69836. }
  69837. if (this.depthOfField) {
  69838. this.depthOfField.disposeEffects(camera);
  69839. }
  69840. if (this.chromaticAberration) {
  69841. this.chromaticAberration.dispose(camera);
  69842. }
  69843. }
  69844. }
  69845. this.pass = null;
  69846. this.highlights = null;
  69847. this.blurX = null;
  69848. this.blurY = null;
  69849. this.copyBack = null;
  69850. this.imageProcessing = null;
  69851. this.fxaa = null;
  69852. this.finalMerge = null;
  69853. if (disposeNonRecreated) {
  69854. this.sharpen = null;
  69855. this.depthOfField = null;
  69856. this.chromaticAberration = null;
  69857. }
  69858. };
  69859. /**
  69860. * Dispose of the pipeline and stop all post processes
  69861. */
  69862. DefaultRenderingPipeline.prototype.dispose = function () {
  69863. this._disposePostProcesses(true);
  69864. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69865. _super.prototype.dispose.call(this);
  69866. };
  69867. /**
  69868. * Serialize the rendering pipeline (Used when exporting)
  69869. * @returns the serialized object
  69870. */
  69871. DefaultRenderingPipeline.prototype.serialize = function () {
  69872. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69873. serializationObject.customType = "DefaultRenderingPipeline";
  69874. return serializationObject;
  69875. };
  69876. /**
  69877. * Parse the serialized pipeline
  69878. * @param source Source pipeline.
  69879. * @param scene The scene to load the pipeline to.
  69880. * @param rootUrl The URL of the serialized pipeline.
  69881. * @returns An instantiated pipeline from the serialized object.
  69882. */
  69883. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69884. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69885. };
  69886. __decorate([
  69887. BABYLON.serialize()
  69888. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69889. __decorate([
  69890. BABYLON.serialize()
  69891. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69892. __decorate([
  69893. BABYLON.serialize()
  69894. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69895. __decorate([
  69896. BABYLON.serialize()
  69897. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69898. __decorate([
  69899. BABYLON.serialize()
  69900. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69901. __decorate([
  69902. BABYLON.serialize()
  69903. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69904. __decorate([
  69905. BABYLON.serialize()
  69906. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69907. __decorate([
  69908. BABYLON.serialize()
  69909. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69910. __decorate([
  69911. BABYLON.serialize()
  69912. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69913. __decorate([
  69914. BABYLON.serialize()
  69915. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69916. __decorate([
  69917. BABYLON.serialize()
  69918. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69919. __decorate([
  69920. BABYLON.serialize()
  69921. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69922. __decorate([
  69923. BABYLON.serialize()
  69924. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69925. return DefaultRenderingPipeline;
  69926. }(BABYLON.PostProcessRenderPipeline));
  69927. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69928. })(BABYLON || (BABYLON = {}));
  69929. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69930. var BABYLON;
  69931. (function (BABYLON) {
  69932. /**
  69933. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69934. */
  69935. var GeometryBufferRenderer = /** @class */ (function () {
  69936. /**
  69937. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69938. * @param scene The scene the buffer belongs to
  69939. * @param ratio How big is the buffer related to the main canvas.
  69940. */
  69941. function GeometryBufferRenderer(scene, ratio) {
  69942. if (ratio === void 0) { ratio = 1; }
  69943. this._enablePosition = false;
  69944. this._scene = scene;
  69945. this._ratio = ratio;
  69946. // Render target
  69947. this._createRenderTargets();
  69948. }
  69949. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69950. /**
  69951. * Set the render list (meshes to be rendered) used in the G buffer.
  69952. */
  69953. set: function (meshes) {
  69954. this._multiRenderTarget.renderList = meshes;
  69955. },
  69956. enumerable: true,
  69957. configurable: true
  69958. });
  69959. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69960. /**
  69961. * Gets wether or not G buffer are supported by the running hardware.
  69962. * This requires draw buffer supports
  69963. */
  69964. get: function () {
  69965. return this._multiRenderTarget.isSupported;
  69966. },
  69967. enumerable: true,
  69968. configurable: true
  69969. });
  69970. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69971. /**
  69972. * Gets wether or not position are enabled for the G buffer.
  69973. */
  69974. get: function () {
  69975. return this._enablePosition;
  69976. },
  69977. /**
  69978. * Sets wether or not position are enabled for the G buffer.
  69979. */
  69980. set: function (enable) {
  69981. this._enablePosition = enable;
  69982. this.dispose();
  69983. this._createRenderTargets();
  69984. },
  69985. enumerable: true,
  69986. configurable: true
  69987. });
  69988. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69989. /**
  69990. * Gets the scene associated with the buffer.
  69991. */
  69992. get: function () {
  69993. return this._scene;
  69994. },
  69995. enumerable: true,
  69996. configurable: true
  69997. });
  69998. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69999. /**
  70000. * Gets the ratio used by the buffer during its creation.
  70001. * How big is the buffer related to the main canvas.
  70002. */
  70003. get: function () {
  70004. return this._ratio;
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. /**
  70010. * Checks wether everything is ready to render a submesh to the G buffer.
  70011. * @param subMesh the submesh to check readiness for
  70012. * @param useInstances is the mesh drawn using instance or not
  70013. * @returns true if ready otherwise false
  70014. */
  70015. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70016. var material = subMesh.getMaterial();
  70017. if (material && material.disableDepthWrite) {
  70018. return false;
  70019. }
  70020. var defines = [];
  70021. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70022. var mesh = subMesh.getMesh();
  70023. // Alpha test
  70024. if (material && material.needAlphaTesting()) {
  70025. defines.push("#define ALPHATEST");
  70026. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70027. attribs.push(BABYLON.VertexBuffer.UVKind);
  70028. defines.push("#define UV1");
  70029. }
  70030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70031. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70032. defines.push("#define UV2");
  70033. }
  70034. }
  70035. // Buffers
  70036. if (this._enablePosition) {
  70037. defines.push("#define POSITION");
  70038. }
  70039. // Bones
  70040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70043. if (mesh.numBoneInfluencers > 4) {
  70044. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70045. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70046. }
  70047. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70048. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70049. }
  70050. else {
  70051. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70052. }
  70053. // Instances
  70054. if (useInstances) {
  70055. defines.push("#define INSTANCES");
  70056. attribs.push("world0");
  70057. attribs.push("world1");
  70058. attribs.push("world2");
  70059. attribs.push("world3");
  70060. }
  70061. // Get correct effect
  70062. var join = defines.join("\n");
  70063. if (this._cachedDefines !== join) {
  70064. this._cachedDefines = join;
  70065. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70066. }
  70067. return this._effect.isReady();
  70068. };
  70069. /**
  70070. * Gets the current underlying G Buffer.
  70071. * @returns the buffer
  70072. */
  70073. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70074. return this._multiRenderTarget;
  70075. };
  70076. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70077. /**
  70078. * Gets the number of samples used to render the buffer (anti aliasing).
  70079. */
  70080. get: function () {
  70081. return this._multiRenderTarget.samples;
  70082. },
  70083. /**
  70084. * Sets the number of samples used to render the buffer (anti aliasing).
  70085. */
  70086. set: function (value) {
  70087. this._multiRenderTarget.samples = value;
  70088. },
  70089. enumerable: true,
  70090. configurable: true
  70091. });
  70092. /**
  70093. * Disposes the renderer and frees up associated resources.
  70094. */
  70095. GeometryBufferRenderer.prototype.dispose = function () {
  70096. this.getGBuffer().dispose();
  70097. };
  70098. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70099. var _this = this;
  70100. var engine = this._scene.getEngine();
  70101. var count = this._enablePosition ? 3 : 2;
  70102. 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 });
  70103. if (!this.isSupported) {
  70104. return;
  70105. }
  70106. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70107. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70108. this._multiRenderTarget.refreshRate = 1;
  70109. this._multiRenderTarget.renderParticles = false;
  70110. this._multiRenderTarget.renderList = null;
  70111. // set default depth value to 1.0 (far away)
  70112. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70113. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70114. });
  70115. // Custom render function
  70116. var renderSubMesh = function (subMesh) {
  70117. var mesh = subMesh.getRenderingMesh();
  70118. var scene = _this._scene;
  70119. var engine = scene.getEngine();
  70120. var material = subMesh.getMaterial();
  70121. if (!material) {
  70122. return;
  70123. }
  70124. // Culling
  70125. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70126. // Managing instances
  70127. var batch = mesh._getInstancesRenderList(subMesh._id);
  70128. if (batch.mustReturn) {
  70129. return;
  70130. }
  70131. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70132. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70133. engine.enableEffect(_this._effect);
  70134. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70135. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70136. _this._effect.setMatrix("view", scene.getViewMatrix());
  70137. // Alpha test
  70138. if (material && material.needAlphaTesting()) {
  70139. var alphaTexture = material.getAlphaTestTexture();
  70140. if (alphaTexture) {
  70141. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70142. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70143. }
  70144. }
  70145. // Bones
  70146. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70147. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70148. }
  70149. // Draw
  70150. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70151. }
  70152. };
  70153. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70154. var index;
  70155. if (depthOnlySubMeshes.length) {
  70156. engine.setColorWrite(false);
  70157. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70158. renderSubMesh(depthOnlySubMeshes.data[index]);
  70159. }
  70160. engine.setColorWrite(true);
  70161. }
  70162. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70163. renderSubMesh(opaqueSubMeshes.data[index]);
  70164. }
  70165. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70166. renderSubMesh(alphaTestSubMeshes.data[index]);
  70167. }
  70168. };
  70169. };
  70170. return GeometryBufferRenderer;
  70171. }());
  70172. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70173. })(BABYLON || (BABYLON = {}));
  70174. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70175. var BABYLON;
  70176. (function (BABYLON) {
  70177. var RefractionPostProcess = /** @class */ (function (_super) {
  70178. __extends(RefractionPostProcess, _super);
  70179. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70180. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70181. _this.color = color;
  70182. _this.depth = depth;
  70183. _this.colorLevel = colorLevel;
  70184. _this._ownRefractionTexture = true;
  70185. _this.onActivateObservable.add(function (cam) {
  70186. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70187. });
  70188. _this.onApplyObservable.add(function (effect) {
  70189. effect.setColor3("baseColor", _this.color);
  70190. effect.setFloat("depth", _this.depth);
  70191. effect.setFloat("colorLevel", _this.colorLevel);
  70192. effect.setTexture("refractionSampler", _this._refTexture);
  70193. });
  70194. return _this;
  70195. }
  70196. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70197. /**
  70198. * Gets or sets the refraction texture
  70199. * Please note that you are responsible for disposing the texture if you set it manually
  70200. */
  70201. get: function () {
  70202. return this._refTexture;
  70203. },
  70204. set: function (value) {
  70205. if (this._refTexture && this._ownRefractionTexture) {
  70206. this._refTexture.dispose();
  70207. }
  70208. this._refTexture = value;
  70209. this._ownRefractionTexture = false;
  70210. },
  70211. enumerable: true,
  70212. configurable: true
  70213. });
  70214. // Methods
  70215. RefractionPostProcess.prototype.dispose = function (camera) {
  70216. if (this._refTexture && this._ownRefractionTexture) {
  70217. this._refTexture.dispose();
  70218. this._refTexture = null;
  70219. }
  70220. _super.prototype.dispose.call(this, camera);
  70221. };
  70222. return RefractionPostProcess;
  70223. }(BABYLON.PostProcess));
  70224. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70225. })(BABYLON || (BABYLON = {}));
  70226. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70227. var BABYLON;
  70228. (function (BABYLON) {
  70229. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70230. __extends(BlackAndWhitePostProcess, _super);
  70231. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70232. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70233. _this.degree = 1;
  70234. _this.onApplyObservable.add(function (effect) {
  70235. effect.setFloat("degree", _this.degree);
  70236. });
  70237. return _this;
  70238. }
  70239. return BlackAndWhitePostProcess;
  70240. }(BABYLON.PostProcess));
  70241. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70242. })(BABYLON || (BABYLON = {}));
  70243. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70244. var BABYLON;
  70245. (function (BABYLON) {
  70246. /**
  70247. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70248. * input texture to perform effects such as edge detection or sharpening
  70249. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70250. */
  70251. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70252. __extends(ConvolutionPostProcess, _super);
  70253. /**
  70254. * Creates a new instance of @see ConvolutionPostProcess
  70255. * @param name The name of the effect.
  70256. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70257. * @param options The required width/height ratio to downsize to before computing the render pass.
  70258. * @param camera The camera to apply the render pass to.
  70259. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70260. * @param engine The engine which the post process will be applied. (default: current engine)
  70261. * @param reusable If the post process can be reused on the same frame. (default: false)
  70262. * @param textureType Type of textures used when performing the post process. (default: 0)
  70263. */
  70264. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70266. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70267. _this.kernel = kernel;
  70268. _this.onApply = function (effect) {
  70269. effect.setFloat2("screenSize", _this.width, _this.height);
  70270. effect.setArray("kernel", _this.kernel);
  70271. };
  70272. return _this;
  70273. }
  70274. // Statics
  70275. /**
  70276. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70277. */
  70278. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70279. /**
  70280. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70281. */
  70282. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70283. /**
  70284. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70285. */
  70286. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70287. /**
  70288. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70289. */
  70290. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70291. /**
  70292. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70293. */
  70294. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70295. /**
  70296. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70297. */
  70298. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70299. return ConvolutionPostProcess;
  70300. }(BABYLON.PostProcess));
  70301. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70302. })(BABYLON || (BABYLON = {}));
  70303. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70304. var BABYLON;
  70305. (function (BABYLON) {
  70306. var FilterPostProcess = /** @class */ (function (_super) {
  70307. __extends(FilterPostProcess, _super);
  70308. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70309. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70310. _this.kernelMatrix = kernelMatrix;
  70311. _this.onApply = function (effect) {
  70312. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70313. };
  70314. return _this;
  70315. }
  70316. return FilterPostProcess;
  70317. }(BABYLON.PostProcess));
  70318. BABYLON.FilterPostProcess = FilterPostProcess;
  70319. })(BABYLON || (BABYLON = {}));
  70320. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70321. var BABYLON;
  70322. (function (BABYLON) {
  70323. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70324. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70325. __extends(VolumetricLightScatteringPostProcess, _super);
  70326. /**
  70327. * @constructor
  70328. * @param {string} name - The post-process name
  70329. * @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)
  70330. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70331. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70332. * @param {number} samples - The post-process quality, default 100
  70333. * @param {number} samplingMode - The post-process filtering mode
  70334. * @param {BABYLON.Engine} engine - The babylon engine
  70335. * @param {boolean} reusable - If the post-process is reusable
  70336. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70337. */
  70338. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70339. if (samples === void 0) { samples = 100; }
  70340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70341. 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;
  70342. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70343. /**
  70344. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70345. * @type {Vector3}
  70346. */
  70347. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70348. /**
  70349. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70350. * @type {boolean}
  70351. */
  70352. _this.useCustomMeshPosition = false;
  70353. /**
  70354. * If the post-process should inverse the light scattering direction
  70355. * @type {boolean}
  70356. */
  70357. _this.invert = true;
  70358. /**
  70359. * Array containing the excluded meshes not rendered in the internal pass
  70360. */
  70361. _this.excludedMeshes = new Array();
  70362. /**
  70363. * Controls the overall intensity of the post-process
  70364. * @type {number}
  70365. */
  70366. _this.exposure = 0.3;
  70367. /**
  70368. * Dissipates each sample's contribution in range [0, 1]
  70369. * @type {number}
  70370. */
  70371. _this.decay = 0.96815;
  70372. /**
  70373. * Controls the overall intensity of each sample
  70374. * @type {number}
  70375. */
  70376. _this.weight = 0.58767;
  70377. /**
  70378. * Controls the density of each sample
  70379. * @type {number}
  70380. */
  70381. _this.density = 0.926;
  70382. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70383. engine = scene.getEngine();
  70384. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70385. // Configure mesh
  70386. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70387. // Configure
  70388. _this._createPass(scene, ratio.passRatio || ratio);
  70389. _this.onActivate = function (camera) {
  70390. if (!_this.isSupported) {
  70391. _this.dispose(camera);
  70392. }
  70393. _this.onActivate = null;
  70394. };
  70395. _this.onApplyObservable.add(function (effect) {
  70396. _this._updateMeshScreenCoordinates(scene);
  70397. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70398. effect.setFloat("exposure", _this.exposure);
  70399. effect.setFloat("decay", _this.decay);
  70400. effect.setFloat("weight", _this.weight);
  70401. effect.setFloat("density", _this.density);
  70402. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70403. });
  70404. return _this;
  70405. }
  70406. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70407. get: function () {
  70408. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70409. return false;
  70410. },
  70411. set: function (useDiffuseColor) {
  70412. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70413. },
  70414. enumerable: true,
  70415. configurable: true
  70416. });
  70417. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70418. return "VolumetricLightScatteringPostProcess";
  70419. };
  70420. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70421. var mesh = subMesh.getMesh();
  70422. // Render this.mesh as default
  70423. if (mesh === this.mesh && mesh.material) {
  70424. return mesh.material.isReady(mesh);
  70425. }
  70426. var defines = [];
  70427. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70428. var material = subMesh.getMaterial();
  70429. // Alpha test
  70430. if (material) {
  70431. if (material.needAlphaTesting()) {
  70432. defines.push("#define ALPHATEST");
  70433. }
  70434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70435. attribs.push(BABYLON.VertexBuffer.UVKind);
  70436. defines.push("#define UV1");
  70437. }
  70438. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70439. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70440. defines.push("#define UV2");
  70441. }
  70442. }
  70443. // Bones
  70444. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70445. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70446. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70447. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70448. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70449. }
  70450. else {
  70451. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70452. }
  70453. // Instances
  70454. if (useInstances) {
  70455. defines.push("#define INSTANCES");
  70456. attribs.push("world0");
  70457. attribs.push("world1");
  70458. attribs.push("world2");
  70459. attribs.push("world3");
  70460. }
  70461. // Get correct effect
  70462. var join = defines.join("\n");
  70463. if (this._cachedDefines !== join) {
  70464. this._cachedDefines = join;
  70465. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70466. }
  70467. return this._volumetricLightScatteringPass.isReady();
  70468. };
  70469. /**
  70470. * Sets the new light position for light scattering effect
  70471. * @param {BABYLON.Vector3} The new custom light position
  70472. */
  70473. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70474. this.customMeshPosition = position;
  70475. };
  70476. /**
  70477. * Returns the light position for light scattering effect
  70478. * @return {BABYLON.Vector3} The custom light position
  70479. */
  70480. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70481. return this.customMeshPosition;
  70482. };
  70483. /**
  70484. * Disposes the internal assets and detaches the post-process from the camera
  70485. */
  70486. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70487. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70488. if (rttIndex !== -1) {
  70489. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70490. }
  70491. this._volumetricLightScatteringRTT.dispose();
  70492. _super.prototype.dispose.call(this, camera);
  70493. };
  70494. /**
  70495. * Returns the render target texture used by the post-process
  70496. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70497. */
  70498. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70499. return this._volumetricLightScatteringRTT;
  70500. };
  70501. // Private methods
  70502. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70503. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70504. return true;
  70505. }
  70506. return false;
  70507. };
  70508. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70509. var _this = this;
  70510. var engine = scene.getEngine();
  70511. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70512. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70513. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70514. this._volumetricLightScatteringRTT.renderList = null;
  70515. this._volumetricLightScatteringRTT.renderParticles = false;
  70516. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70517. var camera = this.getCamera();
  70518. if (camera) {
  70519. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70520. }
  70521. else {
  70522. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70523. }
  70524. // Custom render function for submeshes
  70525. var renderSubMesh = function (subMesh) {
  70526. var mesh = subMesh.getRenderingMesh();
  70527. if (_this._meshExcluded(mesh)) {
  70528. return;
  70529. }
  70530. var material = subMesh.getMaterial();
  70531. if (!material) {
  70532. return;
  70533. }
  70534. var scene = mesh.getScene();
  70535. var engine = scene.getEngine();
  70536. // Culling
  70537. engine.setState(material.backFaceCulling);
  70538. // Managing instances
  70539. var batch = mesh._getInstancesRenderList(subMesh._id);
  70540. if (batch.mustReturn) {
  70541. return;
  70542. }
  70543. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70544. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70545. var effect = _this._volumetricLightScatteringPass;
  70546. if (mesh === _this.mesh) {
  70547. if (subMesh.effect) {
  70548. effect = subMesh.effect;
  70549. }
  70550. else {
  70551. effect = material.getEffect();
  70552. }
  70553. }
  70554. engine.enableEffect(effect);
  70555. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70556. if (mesh === _this.mesh) {
  70557. material.bind(mesh.getWorldMatrix(), mesh);
  70558. }
  70559. else {
  70560. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70561. // Alpha test
  70562. if (material && material.needAlphaTesting()) {
  70563. var alphaTexture = material.getAlphaTestTexture();
  70564. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70565. if (alphaTexture) {
  70566. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70567. }
  70568. }
  70569. // Bones
  70570. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70571. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70572. }
  70573. }
  70574. // Draw
  70575. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70576. }
  70577. };
  70578. // Render target texture callbacks
  70579. var savedSceneClearColor;
  70580. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70581. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70582. savedSceneClearColor = scene.clearColor;
  70583. scene.clearColor = sceneClearColor;
  70584. });
  70585. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70586. scene.clearColor = savedSceneClearColor;
  70587. });
  70588. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70589. var engine = scene.getEngine();
  70590. var index;
  70591. if (depthOnlySubMeshes.length) {
  70592. engine.setColorWrite(false);
  70593. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70594. renderSubMesh(depthOnlySubMeshes.data[index]);
  70595. }
  70596. engine.setColorWrite(true);
  70597. }
  70598. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70599. renderSubMesh(opaqueSubMeshes.data[index]);
  70600. }
  70601. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70602. renderSubMesh(alphaTestSubMeshes.data[index]);
  70603. }
  70604. if (transparentSubMeshes.length) {
  70605. // Sort sub meshes
  70606. for (index = 0; index < transparentSubMeshes.length; index++) {
  70607. var submesh = transparentSubMeshes.data[index];
  70608. var boundingInfo = submesh.getBoundingInfo();
  70609. if (boundingInfo && scene.activeCamera) {
  70610. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70611. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70612. }
  70613. }
  70614. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70615. sortedArray.sort(function (a, b) {
  70616. // Alpha index first
  70617. if (a._alphaIndex > b._alphaIndex) {
  70618. return 1;
  70619. }
  70620. if (a._alphaIndex < b._alphaIndex) {
  70621. return -1;
  70622. }
  70623. // Then distance to camera
  70624. if (a._distanceToCamera < b._distanceToCamera) {
  70625. return 1;
  70626. }
  70627. if (a._distanceToCamera > b._distanceToCamera) {
  70628. return -1;
  70629. }
  70630. return 0;
  70631. });
  70632. // Render sub meshes
  70633. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70634. for (index = 0; index < sortedArray.length; index++) {
  70635. renderSubMesh(sortedArray[index]);
  70636. }
  70637. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70638. }
  70639. };
  70640. };
  70641. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70642. var transform = scene.getTransformMatrix();
  70643. var meshPosition;
  70644. if (this.useCustomMeshPosition) {
  70645. meshPosition = this.customMeshPosition;
  70646. }
  70647. else if (this.attachedNode) {
  70648. meshPosition = this.attachedNode.position;
  70649. }
  70650. else {
  70651. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70652. }
  70653. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70654. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70655. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70656. if (this.invert)
  70657. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70658. };
  70659. // Static methods
  70660. /**
  70661. * Creates a default mesh for the Volumeric Light Scattering post-process
  70662. * @param {string} The mesh name
  70663. * @param {BABYLON.Scene} The scene where to create the mesh
  70664. * @return {BABYLON.Mesh} the default mesh
  70665. */
  70666. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70667. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70668. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70669. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70670. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70671. mesh.material = material;
  70672. return mesh;
  70673. };
  70674. __decorate([
  70675. BABYLON.serializeAsVector3()
  70676. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70677. __decorate([
  70678. BABYLON.serialize()
  70679. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70680. __decorate([
  70681. BABYLON.serialize()
  70682. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70683. __decorate([
  70684. BABYLON.serializeAsMeshReference()
  70685. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70686. __decorate([
  70687. BABYLON.serialize()
  70688. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70689. __decorate([
  70690. BABYLON.serialize()
  70691. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70692. __decorate([
  70693. BABYLON.serialize()
  70694. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70695. __decorate([
  70696. BABYLON.serialize()
  70697. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70698. __decorate([
  70699. BABYLON.serialize()
  70700. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70701. return VolumetricLightScatteringPostProcess;
  70702. }(BABYLON.PostProcess));
  70703. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70704. })(BABYLON || (BABYLON = {}));
  70705. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70706. //
  70707. // This post-process allows the modification of rendered colors by using
  70708. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70709. //
  70710. // The object needs to be provided an url to a texture containing the color
  70711. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70712. // Use an image editing software to tweak the LUT to match your needs.
  70713. //
  70714. // For an example of a color LUT, see here:
  70715. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70716. // For explanations on color grading, see here:
  70717. // http://udn.epicgames.com/Three/ColorGrading.html
  70718. //
  70719. var BABYLON;
  70720. (function (BABYLON) {
  70721. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70722. __extends(ColorCorrectionPostProcess, _super);
  70723. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70724. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70725. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70726. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70727. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70728. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70729. _this.onApply = function (effect) {
  70730. effect.setTexture("colorTable", _this._colorTableTexture);
  70731. };
  70732. return _this;
  70733. }
  70734. return ColorCorrectionPostProcess;
  70735. }(BABYLON.PostProcess));
  70736. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70737. })(BABYLON || (BABYLON = {}));
  70738. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70739. var BABYLON;
  70740. (function (BABYLON) {
  70741. var TonemappingOperator;
  70742. (function (TonemappingOperator) {
  70743. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70744. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70745. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70746. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70747. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70748. ;
  70749. var TonemapPostProcess = /** @class */ (function (_super) {
  70750. __extends(TonemapPostProcess, _super);
  70751. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70753. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70754. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70755. _this._operator = _operator;
  70756. _this.exposureAdjustment = exposureAdjustment;
  70757. var defines = "#define ";
  70758. if (_this._operator === TonemappingOperator.Hable)
  70759. defines += "HABLE_TONEMAPPING";
  70760. else if (_this._operator === TonemappingOperator.Reinhard)
  70761. defines += "REINHARD_TONEMAPPING";
  70762. else if (_this._operator === TonemappingOperator.HejiDawson)
  70763. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70764. else if (_this._operator === TonemappingOperator.Photographic)
  70765. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70766. //sadly a second call to create the effect.
  70767. _this.updateEffect(defines);
  70768. _this.onApply = function (effect) {
  70769. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70770. };
  70771. return _this;
  70772. }
  70773. return TonemapPostProcess;
  70774. }(BABYLON.PostProcess));
  70775. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70776. })(BABYLON || (BABYLON = {}));
  70777. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70778. var BABYLON;
  70779. (function (BABYLON) {
  70780. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70781. __extends(DisplayPassPostProcess, _super);
  70782. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70783. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70784. }
  70785. return DisplayPassPostProcess;
  70786. }(BABYLON.PostProcess));
  70787. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70788. })(BABYLON || (BABYLON = {}));
  70789. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70790. var BABYLON;
  70791. (function (BABYLON) {
  70792. var HighlightsPostProcess = /** @class */ (function (_super) {
  70793. __extends(HighlightsPostProcess, _super);
  70794. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70796. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70797. }
  70798. return HighlightsPostProcess;
  70799. }(BABYLON.PostProcess));
  70800. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70801. })(BABYLON || (BABYLON = {}));
  70802. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70803. var BABYLON;
  70804. (function (BABYLON) {
  70805. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70806. __extends(ImageProcessingPostProcess, _super);
  70807. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70808. if (camera === void 0) { camera = null; }
  70809. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70810. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70811. _this._fromLinearSpace = true;
  70812. /**
  70813. * Defines cache preventing GC.
  70814. */
  70815. _this._defines = {
  70816. IMAGEPROCESSING: false,
  70817. VIGNETTE: false,
  70818. VIGNETTEBLENDMODEMULTIPLY: false,
  70819. VIGNETTEBLENDMODEOPAQUE: false,
  70820. TONEMAPPING: false,
  70821. CONTRAST: false,
  70822. COLORCURVES: false,
  70823. COLORGRADING: false,
  70824. COLORGRADING3D: false,
  70825. FROMLINEARSPACE: false,
  70826. SAMPLER3DGREENDEPTH: false,
  70827. SAMPLER3DBGRMAP: false,
  70828. IMAGEPROCESSINGPOSTPROCESS: false,
  70829. EXPOSURE: false,
  70830. GRAIN: false,
  70831. };
  70832. // Setup the configuration as forced by the constructor. This would then not force the
  70833. // scene materials output in linear space and let untouched the default forward pass.
  70834. if (imageProcessingConfiguration) {
  70835. imageProcessingConfiguration.applyByPostProcess = true;
  70836. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70837. // This will cause the shader to be compiled
  70838. _this.fromLinearSpace = false;
  70839. }
  70840. else {
  70841. _this._attachImageProcessingConfiguration(null, true);
  70842. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70843. }
  70844. _this.onApply = function (effect) {
  70845. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70846. };
  70847. return _this;
  70848. }
  70849. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70850. /**
  70851. * Gets the image processing configuration used either in this material.
  70852. */
  70853. get: function () {
  70854. return this._imageProcessingConfiguration;
  70855. },
  70856. /**
  70857. * Sets the Default image processing configuration used either in the this material.
  70858. *
  70859. * If sets to null, the scene one is in use.
  70860. */
  70861. set: function (value) {
  70862. this._attachImageProcessingConfiguration(value);
  70863. },
  70864. enumerable: true,
  70865. configurable: true
  70866. });
  70867. /**
  70868. * Attaches a new image processing configuration to the PBR Material.
  70869. * @param configuration
  70870. */
  70871. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70872. var _this = this;
  70873. if (doNotBuild === void 0) { doNotBuild = false; }
  70874. if (configuration === this._imageProcessingConfiguration) {
  70875. return;
  70876. }
  70877. // Detaches observer.
  70878. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70879. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70880. }
  70881. // Pick the scene configuration if needed.
  70882. if (!configuration) {
  70883. var scene = null;
  70884. var engine = this.getEngine();
  70885. var camera = this.getCamera();
  70886. if (camera) {
  70887. scene = camera.getScene();
  70888. }
  70889. else if (engine && engine.scenes) {
  70890. var scenes = engine.scenes;
  70891. scene = scenes[scenes.length - 1];
  70892. }
  70893. else {
  70894. scene = BABYLON.Engine.LastCreatedScene;
  70895. }
  70896. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70897. }
  70898. else {
  70899. this._imageProcessingConfiguration = configuration;
  70900. }
  70901. // Attaches observer.
  70902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70903. _this._updateParameters();
  70904. });
  70905. // Ensure the effect will be rebuilt.
  70906. if (!doNotBuild) {
  70907. this._updateParameters();
  70908. }
  70909. };
  70910. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70911. /**
  70912. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70913. */
  70914. get: function () {
  70915. return this.imageProcessingConfiguration.colorCurves;
  70916. },
  70917. /**
  70918. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70919. */
  70920. set: function (value) {
  70921. this.imageProcessingConfiguration.colorCurves = value;
  70922. },
  70923. enumerable: true,
  70924. configurable: true
  70925. });
  70926. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70927. /**
  70928. * Gets wether the color curves effect is enabled.
  70929. */
  70930. get: function () {
  70931. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70932. },
  70933. /**
  70934. * Sets wether the color curves effect is enabled.
  70935. */
  70936. set: function (value) {
  70937. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70938. },
  70939. enumerable: true,
  70940. configurable: true
  70941. });
  70942. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70943. /**
  70944. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70945. */
  70946. get: function () {
  70947. return this.imageProcessingConfiguration.colorGradingTexture;
  70948. },
  70949. /**
  70950. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70951. */
  70952. set: function (value) {
  70953. this.imageProcessingConfiguration.colorGradingTexture = value;
  70954. },
  70955. enumerable: true,
  70956. configurable: true
  70957. });
  70958. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70959. /**
  70960. * Gets wether the color grading effect is enabled.
  70961. */
  70962. get: function () {
  70963. return this.imageProcessingConfiguration.colorGradingEnabled;
  70964. },
  70965. /**
  70966. * Gets wether the color grading effect is enabled.
  70967. */
  70968. set: function (value) {
  70969. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70970. },
  70971. enumerable: true,
  70972. configurable: true
  70973. });
  70974. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70975. /**
  70976. * Gets exposure used in the effect.
  70977. */
  70978. get: function () {
  70979. return this.imageProcessingConfiguration.exposure;
  70980. },
  70981. /**
  70982. * Sets exposure used in the effect.
  70983. */
  70984. set: function (value) {
  70985. this.imageProcessingConfiguration.exposure = value;
  70986. },
  70987. enumerable: true,
  70988. configurable: true
  70989. });
  70990. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70991. /**
  70992. * Gets wether tonemapping is enabled or not.
  70993. */
  70994. get: function () {
  70995. return this._imageProcessingConfiguration.toneMappingEnabled;
  70996. },
  70997. /**
  70998. * Sets wether tonemapping is enabled or not
  70999. */
  71000. set: function (value) {
  71001. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71002. },
  71003. enumerable: true,
  71004. configurable: true
  71005. });
  71006. ;
  71007. ;
  71008. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71009. /**
  71010. * Gets contrast used in the effect.
  71011. */
  71012. get: function () {
  71013. return this.imageProcessingConfiguration.contrast;
  71014. },
  71015. /**
  71016. * Sets contrast used in the effect.
  71017. */
  71018. set: function (value) {
  71019. this.imageProcessingConfiguration.contrast = value;
  71020. },
  71021. enumerable: true,
  71022. configurable: true
  71023. });
  71024. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71025. /**
  71026. * Gets Vignette stretch size.
  71027. */
  71028. get: function () {
  71029. return this.imageProcessingConfiguration.vignetteStretch;
  71030. },
  71031. /**
  71032. * Sets Vignette stretch size.
  71033. */
  71034. set: function (value) {
  71035. this.imageProcessingConfiguration.vignetteStretch = value;
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71041. /**
  71042. * Gets Vignette centre X Offset.
  71043. */
  71044. get: function () {
  71045. return this.imageProcessingConfiguration.vignetteCentreX;
  71046. },
  71047. /**
  71048. * Sets Vignette centre X Offset.
  71049. */
  71050. set: function (value) {
  71051. this.imageProcessingConfiguration.vignetteCentreX = value;
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71057. /**
  71058. * Gets Vignette centre Y Offset.
  71059. */
  71060. get: function () {
  71061. return this.imageProcessingConfiguration.vignetteCentreY;
  71062. },
  71063. /**
  71064. * Sets Vignette centre Y Offset.
  71065. */
  71066. set: function (value) {
  71067. this.imageProcessingConfiguration.vignetteCentreY = value;
  71068. },
  71069. enumerable: true,
  71070. configurable: true
  71071. });
  71072. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71073. /**
  71074. * Gets Vignette weight or intensity of the vignette effect.
  71075. */
  71076. get: function () {
  71077. return this.imageProcessingConfiguration.vignetteWeight;
  71078. },
  71079. /**
  71080. * Sets Vignette weight or intensity of the vignette effect.
  71081. */
  71082. set: function (value) {
  71083. this.imageProcessingConfiguration.vignetteWeight = value;
  71084. },
  71085. enumerable: true,
  71086. configurable: true
  71087. });
  71088. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71089. /**
  71090. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71091. * if vignetteEnabled is set to true.
  71092. */
  71093. get: function () {
  71094. return this.imageProcessingConfiguration.vignetteColor;
  71095. },
  71096. /**
  71097. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71098. * if vignetteEnabled is set to true.
  71099. */
  71100. set: function (value) {
  71101. this.imageProcessingConfiguration.vignetteColor = value;
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71107. /**
  71108. * Gets Camera field of view used by the Vignette effect.
  71109. */
  71110. get: function () {
  71111. return this.imageProcessingConfiguration.vignetteCameraFov;
  71112. },
  71113. /**
  71114. * Sets Camera field of view used by the Vignette effect.
  71115. */
  71116. set: function (value) {
  71117. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71118. },
  71119. enumerable: true,
  71120. configurable: true
  71121. });
  71122. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71123. /**
  71124. * Gets the vignette blend mode allowing different kind of effect.
  71125. */
  71126. get: function () {
  71127. return this.imageProcessingConfiguration.vignetteBlendMode;
  71128. },
  71129. /**
  71130. * Sets the vignette blend mode allowing different kind of effect.
  71131. */
  71132. set: function (value) {
  71133. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71134. },
  71135. enumerable: true,
  71136. configurable: true
  71137. });
  71138. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71139. /**
  71140. * Gets wether the vignette effect is enabled.
  71141. */
  71142. get: function () {
  71143. return this.imageProcessingConfiguration.vignetteEnabled;
  71144. },
  71145. /**
  71146. * Sets wether the vignette effect is enabled.
  71147. */
  71148. set: function (value) {
  71149. this.imageProcessingConfiguration.vignetteEnabled = value;
  71150. },
  71151. enumerable: true,
  71152. configurable: true
  71153. });
  71154. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71155. /**
  71156. * Gets wether the grain effect is enabled.
  71157. */
  71158. get: function () {
  71159. return this.imageProcessingConfiguration.grainEnabled;
  71160. },
  71161. /**
  71162. * Sets wether the grain effect is enabled.
  71163. */
  71164. set: function (value) {
  71165. this.imageProcessingConfiguration.grainEnabled = value;
  71166. },
  71167. enumerable: true,
  71168. configurable: true
  71169. });
  71170. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71171. /**
  71172. * Gets the grain effect's intensity.
  71173. */
  71174. get: function () {
  71175. return this.imageProcessingConfiguration.grainIntensity;
  71176. },
  71177. /**
  71178. * Sets the grain effect's intensity.
  71179. */
  71180. set: function (value) {
  71181. this.imageProcessingConfiguration.grainIntensity = value;
  71182. },
  71183. enumerable: true,
  71184. configurable: true
  71185. });
  71186. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71187. /**
  71188. * Gets wether the grain effect is animated.
  71189. */
  71190. get: function () {
  71191. return this.imageProcessingConfiguration.grainAnimated;
  71192. },
  71193. /**
  71194. * Sets wether the grain effect is animated.
  71195. */
  71196. set: function (value) {
  71197. this.imageProcessingConfiguration.grainAnimated = value;
  71198. },
  71199. enumerable: true,
  71200. configurable: true
  71201. });
  71202. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71203. /**
  71204. * Gets wether the input of the processing is in Gamma or Linear Space.
  71205. */
  71206. get: function () {
  71207. return this._fromLinearSpace;
  71208. },
  71209. /**
  71210. * Sets wether the input of the processing is in Gamma or Linear Space.
  71211. */
  71212. set: function (value) {
  71213. if (this._fromLinearSpace === value) {
  71214. return;
  71215. }
  71216. this._fromLinearSpace = value;
  71217. this._updateParameters();
  71218. },
  71219. enumerable: true,
  71220. configurable: true
  71221. });
  71222. ImageProcessingPostProcess.prototype.getClassName = function () {
  71223. return "ImageProcessingPostProcess";
  71224. };
  71225. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71226. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71227. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71228. var defines = "";
  71229. for (var define in this._defines) {
  71230. if (this._defines[define]) {
  71231. defines += "#define " + define + ";\r\n";
  71232. }
  71233. }
  71234. var samplers = ["textureSampler"];
  71235. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71236. var uniforms = ["scale"];
  71237. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71238. this.updateEffect(defines, uniforms, samplers);
  71239. };
  71240. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71241. _super.prototype.dispose.call(this, camera);
  71242. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71243. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71244. }
  71245. this.imageProcessingConfiguration.applyByPostProcess = false;
  71246. };
  71247. __decorate([
  71248. BABYLON.serialize()
  71249. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71250. return ImageProcessingPostProcess;
  71251. }(BABYLON.PostProcess));
  71252. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71253. })(BABYLON || (BABYLON = {}));
  71254. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71255. var BABYLON;
  71256. (function (BABYLON) {
  71257. var Bone = /** @class */ (function (_super) {
  71258. __extends(Bone, _super);
  71259. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71260. if (parentBone === void 0) { parentBone = null; }
  71261. if (localMatrix === void 0) { localMatrix = null; }
  71262. if (restPose === void 0) { restPose = null; }
  71263. if (baseMatrix === void 0) { baseMatrix = null; }
  71264. if (index === void 0) { index = null; }
  71265. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71266. _this.name = name;
  71267. _this.children = new Array();
  71268. _this.animations = new Array();
  71269. // Set this value to map this bone to a different index in the transform matrices.
  71270. // Set this value to -1 to exclude the bone from the transform matrices.
  71271. _this._index = null;
  71272. _this._worldTransform = new BABYLON.Matrix();
  71273. _this._absoluteTransform = new BABYLON.Matrix();
  71274. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71275. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71276. _this._scaleVector = BABYLON.Vector3.One();
  71277. _this._negateScaleChildren = BABYLON.Vector3.One();
  71278. _this._scalingDeterminant = 1;
  71279. _this._skeleton = skeleton;
  71280. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71281. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71282. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71283. _this._index = index;
  71284. skeleton.bones.push(_this);
  71285. _this.setParent(parentBone, false);
  71286. _this._updateDifferenceMatrix();
  71287. return _this;
  71288. }
  71289. Object.defineProperty(Bone.prototype, "_matrix", {
  71290. get: function () {
  71291. return this._localMatrix;
  71292. },
  71293. set: function (val) {
  71294. if (this._localMatrix) {
  71295. this._localMatrix.copyFrom(val);
  71296. }
  71297. else {
  71298. this._localMatrix = val;
  71299. }
  71300. },
  71301. enumerable: true,
  71302. configurable: true
  71303. });
  71304. // Members
  71305. Bone.prototype.getSkeleton = function () {
  71306. return this._skeleton;
  71307. };
  71308. Bone.prototype.getParent = function () {
  71309. return this._parent;
  71310. };
  71311. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71312. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71313. if (this._parent === parent) {
  71314. return;
  71315. }
  71316. if (this._parent) {
  71317. var index = this._parent.children.indexOf(this);
  71318. if (index !== -1) {
  71319. this._parent.children.splice(index, 1);
  71320. }
  71321. }
  71322. this._parent = parent;
  71323. if (this._parent) {
  71324. this._parent.children.push(this);
  71325. }
  71326. if (updateDifferenceMatrix) {
  71327. this._updateDifferenceMatrix();
  71328. }
  71329. };
  71330. Bone.prototype.getLocalMatrix = function () {
  71331. return this._localMatrix;
  71332. };
  71333. Bone.prototype.getBaseMatrix = function () {
  71334. return this._baseMatrix;
  71335. };
  71336. Bone.prototype.getRestPose = function () {
  71337. return this._restPose;
  71338. };
  71339. Bone.prototype.returnToRest = function () {
  71340. this.updateMatrix(this._restPose.clone());
  71341. };
  71342. Bone.prototype.getWorldMatrix = function () {
  71343. return this._worldTransform;
  71344. };
  71345. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71346. return this._invertedAbsoluteTransform;
  71347. };
  71348. Bone.prototype.getAbsoluteTransform = function () {
  71349. return this._absoluteTransform;
  71350. };
  71351. Object.defineProperty(Bone.prototype, "position", {
  71352. // Properties (matches AbstractMesh properties)
  71353. get: function () {
  71354. return this.getPosition();
  71355. },
  71356. set: function (newPosition) {
  71357. this.setPosition(newPosition);
  71358. },
  71359. enumerable: true,
  71360. configurable: true
  71361. });
  71362. Object.defineProperty(Bone.prototype, "rotation", {
  71363. get: function () {
  71364. return this.getRotation();
  71365. },
  71366. set: function (newRotation) {
  71367. this.setRotation(newRotation);
  71368. },
  71369. enumerable: true,
  71370. configurable: true
  71371. });
  71372. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71373. get: function () {
  71374. return this.getRotationQuaternion();
  71375. },
  71376. set: function (newRotation) {
  71377. this.setRotationQuaternion(newRotation);
  71378. },
  71379. enumerable: true,
  71380. configurable: true
  71381. });
  71382. Object.defineProperty(Bone.prototype, "scaling", {
  71383. get: function () {
  71384. return this.getScale();
  71385. },
  71386. set: function (newScaling) {
  71387. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71388. },
  71389. enumerable: true,
  71390. configurable: true
  71391. });
  71392. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71393. /**
  71394. * Gets the animation properties override
  71395. */
  71396. get: function () {
  71397. return this._skeleton.animationPropertiesOverride;
  71398. },
  71399. enumerable: true,
  71400. configurable: true
  71401. });
  71402. // Methods
  71403. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71404. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71405. this._baseMatrix = matrix.clone();
  71406. this._localMatrix = matrix.clone();
  71407. this._skeleton._markAsDirty();
  71408. if (updateDifferenceMatrix) {
  71409. this._updateDifferenceMatrix();
  71410. }
  71411. };
  71412. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71413. if (!rootMatrix) {
  71414. rootMatrix = this._baseMatrix;
  71415. }
  71416. if (this._parent) {
  71417. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71418. }
  71419. else {
  71420. this._absoluteTransform.copyFrom(rootMatrix);
  71421. }
  71422. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71423. for (var index = 0; index < this.children.length; index++) {
  71424. this.children[index]._updateDifferenceMatrix();
  71425. }
  71426. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71427. };
  71428. Bone.prototype.markAsDirty = function () {
  71429. this._currentRenderId++;
  71430. this._skeleton._markAsDirty();
  71431. };
  71432. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71433. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71434. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71435. // all animation may be coming from a library skeleton, so may need to create animation
  71436. if (this.animations.length === 0) {
  71437. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71438. this.animations[0].setKeys([]);
  71439. }
  71440. // get animation info / verify there is such a range from the source bone
  71441. var sourceRange = source.animations[0].getRange(rangeName);
  71442. if (!sourceRange) {
  71443. return false;
  71444. }
  71445. var from = sourceRange.from;
  71446. var to = sourceRange.to;
  71447. var sourceKeys = source.animations[0].getKeys();
  71448. // rescaling prep
  71449. var sourceBoneLength = source.length;
  71450. var sourceParent = source.getParent();
  71451. var parent = this.getParent();
  71452. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71453. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71454. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71455. var destKeys = this.animations[0].getKeys();
  71456. // loop vars declaration
  71457. var orig;
  71458. var origTranslation;
  71459. var mat;
  71460. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71461. orig = sourceKeys[key];
  71462. if (orig.frame >= from && orig.frame <= to) {
  71463. if (rescaleAsRequired) {
  71464. mat = orig.value.clone();
  71465. // scale based on parent ratio, when bone has parent
  71466. if (parentScalingReqd) {
  71467. origTranslation = mat.getTranslation();
  71468. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71469. // scale based on skeleton dimension ratio when root bone, and value is passed
  71470. }
  71471. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71472. origTranslation = mat.getTranslation();
  71473. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71474. // use original when root bone, and no data for skelDimensionsRatio
  71475. }
  71476. else {
  71477. mat = orig.value;
  71478. }
  71479. }
  71480. else {
  71481. mat = orig.value;
  71482. }
  71483. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71484. }
  71485. }
  71486. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71487. return true;
  71488. };
  71489. /**
  71490. * Translate the bone in local or world space.
  71491. * @param vec The amount to translate the bone.
  71492. * @param space The space that the translation is in.
  71493. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71494. */
  71495. Bone.prototype.translate = function (vec, space, mesh) {
  71496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71497. var lm = this.getLocalMatrix();
  71498. if (space == BABYLON.Space.LOCAL) {
  71499. lm.m[12] += vec.x;
  71500. lm.m[13] += vec.y;
  71501. lm.m[14] += vec.z;
  71502. }
  71503. else {
  71504. var wm = null;
  71505. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71506. if (mesh) {
  71507. wm = mesh.getWorldMatrix();
  71508. }
  71509. this._skeleton.computeAbsoluteTransforms();
  71510. var tmat = Bone._tmpMats[0];
  71511. var tvec = Bone._tmpVecs[0];
  71512. if (this._parent) {
  71513. if (mesh && wm) {
  71514. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71515. tmat.multiplyToRef(wm, tmat);
  71516. }
  71517. else {
  71518. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71519. }
  71520. }
  71521. tmat.m[12] = 0;
  71522. tmat.m[13] = 0;
  71523. tmat.m[14] = 0;
  71524. tmat.invert();
  71525. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71526. lm.m[12] += tvec.x;
  71527. lm.m[13] += tvec.y;
  71528. lm.m[14] += tvec.z;
  71529. }
  71530. this.markAsDirty();
  71531. };
  71532. /**
  71533. * Set the postion of the bone in local or world space.
  71534. * @param position The position to set the bone.
  71535. * @param space The space that the position is in.
  71536. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71537. */
  71538. Bone.prototype.setPosition = function (position, space, mesh) {
  71539. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71540. var lm = this.getLocalMatrix();
  71541. if (space == BABYLON.Space.LOCAL) {
  71542. lm.m[12] = position.x;
  71543. lm.m[13] = position.y;
  71544. lm.m[14] = position.z;
  71545. }
  71546. else {
  71547. var wm = null;
  71548. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71549. if (mesh) {
  71550. wm = mesh.getWorldMatrix();
  71551. }
  71552. this._skeleton.computeAbsoluteTransforms();
  71553. var tmat = Bone._tmpMats[0];
  71554. var vec = Bone._tmpVecs[0];
  71555. if (this._parent) {
  71556. if (mesh && wm) {
  71557. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71558. tmat.multiplyToRef(wm, tmat);
  71559. }
  71560. else {
  71561. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71562. }
  71563. }
  71564. tmat.invert();
  71565. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71566. lm.m[12] = vec.x;
  71567. lm.m[13] = vec.y;
  71568. lm.m[14] = vec.z;
  71569. }
  71570. this.markAsDirty();
  71571. };
  71572. /**
  71573. * Set the absolute postion of the bone (world space).
  71574. * @param position The position to set the bone.
  71575. * @param mesh The mesh that this bone is attached to.
  71576. */
  71577. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71578. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71579. };
  71580. /**
  71581. * Set the scale of the bone on the x, y and z axes.
  71582. * @param x The scale of the bone on the x axis.
  71583. * @param x The scale of the bone on the y axis.
  71584. * @param z The scale of the bone on the z axis.
  71585. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71586. */
  71587. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71588. if (scaleChildren === void 0) { scaleChildren = false; }
  71589. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71590. if (!scaleChildren) {
  71591. this._negateScaleChildren.x = 1 / x;
  71592. this._negateScaleChildren.y = 1 / y;
  71593. this._negateScaleChildren.z = 1 / z;
  71594. }
  71595. this._syncScaleVector();
  71596. }
  71597. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71598. };
  71599. /**
  71600. * Scale the bone on the x, y and z axes.
  71601. * @param x The amount to scale the bone on the x axis.
  71602. * @param x The amount to scale the bone on the y axis.
  71603. * @param z The amount to scale the bone on the z axis.
  71604. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71605. */
  71606. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71607. if (scaleChildren === void 0) { scaleChildren = false; }
  71608. var locMat = this.getLocalMatrix();
  71609. var origLocMat = Bone._tmpMats[0];
  71610. origLocMat.copyFrom(locMat);
  71611. var origLocMatInv = Bone._tmpMats[1];
  71612. origLocMatInv.copyFrom(origLocMat);
  71613. origLocMatInv.invert();
  71614. var scaleMat = Bone._tmpMats[2];
  71615. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71616. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71617. this._scaleVector.x *= x;
  71618. this._scaleVector.y *= y;
  71619. this._scaleVector.z *= z;
  71620. locMat.multiplyToRef(origLocMatInv, locMat);
  71621. locMat.multiplyToRef(scaleMat, locMat);
  71622. locMat.multiplyToRef(origLocMat, locMat);
  71623. var parent = this.getParent();
  71624. if (parent) {
  71625. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71626. }
  71627. else {
  71628. this.getAbsoluteTransform().copyFrom(locMat);
  71629. }
  71630. var len = this.children.length;
  71631. scaleMat.invert();
  71632. for (var i = 0; i < len; i++) {
  71633. var child = this.children[i];
  71634. var cm = child.getLocalMatrix();
  71635. cm.multiplyToRef(scaleMat, cm);
  71636. var lm = child.getLocalMatrix();
  71637. lm.m[12] *= x;
  71638. lm.m[13] *= y;
  71639. lm.m[14] *= z;
  71640. }
  71641. this.computeAbsoluteTransforms();
  71642. if (scaleChildren) {
  71643. for (var i = 0; i < len; i++) {
  71644. this.children[i].scale(x, y, z, scaleChildren);
  71645. }
  71646. }
  71647. this.markAsDirty();
  71648. };
  71649. /**
  71650. * Set the yaw, pitch, and roll of the bone in local or world space.
  71651. * @param yaw The rotation of the bone on the y axis.
  71652. * @param pitch The rotation of the bone on the x axis.
  71653. * @param roll The rotation of the bone on the z axis.
  71654. * @param space The space that the axes of rotation are in.
  71655. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71656. */
  71657. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71659. var rotMat = Bone._tmpMats[0];
  71660. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71661. var rotMatInv = Bone._tmpMats[1];
  71662. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71663. rotMatInv.multiplyToRef(rotMat, rotMat);
  71664. this._rotateWithMatrix(rotMat, space, mesh);
  71665. };
  71666. /**
  71667. * Rotate the bone on an axis in local or world space.
  71668. * @param axis The axis to rotate the bone on.
  71669. * @param amount The amount to rotate the bone.
  71670. * @param space The space that the axis is in.
  71671. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71672. */
  71673. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71675. var rmat = Bone._tmpMats[0];
  71676. rmat.m[12] = 0;
  71677. rmat.m[13] = 0;
  71678. rmat.m[14] = 0;
  71679. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71680. this._rotateWithMatrix(rmat, space, mesh);
  71681. };
  71682. /**
  71683. * Set the rotation of the bone to a particular axis angle in local or world space.
  71684. * @param axis The axis to rotate the bone on.
  71685. * @param angle The angle that the bone should be rotated to.
  71686. * @param space The space that the axis is in.
  71687. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71688. */
  71689. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71691. var rotMat = Bone._tmpMats[0];
  71692. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71693. var rotMatInv = Bone._tmpMats[1];
  71694. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71695. rotMatInv.multiplyToRef(rotMat, rotMat);
  71696. this._rotateWithMatrix(rotMat, space, mesh);
  71697. };
  71698. /**
  71699. * Set the euler rotation of the bone in local of world space.
  71700. * @param rotation The euler rotation that the bone should be set to.
  71701. * @param space The space that the rotation is in.
  71702. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71703. */
  71704. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71705. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71706. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71707. };
  71708. /**
  71709. * Set the quaternion rotation of the bone in local of world space.
  71710. * @param quat The quaternion rotation that the bone should be set to.
  71711. * @param space The space that the rotation is in.
  71712. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71713. */
  71714. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71715. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71716. var rotMatInv = Bone._tmpMats[0];
  71717. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71718. var rotMat = Bone._tmpMats[1];
  71719. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71720. rotMatInv.multiplyToRef(rotMat, rotMat);
  71721. this._rotateWithMatrix(rotMat, space, mesh);
  71722. };
  71723. /**
  71724. * Set the rotation matrix of the bone in local of world space.
  71725. * @param rotMat The rotation matrix that the bone should be set to.
  71726. * @param space The space that the rotation is in.
  71727. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71728. */
  71729. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71731. var rotMatInv = Bone._tmpMats[0];
  71732. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71733. var rotMat2 = Bone._tmpMats[1];
  71734. rotMat2.copyFrom(rotMat);
  71735. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71736. this._rotateWithMatrix(rotMat2, space, mesh);
  71737. };
  71738. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71740. var lmat = this.getLocalMatrix();
  71741. var lx = lmat.m[12];
  71742. var ly = lmat.m[13];
  71743. var lz = lmat.m[14];
  71744. var parent = this.getParent();
  71745. var parentScale = Bone._tmpMats[3];
  71746. var parentScaleInv = Bone._tmpMats[4];
  71747. if (parent) {
  71748. if (space == BABYLON.Space.WORLD) {
  71749. if (mesh) {
  71750. parentScale.copyFrom(mesh.getWorldMatrix());
  71751. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71752. }
  71753. else {
  71754. parentScale.copyFrom(parent.getAbsoluteTransform());
  71755. }
  71756. }
  71757. else {
  71758. parentScale = parent._scaleMatrix;
  71759. }
  71760. parentScaleInv.copyFrom(parentScale);
  71761. parentScaleInv.invert();
  71762. lmat.multiplyToRef(parentScale, lmat);
  71763. lmat.multiplyToRef(rmat, lmat);
  71764. lmat.multiplyToRef(parentScaleInv, lmat);
  71765. }
  71766. else {
  71767. if (space == BABYLON.Space.WORLD && mesh) {
  71768. parentScale.copyFrom(mesh.getWorldMatrix());
  71769. parentScaleInv.copyFrom(parentScale);
  71770. parentScaleInv.invert();
  71771. lmat.multiplyToRef(parentScale, lmat);
  71772. lmat.multiplyToRef(rmat, lmat);
  71773. lmat.multiplyToRef(parentScaleInv, lmat);
  71774. }
  71775. else {
  71776. lmat.multiplyToRef(rmat, lmat);
  71777. }
  71778. }
  71779. lmat.m[12] = lx;
  71780. lmat.m[13] = ly;
  71781. lmat.m[14] = lz;
  71782. this.computeAbsoluteTransforms();
  71783. this.markAsDirty();
  71784. };
  71785. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71787. if (space == BABYLON.Space.WORLD) {
  71788. var scaleMatrix = Bone._tmpMats[2];
  71789. scaleMatrix.copyFrom(this._scaleMatrix);
  71790. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71791. if (mesh) {
  71792. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71793. var meshScale = Bone._tmpMats[3];
  71794. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71795. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71796. }
  71797. rotMatInv.invert();
  71798. scaleMatrix.m[0] *= this._scalingDeterminant;
  71799. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71800. }
  71801. else {
  71802. rotMatInv.copyFrom(this.getLocalMatrix());
  71803. rotMatInv.invert();
  71804. var scaleMatrix = Bone._tmpMats[2];
  71805. scaleMatrix.copyFrom(this._scaleMatrix);
  71806. if (this._parent) {
  71807. var pscaleMatrix = Bone._tmpMats[3];
  71808. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71809. pscaleMatrix.invert();
  71810. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71811. }
  71812. else {
  71813. scaleMatrix.m[0] *= this._scalingDeterminant;
  71814. }
  71815. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71816. }
  71817. };
  71818. /**
  71819. * Get the scale of the bone
  71820. * @returns the scale of the bone
  71821. */
  71822. Bone.prototype.getScale = function () {
  71823. return this._scaleVector.clone();
  71824. };
  71825. /**
  71826. * Copy the scale of the bone to a vector3.
  71827. * @param result The vector3 to copy the scale to
  71828. */
  71829. Bone.prototype.getScaleToRef = function (result) {
  71830. result.copyFrom(this._scaleVector);
  71831. };
  71832. /**
  71833. * Get the position of the bone in local or world space.
  71834. * @param space The space that the returned position is in.
  71835. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71836. * @returns The position of the bone
  71837. */
  71838. Bone.prototype.getPosition = function (space, mesh) {
  71839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71840. if (mesh === void 0) { mesh = null; }
  71841. var pos = BABYLON.Vector3.Zero();
  71842. this.getPositionToRef(space, mesh, pos);
  71843. return pos;
  71844. };
  71845. /**
  71846. * Copy the position of the bone to a vector3 in local or world space.
  71847. * @param space The space that the returned position is in.
  71848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71849. * @param result The vector3 to copy the position to.
  71850. */
  71851. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71852. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71853. if (space == BABYLON.Space.LOCAL) {
  71854. var lm = this.getLocalMatrix();
  71855. result.x = lm.m[12];
  71856. result.y = lm.m[13];
  71857. result.z = lm.m[14];
  71858. }
  71859. else {
  71860. var wm = null;
  71861. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71862. if (mesh) {
  71863. wm = mesh.getWorldMatrix();
  71864. }
  71865. this._skeleton.computeAbsoluteTransforms();
  71866. var tmat = Bone._tmpMats[0];
  71867. if (mesh && wm) {
  71868. tmat.copyFrom(this.getAbsoluteTransform());
  71869. tmat.multiplyToRef(wm, tmat);
  71870. }
  71871. else {
  71872. tmat = this.getAbsoluteTransform();
  71873. }
  71874. result.x = tmat.m[12];
  71875. result.y = tmat.m[13];
  71876. result.z = tmat.m[14];
  71877. }
  71878. };
  71879. /**
  71880. * Get the absolute position of the bone (world space).
  71881. * @param mesh The mesh that this bone is attached to.
  71882. * @returns The absolute position of the bone
  71883. */
  71884. Bone.prototype.getAbsolutePosition = function (mesh) {
  71885. if (mesh === void 0) { mesh = null; }
  71886. var pos = BABYLON.Vector3.Zero();
  71887. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71888. return pos;
  71889. };
  71890. /**
  71891. * Copy the absolute position of the bone (world space) to the result param.
  71892. * @param mesh The mesh that this bone is attached to.
  71893. * @param result The vector3 to copy the absolute position to.
  71894. */
  71895. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71896. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71897. };
  71898. /**
  71899. * Compute the absolute transforms of this bone and its children.
  71900. */
  71901. Bone.prototype.computeAbsoluteTransforms = function () {
  71902. if (this._parent) {
  71903. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71904. }
  71905. else {
  71906. this._absoluteTransform.copyFrom(this._localMatrix);
  71907. var poseMatrix = this._skeleton.getPoseMatrix();
  71908. if (poseMatrix) {
  71909. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71910. }
  71911. }
  71912. var children = this.children;
  71913. var len = children.length;
  71914. for (var i = 0; i < len; i++) {
  71915. children[i].computeAbsoluteTransforms();
  71916. }
  71917. };
  71918. Bone.prototype._syncScaleVector = function () {
  71919. var lm = this.getLocalMatrix();
  71920. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71921. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71922. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71923. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71924. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71925. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71926. this._scaleVector.x = xs * Math.sqrt(xsq);
  71927. this._scaleVector.y = ys * Math.sqrt(ysq);
  71928. this._scaleVector.z = zs * Math.sqrt(zsq);
  71929. if (this._parent) {
  71930. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71931. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71932. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71933. }
  71934. 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);
  71935. };
  71936. /**
  71937. * Get the world direction from an axis that is in the local space of the bone.
  71938. * @param localAxis The local direction that is used to compute the world direction.
  71939. * @param mesh The mesh that this bone is attached to.
  71940. * @returns The world direction
  71941. */
  71942. Bone.prototype.getDirection = function (localAxis, mesh) {
  71943. if (mesh === void 0) { mesh = null; }
  71944. var result = BABYLON.Vector3.Zero();
  71945. this.getDirectionToRef(localAxis, mesh, result);
  71946. return result;
  71947. };
  71948. /**
  71949. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71950. * @param localAxis The local direction that is used to compute the world direction.
  71951. * @param mesh The mesh that this bone is attached to.
  71952. * @param result The vector3 that the world direction will be copied to.
  71953. */
  71954. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71955. if (mesh === void 0) { mesh = null; }
  71956. var wm = null;
  71957. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71958. if (mesh) {
  71959. wm = mesh.getWorldMatrix();
  71960. }
  71961. this._skeleton.computeAbsoluteTransforms();
  71962. var mat = Bone._tmpMats[0];
  71963. mat.copyFrom(this.getAbsoluteTransform());
  71964. if (mesh && wm) {
  71965. mat.multiplyToRef(wm, mat);
  71966. }
  71967. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71968. result.normalize();
  71969. };
  71970. /**
  71971. * Get the euler rotation of the bone in local or world space.
  71972. * @param space The space that the rotation should be in.
  71973. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71974. * @returns The euler rotation
  71975. */
  71976. Bone.prototype.getRotation = function (space, mesh) {
  71977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71978. if (mesh === void 0) { mesh = null; }
  71979. var result = BABYLON.Vector3.Zero();
  71980. this.getRotationToRef(space, mesh, result);
  71981. return result;
  71982. };
  71983. /**
  71984. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71985. * @param space The space that the rotation should be in.
  71986. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71987. * @param result The vector3 that the rotation should be copied to.
  71988. */
  71989. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71991. if (mesh === void 0) { mesh = null; }
  71992. var quat = Bone._tmpQuat;
  71993. this.getRotationQuaternionToRef(space, mesh, quat);
  71994. quat.toEulerAnglesToRef(result);
  71995. };
  71996. /**
  71997. * Get the quaternion rotation of the bone in either local or world space.
  71998. * @param space The space that the rotation should be in.
  71999. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72000. * @returns The quaternion rotation
  72001. */
  72002. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72004. if (mesh === void 0) { mesh = null; }
  72005. var result = BABYLON.Quaternion.Identity();
  72006. this.getRotationQuaternionToRef(space, mesh, result);
  72007. return result;
  72008. };
  72009. /**
  72010. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72011. * @param space The space that the rotation should be in.
  72012. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72013. * @param result The quaternion that the rotation should be copied to.
  72014. */
  72015. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72016. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72017. if (mesh === void 0) { mesh = null; }
  72018. if (space == BABYLON.Space.LOCAL) {
  72019. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72020. }
  72021. else {
  72022. var mat = Bone._tmpMats[0];
  72023. var amat = this.getAbsoluteTransform();
  72024. if (mesh) {
  72025. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72026. }
  72027. else {
  72028. mat.copyFrom(amat);
  72029. }
  72030. mat.m[0] *= this._scalingDeterminant;
  72031. mat.m[1] *= this._scalingDeterminant;
  72032. mat.m[2] *= this._scalingDeterminant;
  72033. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72034. }
  72035. };
  72036. /**
  72037. * Get the rotation matrix of the bone in local or world space.
  72038. * @param space The space that the rotation should be in.
  72039. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72040. * @returns The rotation matrix
  72041. */
  72042. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72043. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72044. var result = BABYLON.Matrix.Identity();
  72045. this.getRotationMatrixToRef(space, mesh, result);
  72046. return result;
  72047. };
  72048. /**
  72049. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72050. * @param space The space that the rotation should be in.
  72051. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72052. * @param result The quaternion that the rotation should be copied to.
  72053. */
  72054. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72056. if (space == BABYLON.Space.LOCAL) {
  72057. this.getLocalMatrix().getRotationMatrixToRef(result);
  72058. }
  72059. else {
  72060. var mat = Bone._tmpMats[0];
  72061. var amat = this.getAbsoluteTransform();
  72062. if (mesh) {
  72063. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72064. }
  72065. else {
  72066. mat.copyFrom(amat);
  72067. }
  72068. mat.m[0] *= this._scalingDeterminant;
  72069. mat.m[1] *= this._scalingDeterminant;
  72070. mat.m[2] *= this._scalingDeterminant;
  72071. mat.getRotationMatrixToRef(result);
  72072. }
  72073. };
  72074. /**
  72075. * Get the world position of a point that is in the local space of the bone.
  72076. * @param position The local position
  72077. * @param mesh The mesh that this bone is attached to.
  72078. * @returns The world position
  72079. */
  72080. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72081. if (mesh === void 0) { mesh = null; }
  72082. var result = BABYLON.Vector3.Zero();
  72083. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72084. return result;
  72085. };
  72086. /**
  72087. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72088. * @param position The local position
  72089. * @param mesh The mesh that this bone is attached to.
  72090. * @param result The vector3 that the world position should be copied to.
  72091. */
  72092. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72093. if (mesh === void 0) { mesh = null; }
  72094. var wm = null;
  72095. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72096. if (mesh) {
  72097. wm = mesh.getWorldMatrix();
  72098. }
  72099. this._skeleton.computeAbsoluteTransforms();
  72100. var tmat = Bone._tmpMats[0];
  72101. if (mesh && wm) {
  72102. tmat.copyFrom(this.getAbsoluteTransform());
  72103. tmat.multiplyToRef(wm, tmat);
  72104. }
  72105. else {
  72106. tmat = this.getAbsoluteTransform();
  72107. }
  72108. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72109. };
  72110. /**
  72111. * Get the local position of a point that is in world space.
  72112. * @param position The world position
  72113. * @param mesh The mesh that this bone is attached to.
  72114. * @returns The local position
  72115. */
  72116. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72117. if (mesh === void 0) { mesh = null; }
  72118. var result = BABYLON.Vector3.Zero();
  72119. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72120. return result;
  72121. };
  72122. /**
  72123. * Get the local position of a point that is in world space and copy it to the result param.
  72124. * @param position The world position
  72125. * @param mesh The mesh that this bone is attached to.
  72126. * @param result The vector3 that the local position should be copied to.
  72127. */
  72128. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72129. if (mesh === void 0) { mesh = null; }
  72130. var wm = null;
  72131. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72132. if (mesh) {
  72133. wm = mesh.getWorldMatrix();
  72134. }
  72135. this._skeleton.computeAbsoluteTransforms();
  72136. var tmat = Bone._tmpMats[0];
  72137. tmat.copyFrom(this.getAbsoluteTransform());
  72138. if (mesh && wm) {
  72139. tmat.multiplyToRef(wm, tmat);
  72140. }
  72141. tmat.invert();
  72142. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72143. };
  72144. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72145. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72146. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72147. return Bone;
  72148. }(BABYLON.Node));
  72149. BABYLON.Bone = Bone;
  72150. })(BABYLON || (BABYLON = {}));
  72151. //# sourceMappingURL=babylon.bone.js.map
  72152. var BABYLON;
  72153. (function (BABYLON) {
  72154. var BoneIKController = /** @class */ (function () {
  72155. function BoneIKController(mesh, bone, options) {
  72156. this.targetPosition = BABYLON.Vector3.Zero();
  72157. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72158. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72159. this.poleAngle = 0;
  72160. this.slerpAmount = 1;
  72161. this._bone1Quat = BABYLON.Quaternion.Identity();
  72162. this._bone1Mat = BABYLON.Matrix.Identity();
  72163. this._bone2Ang = Math.PI;
  72164. this._maxAngle = Math.PI;
  72165. this._rightHandedSystem = false;
  72166. this._bendAxis = BABYLON.Vector3.Right();
  72167. this._slerping = false;
  72168. this._adjustRoll = 0;
  72169. this._bone2 = bone;
  72170. this._bone1 = bone.getParent();
  72171. if (!this._bone1) {
  72172. return;
  72173. }
  72174. this.mesh = mesh;
  72175. var bonePos = bone.getPosition();
  72176. if (bone.getAbsoluteTransform().determinant() > 0) {
  72177. this._rightHandedSystem = true;
  72178. this._bendAxis.x = 0;
  72179. this._bendAxis.y = 0;
  72180. this._bendAxis.z = -1;
  72181. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72182. this._adjustRoll = Math.PI * .5;
  72183. this._bendAxis.z = 1;
  72184. }
  72185. }
  72186. if (this._bone1.length) {
  72187. var boneScale1 = this._bone1.getScale();
  72188. var boneScale2 = this._bone2.getScale();
  72189. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72190. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72191. }
  72192. else if (this._bone1.children[0]) {
  72193. mesh.computeWorldMatrix(true);
  72194. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72195. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72196. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72197. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72198. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72199. }
  72200. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72201. this.maxAngle = Math.PI;
  72202. if (options) {
  72203. if (options.targetMesh) {
  72204. this.targetMesh = options.targetMesh;
  72205. this.targetMesh.computeWorldMatrix(true);
  72206. }
  72207. if (options.poleTargetMesh) {
  72208. this.poleTargetMesh = options.poleTargetMesh;
  72209. this.poleTargetMesh.computeWorldMatrix(true);
  72210. }
  72211. else if (options.poleTargetBone) {
  72212. this.poleTargetBone = options.poleTargetBone;
  72213. }
  72214. else if (this._bone1.getParent()) {
  72215. this.poleTargetBone = this._bone1.getParent();
  72216. }
  72217. if (options.poleTargetLocalOffset) {
  72218. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72219. }
  72220. if (options.poleAngle) {
  72221. this.poleAngle = options.poleAngle;
  72222. }
  72223. if (options.bendAxis) {
  72224. this._bendAxis.copyFrom(options.bendAxis);
  72225. }
  72226. if (options.maxAngle) {
  72227. this.maxAngle = options.maxAngle;
  72228. }
  72229. if (options.slerpAmount) {
  72230. this.slerpAmount = options.slerpAmount;
  72231. }
  72232. }
  72233. }
  72234. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72235. get: function () {
  72236. return this._maxAngle;
  72237. },
  72238. set: function (value) {
  72239. this._setMaxAngle(value);
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. BoneIKController.prototype._setMaxAngle = function (ang) {
  72245. if (ang < 0) {
  72246. ang = 0;
  72247. }
  72248. if (ang > Math.PI || ang == undefined) {
  72249. ang = Math.PI;
  72250. }
  72251. this._maxAngle = ang;
  72252. var a = this._bone1Length;
  72253. var b = this._bone2Length;
  72254. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72255. };
  72256. BoneIKController.prototype.update = function () {
  72257. var bone1 = this._bone1;
  72258. if (!bone1) {
  72259. return;
  72260. }
  72261. var target = this.targetPosition;
  72262. var poleTarget = this.poleTargetPosition;
  72263. var mat1 = BoneIKController._tmpMats[0];
  72264. var mat2 = BoneIKController._tmpMats[1];
  72265. if (this.targetMesh) {
  72266. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72267. }
  72268. if (this.poleTargetBone) {
  72269. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72270. }
  72271. else if (this.poleTargetMesh) {
  72272. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72273. }
  72274. var bonePos = BoneIKController._tmpVecs[0];
  72275. var zaxis = BoneIKController._tmpVecs[1];
  72276. var xaxis = BoneIKController._tmpVecs[2];
  72277. var yaxis = BoneIKController._tmpVecs[3];
  72278. var upAxis = BoneIKController._tmpVecs[4];
  72279. var _tmpQuat = BoneIKController._tmpQuat;
  72280. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72281. poleTarget.subtractToRef(bonePos, upAxis);
  72282. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72283. upAxis.y = 1;
  72284. }
  72285. else {
  72286. upAxis.normalize();
  72287. }
  72288. target.subtractToRef(bonePos, yaxis);
  72289. yaxis.normalize();
  72290. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72291. zaxis.normalize();
  72292. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72293. xaxis.normalize();
  72294. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72295. var a = this._bone1Length;
  72296. var b = this._bone2Length;
  72297. var c = BABYLON.Vector3.Distance(bonePos, target);
  72298. if (this._maxReach > 0) {
  72299. c = Math.min(this._maxReach, c);
  72300. }
  72301. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72302. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72303. if (acosa > 1) {
  72304. acosa = 1;
  72305. }
  72306. if (acosb > 1) {
  72307. acosb = 1;
  72308. }
  72309. if (acosa < -1) {
  72310. acosa = -1;
  72311. }
  72312. if (acosb < -1) {
  72313. acosb = -1;
  72314. }
  72315. var angA = Math.acos(acosa);
  72316. var angB = Math.acos(acosb);
  72317. var angC = -angA - angB;
  72318. if (this._rightHandedSystem) {
  72319. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72320. mat2.multiplyToRef(mat1, mat1);
  72321. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72322. mat2.multiplyToRef(mat1, mat1);
  72323. }
  72324. else {
  72325. var _tmpVec = BoneIKController._tmpVecs[5];
  72326. _tmpVec.copyFrom(this._bendAxis);
  72327. _tmpVec.x *= -1;
  72328. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72329. mat2.multiplyToRef(mat1, mat1);
  72330. }
  72331. if (this.poleAngle) {
  72332. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72333. mat1.multiplyToRef(mat2, mat1);
  72334. }
  72335. if (this._bone1) {
  72336. if (this.slerpAmount < 1) {
  72337. if (!this._slerping) {
  72338. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72339. }
  72340. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72341. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72342. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72343. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72344. this._slerping = true;
  72345. }
  72346. else {
  72347. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72348. this._bone1Mat.copyFrom(mat1);
  72349. this._slerping = false;
  72350. }
  72351. }
  72352. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72353. this._bone2Ang = angC;
  72354. };
  72355. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72356. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72357. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72358. return BoneIKController;
  72359. }());
  72360. BABYLON.BoneIKController = BoneIKController;
  72361. })(BABYLON || (BABYLON = {}));
  72362. //# sourceMappingURL=babylon.boneIKController.js.map
  72363. var BABYLON;
  72364. (function (BABYLON) {
  72365. var BoneLookController = /** @class */ (function () {
  72366. /**
  72367. * Create a BoneLookController
  72368. * @param mesh the mesh that the bone belongs to
  72369. * @param bone the bone that will be looking to the target
  72370. * @param target the target Vector3 to look at
  72371. * @param settings optional settings:
  72372. * - maxYaw: the maximum angle the bone will yaw to
  72373. * - minYaw: the minimum angle the bone will yaw to
  72374. * - maxPitch: the maximum angle the bone will pitch to
  72375. * - minPitch: the minimum angle the bone will yaw to
  72376. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72377. * - upAxis: the up axis of the coordinate system
  72378. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72379. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72380. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72381. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72382. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72383. * - adjustRoll: used to make an adjustment to the roll of the bone
  72384. **/
  72385. function BoneLookController(mesh, bone, target, options) {
  72386. /**
  72387. * The up axis of the coordinate system that is used when the bone is rotated.
  72388. */
  72389. this.upAxis = BABYLON.Vector3.Up();
  72390. /**
  72391. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72392. */
  72393. this.upAxisSpace = BABYLON.Space.LOCAL;
  72394. /**
  72395. * Used to make an adjustment to the yaw of the bone.
  72396. */
  72397. this.adjustYaw = 0;
  72398. /**
  72399. * Used to make an adjustment to the pitch of the bone.
  72400. */
  72401. this.adjustPitch = 0;
  72402. /**
  72403. * Used to make an adjustment to the roll of the bone.
  72404. */
  72405. this.adjustRoll = 0;
  72406. /**
  72407. * 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).
  72408. */
  72409. this.slerpAmount = 1;
  72410. this._boneQuat = BABYLON.Quaternion.Identity();
  72411. this._slerping = false;
  72412. this._firstFrameSkipped = false;
  72413. this._fowardAxis = BABYLON.Vector3.Forward();
  72414. this.mesh = mesh;
  72415. this.bone = bone;
  72416. this.target = target;
  72417. if (options) {
  72418. if (options.adjustYaw) {
  72419. this.adjustYaw = options.adjustYaw;
  72420. }
  72421. if (options.adjustPitch) {
  72422. this.adjustPitch = options.adjustPitch;
  72423. }
  72424. if (options.adjustRoll) {
  72425. this.adjustRoll = options.adjustRoll;
  72426. }
  72427. if (options.maxYaw != null) {
  72428. this.maxYaw = options.maxYaw;
  72429. }
  72430. else {
  72431. this.maxYaw = Math.PI;
  72432. }
  72433. if (options.minYaw != null) {
  72434. this.minYaw = options.minYaw;
  72435. }
  72436. else {
  72437. this.minYaw = -Math.PI;
  72438. }
  72439. if (options.maxPitch != null) {
  72440. this.maxPitch = options.maxPitch;
  72441. }
  72442. else {
  72443. this.maxPitch = Math.PI;
  72444. }
  72445. if (options.minPitch != null) {
  72446. this.minPitch = options.minPitch;
  72447. }
  72448. else {
  72449. this.minPitch = -Math.PI;
  72450. }
  72451. if (options.slerpAmount != null) {
  72452. this.slerpAmount = options.slerpAmount;
  72453. }
  72454. if (options.upAxis != null) {
  72455. this.upAxis = options.upAxis;
  72456. }
  72457. if (options.upAxisSpace != null) {
  72458. this.upAxisSpace = options.upAxisSpace;
  72459. }
  72460. if (options.yawAxis != null || options.pitchAxis != null) {
  72461. var newYawAxis = BABYLON.Axis.Y;
  72462. var newPitchAxis = BABYLON.Axis.X;
  72463. if (options.yawAxis != null) {
  72464. newYawAxis = options.yawAxis.clone();
  72465. newYawAxis.normalize();
  72466. }
  72467. if (options.pitchAxis != null) {
  72468. newPitchAxis = options.pitchAxis.clone();
  72469. newPitchAxis.normalize();
  72470. }
  72471. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72472. this._transformYawPitch = BABYLON.Matrix.Identity();
  72473. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72474. this._transformYawPitchInv = this._transformYawPitch.clone();
  72475. this._transformYawPitch.invert();
  72476. }
  72477. }
  72478. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72479. this.upAxisSpace = BABYLON.Space.LOCAL;
  72480. }
  72481. }
  72482. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72483. /**
  72484. * Get/set the minimum yaw angle that the bone can look to.
  72485. */
  72486. get: function () {
  72487. return this._minYaw;
  72488. },
  72489. set: function (value) {
  72490. this._minYaw = value;
  72491. this._minYawSin = Math.sin(value);
  72492. this._minYawCos = Math.cos(value);
  72493. if (this._maxYaw != null) {
  72494. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72495. this._yawRange = this._maxYaw - this._minYaw;
  72496. }
  72497. },
  72498. enumerable: true,
  72499. configurable: true
  72500. });
  72501. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72502. /**
  72503. * Get/set the maximum yaw angle that the bone can look to.
  72504. */
  72505. get: function () {
  72506. return this._maxYaw;
  72507. },
  72508. set: function (value) {
  72509. this._maxYaw = value;
  72510. this._maxYawSin = Math.sin(value);
  72511. this._maxYawCos = Math.cos(value);
  72512. if (this._minYaw != null) {
  72513. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72514. this._yawRange = this._maxYaw - this._minYaw;
  72515. }
  72516. },
  72517. enumerable: true,
  72518. configurable: true
  72519. });
  72520. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72521. /**
  72522. * Get/set the minimum pitch angle that the bone can look to.
  72523. */
  72524. get: function () {
  72525. return this._minPitch;
  72526. },
  72527. set: function (value) {
  72528. this._minPitch = value;
  72529. this._minPitchTan = Math.tan(value);
  72530. },
  72531. enumerable: true,
  72532. configurable: true
  72533. });
  72534. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72535. /**
  72536. * Get/set the maximum pitch angle that the bone can look to.
  72537. */
  72538. get: function () {
  72539. return this._maxPitch;
  72540. },
  72541. set: function (value) {
  72542. this._maxPitch = value;
  72543. this._maxPitchTan = Math.tan(value);
  72544. },
  72545. enumerable: true,
  72546. configurable: true
  72547. });
  72548. /**
  72549. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72550. */
  72551. BoneLookController.prototype.update = function () {
  72552. //skip the first frame when slerping so that the mesh rotation is correct
  72553. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72554. this._firstFrameSkipped = true;
  72555. return;
  72556. }
  72557. var bone = this.bone;
  72558. var bonePos = BoneLookController._tmpVecs[0];
  72559. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72560. var target = this.target;
  72561. var _tmpMat1 = BoneLookController._tmpMats[0];
  72562. var _tmpMat2 = BoneLookController._tmpMats[1];
  72563. var mesh = this.mesh;
  72564. var parentBone = bone.getParent();
  72565. var upAxis = BoneLookController._tmpVecs[1];
  72566. upAxis.copyFrom(this.upAxis);
  72567. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72568. if (this._transformYawPitch) {
  72569. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72570. }
  72571. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72572. }
  72573. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72574. mesh.getDirectionToRef(upAxis, upAxis);
  72575. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72576. upAxis.normalize();
  72577. }
  72578. }
  72579. var checkYaw = false;
  72580. var checkPitch = false;
  72581. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72582. checkYaw = true;
  72583. }
  72584. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72585. checkPitch = true;
  72586. }
  72587. if (checkYaw || checkPitch) {
  72588. var spaceMat = BoneLookController._tmpMats[2];
  72589. var spaceMatInv = BoneLookController._tmpMats[3];
  72590. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72591. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72592. }
  72593. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72594. spaceMat.copyFrom(mesh.getWorldMatrix());
  72595. }
  72596. else {
  72597. var forwardAxis = BoneLookController._tmpVecs[2];
  72598. forwardAxis.copyFrom(this._fowardAxis);
  72599. if (this._transformYawPitch) {
  72600. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72601. }
  72602. if (parentBone) {
  72603. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72604. }
  72605. else {
  72606. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72607. }
  72608. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72609. rightAxis.normalize();
  72610. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72611. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72612. }
  72613. spaceMat.invertToRef(spaceMatInv);
  72614. var xzlen = null;
  72615. if (checkPitch) {
  72616. var localTarget = BoneLookController._tmpVecs[3];
  72617. target.subtractToRef(bonePos, localTarget);
  72618. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72619. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72620. var pitch = Math.atan2(localTarget.y, xzlen);
  72621. var newPitch = pitch;
  72622. if (pitch > this._maxPitch) {
  72623. localTarget.y = this._maxPitchTan * xzlen;
  72624. newPitch = this._maxPitch;
  72625. }
  72626. else if (pitch < this._minPitch) {
  72627. localTarget.y = this._minPitchTan * xzlen;
  72628. newPitch = this._minPitch;
  72629. }
  72630. if (pitch != newPitch) {
  72631. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72632. localTarget.addInPlace(bonePos);
  72633. target = localTarget;
  72634. }
  72635. }
  72636. if (checkYaw) {
  72637. var localTarget = BoneLookController._tmpVecs[4];
  72638. target.subtractToRef(bonePos, localTarget);
  72639. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72640. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72641. var newYaw = yaw;
  72642. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72643. if (xzlen == null) {
  72644. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72645. }
  72646. if (this._yawRange > Math.PI) {
  72647. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72648. localTarget.z = this._maxYawCos * xzlen;
  72649. localTarget.x = this._maxYawSin * xzlen;
  72650. newYaw = this._maxYaw;
  72651. }
  72652. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72653. localTarget.z = this._minYawCos * xzlen;
  72654. localTarget.x = this._minYawSin * xzlen;
  72655. newYaw = this._minYaw;
  72656. }
  72657. }
  72658. else {
  72659. if (yaw > this._maxYaw) {
  72660. localTarget.z = this._maxYawCos * xzlen;
  72661. localTarget.x = this._maxYawSin * xzlen;
  72662. newYaw = this._maxYaw;
  72663. }
  72664. else if (yaw < this._minYaw) {
  72665. localTarget.z = this._minYawCos * xzlen;
  72666. localTarget.x = this._minYawSin * xzlen;
  72667. newYaw = this._minYaw;
  72668. }
  72669. }
  72670. }
  72671. if (this._slerping && this._yawRange > Math.PI) {
  72672. //are we going to be crossing into the min/max region?
  72673. var boneFwd = BoneLookController._tmpVecs[8];
  72674. boneFwd.copyFrom(BABYLON.Axis.Z);
  72675. if (this._transformYawPitch) {
  72676. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72677. }
  72678. var boneRotMat = BoneLookController._tmpMats[4];
  72679. this._boneQuat.toRotationMatrix(boneRotMat);
  72680. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72681. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72682. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72683. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72684. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72685. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72686. if (angBtwTar > angBtwMidYaw) {
  72687. if (xzlen == null) {
  72688. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72689. }
  72690. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72691. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72692. if (angBtwMin < angBtwMax) {
  72693. newYaw = boneYaw + Math.PI * .75;
  72694. localTarget.z = Math.cos(newYaw) * xzlen;
  72695. localTarget.x = Math.sin(newYaw) * xzlen;
  72696. }
  72697. else {
  72698. newYaw = boneYaw - Math.PI * .75;
  72699. localTarget.z = Math.cos(newYaw) * xzlen;
  72700. localTarget.x = Math.sin(newYaw) * xzlen;
  72701. }
  72702. }
  72703. }
  72704. if (yaw != newYaw) {
  72705. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72706. localTarget.addInPlace(bonePos);
  72707. target = localTarget;
  72708. }
  72709. }
  72710. }
  72711. var zaxis = BoneLookController._tmpVecs[5];
  72712. var xaxis = BoneLookController._tmpVecs[6];
  72713. var yaxis = BoneLookController._tmpVecs[7];
  72714. var _tmpQuat = BoneLookController._tmpQuat;
  72715. target.subtractToRef(bonePos, zaxis);
  72716. zaxis.normalize();
  72717. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72718. xaxis.normalize();
  72719. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72720. yaxis.normalize();
  72721. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72722. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72723. return;
  72724. }
  72725. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72726. return;
  72727. }
  72728. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72729. return;
  72730. }
  72731. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72732. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72733. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72734. }
  72735. if (this.slerpAmount < 1) {
  72736. if (!this._slerping) {
  72737. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72738. }
  72739. if (this._transformYawPitch) {
  72740. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72741. }
  72742. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72743. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72744. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72745. this._slerping = true;
  72746. }
  72747. else {
  72748. if (this._transformYawPitch) {
  72749. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72750. }
  72751. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72752. this._slerping = false;
  72753. }
  72754. };
  72755. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72756. var angDiff = ang2 - ang1;
  72757. angDiff %= Math.PI * 2;
  72758. if (angDiff > Math.PI) {
  72759. angDiff -= Math.PI * 2;
  72760. }
  72761. else if (angDiff < -Math.PI) {
  72762. angDiff += Math.PI * 2;
  72763. }
  72764. return angDiff;
  72765. };
  72766. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72767. ang1 %= (2 * Math.PI);
  72768. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72769. ang2 %= (2 * Math.PI);
  72770. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72771. var ab = 0;
  72772. if (ang1 < ang2) {
  72773. ab = ang2 - ang1;
  72774. }
  72775. else {
  72776. ab = ang1 - ang2;
  72777. }
  72778. if (ab > Math.PI) {
  72779. ab = Math.PI * 2 - ab;
  72780. }
  72781. return ab;
  72782. };
  72783. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72784. ang %= (2 * Math.PI);
  72785. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72786. ang1 %= (2 * Math.PI);
  72787. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72788. ang2 %= (2 * Math.PI);
  72789. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72790. if (ang1 < ang2) {
  72791. if (ang > ang1 && ang < ang2) {
  72792. return true;
  72793. }
  72794. }
  72795. else {
  72796. if (ang > ang2 && ang < ang1) {
  72797. return true;
  72798. }
  72799. }
  72800. return false;
  72801. };
  72802. 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()];
  72803. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72804. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72805. return BoneLookController;
  72806. }());
  72807. BABYLON.BoneLookController = BoneLookController;
  72808. })(BABYLON || (BABYLON = {}));
  72809. //# sourceMappingURL=babylon.boneLookController.js.map
  72810. var BABYLON;
  72811. (function (BABYLON) {
  72812. var Skeleton = /** @class */ (function () {
  72813. function Skeleton(name, id, scene) {
  72814. this.name = name;
  72815. this.id = id;
  72816. this.bones = new Array();
  72817. this.needInitialSkinMatrix = false;
  72818. this._isDirty = true;
  72819. this._meshesWithPoseMatrix = new Array();
  72820. this._identity = BABYLON.Matrix.Identity();
  72821. this._ranges = {};
  72822. this._lastAbsoluteTransformsUpdateId = -1;
  72823. /**
  72824. * Specifies if the skeleton should be serialized.
  72825. */
  72826. this.doNotSerialize = false;
  72827. // Events
  72828. /**
  72829. * An event triggered before computing the skeleton's matrices
  72830. * @type {BABYLON.Observable}
  72831. */
  72832. this.onBeforeComputeObservable = new BABYLON.Observable();
  72833. this.bones = [];
  72834. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72835. scene.skeletons.push(this);
  72836. //make sure it will recalculate the matrix next time prepare is called.
  72837. this._isDirty = true;
  72838. }
  72839. // Members
  72840. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72841. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72842. return mesh._bonesTransformMatrices;
  72843. }
  72844. if (!this._transformMatrices) {
  72845. this.prepare();
  72846. }
  72847. return this._transformMatrices;
  72848. };
  72849. Skeleton.prototype.getScene = function () {
  72850. return this._scene;
  72851. };
  72852. // Methods
  72853. /**
  72854. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72855. */
  72856. Skeleton.prototype.toString = function (fullDetails) {
  72857. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72858. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72859. if (fullDetails) {
  72860. ret += ", Ranges: {";
  72861. var first = true;
  72862. for (var name_1 in this._ranges) {
  72863. if (first) {
  72864. ret += ", ";
  72865. first = false;
  72866. }
  72867. ret += name_1;
  72868. }
  72869. ret += "}";
  72870. }
  72871. return ret;
  72872. };
  72873. /**
  72874. * Get bone's index searching by name
  72875. * @param {string} name is bone's name to search for
  72876. * @return {number} Indice of the bone. Returns -1 if not found
  72877. */
  72878. Skeleton.prototype.getBoneIndexByName = function (name) {
  72879. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72880. if (this.bones[boneIndex].name === name) {
  72881. return boneIndex;
  72882. }
  72883. }
  72884. return -1;
  72885. };
  72886. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72887. // check name not already in use
  72888. if (!this._ranges[name]) {
  72889. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72890. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72891. if (this.bones[i].animations[0]) {
  72892. this.bones[i].animations[0].createRange(name, from, to);
  72893. }
  72894. }
  72895. }
  72896. };
  72897. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72898. if (deleteFrames === void 0) { deleteFrames = true; }
  72899. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72900. if (this.bones[i].animations[0]) {
  72901. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72902. }
  72903. }
  72904. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72905. };
  72906. Skeleton.prototype.getAnimationRange = function (name) {
  72907. return this._ranges[name];
  72908. };
  72909. /**
  72910. * Returns as an Array, all AnimationRanges defined on this skeleton
  72911. */
  72912. Skeleton.prototype.getAnimationRanges = function () {
  72913. var animationRanges = [];
  72914. var name;
  72915. var i = 0;
  72916. for (name in this._ranges) {
  72917. animationRanges[i] = this._ranges[name];
  72918. i++;
  72919. }
  72920. return animationRanges;
  72921. };
  72922. /**
  72923. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72924. */
  72925. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72926. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72927. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72928. return false;
  72929. }
  72930. var ret = true;
  72931. var frameOffset = this._getHighestAnimationFrame() + 1;
  72932. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72933. var boneDict = {};
  72934. var sourceBones = source.bones;
  72935. var nBones;
  72936. var i;
  72937. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72938. boneDict[sourceBones[i].name] = sourceBones[i];
  72939. }
  72940. if (this.bones.length !== sourceBones.length) {
  72941. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72942. ret = false;
  72943. }
  72944. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72945. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72946. var boneName = this.bones[i].name;
  72947. var sourceBone = boneDict[boneName];
  72948. if (sourceBone) {
  72949. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72950. }
  72951. else {
  72952. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72953. ret = false;
  72954. }
  72955. }
  72956. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72957. var range = source.getAnimationRange(name);
  72958. if (range) {
  72959. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72960. }
  72961. return ret;
  72962. };
  72963. Skeleton.prototype.returnToRest = function () {
  72964. for (var index = 0; index < this.bones.length; index++) {
  72965. this.bones[index].returnToRest();
  72966. }
  72967. };
  72968. Skeleton.prototype._getHighestAnimationFrame = function () {
  72969. var ret = 0;
  72970. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72971. if (this.bones[i].animations[0]) {
  72972. var highest = this.bones[i].animations[0].getHighestFrame();
  72973. if (ret < highest) {
  72974. ret = highest;
  72975. }
  72976. }
  72977. }
  72978. return ret;
  72979. };
  72980. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72981. var range = this.getAnimationRange(name);
  72982. if (!range) {
  72983. return null;
  72984. }
  72985. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72986. };
  72987. Skeleton.prototype._markAsDirty = function () {
  72988. this._isDirty = true;
  72989. };
  72990. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72991. this._meshesWithPoseMatrix.push(mesh);
  72992. };
  72993. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72994. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72995. if (index > -1) {
  72996. this._meshesWithPoseMatrix.splice(index, 1);
  72997. }
  72998. };
  72999. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73000. this.onBeforeComputeObservable.notifyObservers(this);
  73001. for (var index = 0; index < this.bones.length; index++) {
  73002. var bone = this.bones[index];
  73003. var parentBone = bone.getParent();
  73004. if (parentBone) {
  73005. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73006. }
  73007. else {
  73008. if (initialSkinMatrix) {
  73009. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73010. }
  73011. else {
  73012. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73013. }
  73014. }
  73015. if (bone._index !== -1) {
  73016. var mappedIndex = bone._index === null ? index : bone._index;
  73017. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73018. }
  73019. }
  73020. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73021. };
  73022. Skeleton.prototype.prepare = function () {
  73023. if (!this._isDirty) {
  73024. return;
  73025. }
  73026. if (this.needInitialSkinMatrix) {
  73027. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73028. var mesh = this._meshesWithPoseMatrix[index];
  73029. var poseMatrix = mesh.getPoseMatrix();
  73030. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73031. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73032. }
  73033. if (this._synchronizedWithMesh !== mesh) {
  73034. this._synchronizedWithMesh = mesh;
  73035. // Prepare bones
  73036. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73037. var bone = this.bones[boneIndex];
  73038. if (!bone.getParent()) {
  73039. var matrix = bone.getBaseMatrix();
  73040. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73041. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73042. }
  73043. }
  73044. }
  73045. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73046. }
  73047. }
  73048. else {
  73049. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73050. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73051. }
  73052. this._computeTransformMatrices(this._transformMatrices, null);
  73053. }
  73054. this._isDirty = false;
  73055. this._scene._activeBones.addCount(this.bones.length, false);
  73056. };
  73057. Skeleton.prototype.getAnimatables = function () {
  73058. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73059. this._animatables = [];
  73060. for (var index = 0; index < this.bones.length; index++) {
  73061. this._animatables.push(this.bones[index]);
  73062. }
  73063. }
  73064. return this._animatables;
  73065. };
  73066. Skeleton.prototype.clone = function (name, id) {
  73067. var result = new Skeleton(name, id || name, this._scene);
  73068. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73069. for (var index = 0; index < this.bones.length; index++) {
  73070. var source = this.bones[index];
  73071. var parentBone = null;
  73072. var parent_1 = source.getParent();
  73073. if (parent_1) {
  73074. var parentIndex = this.bones.indexOf(parent_1);
  73075. parentBone = result.bones[parentIndex];
  73076. }
  73077. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73078. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73079. }
  73080. if (this._ranges) {
  73081. result._ranges = {};
  73082. for (var rangeName in this._ranges) {
  73083. var range = this._ranges[rangeName];
  73084. if (range) {
  73085. result._ranges[rangeName] = range.clone();
  73086. }
  73087. }
  73088. }
  73089. this._isDirty = true;
  73090. return result;
  73091. };
  73092. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73093. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73094. this.bones.forEach(function (bone) {
  73095. bone.animations.forEach(function (animation) {
  73096. animation.enableBlending = true;
  73097. animation.blendingSpeed = blendingSpeed;
  73098. });
  73099. });
  73100. };
  73101. Skeleton.prototype.dispose = function () {
  73102. this._meshesWithPoseMatrix = [];
  73103. // Animations
  73104. this.getScene().stopAnimation(this);
  73105. // Remove from scene
  73106. this.getScene().removeSkeleton(this);
  73107. };
  73108. Skeleton.prototype.serialize = function () {
  73109. var serializationObject = {};
  73110. serializationObject.name = this.name;
  73111. serializationObject.id = this.id;
  73112. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73113. serializationObject.bones = [];
  73114. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73115. for (var index = 0; index < this.bones.length; index++) {
  73116. var bone = this.bones[index];
  73117. var parent_2 = bone.getParent();
  73118. var serializedBone = {
  73119. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73120. name: bone.name,
  73121. matrix: bone.getBaseMatrix().toArray(),
  73122. rest: bone.getRestPose().toArray()
  73123. };
  73124. serializationObject.bones.push(serializedBone);
  73125. if (bone.length) {
  73126. serializedBone.length = bone.length;
  73127. }
  73128. if (bone.animations && bone.animations.length > 0) {
  73129. serializedBone.animation = bone.animations[0].serialize();
  73130. }
  73131. serializationObject.ranges = [];
  73132. for (var name in this._ranges) {
  73133. var source = this._ranges[name];
  73134. if (!source) {
  73135. continue;
  73136. }
  73137. var range = {};
  73138. range.name = name;
  73139. range.from = source.from;
  73140. range.to = source.to;
  73141. serializationObject.ranges.push(range);
  73142. }
  73143. }
  73144. return serializationObject;
  73145. };
  73146. Skeleton.Parse = function (parsedSkeleton, scene) {
  73147. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73148. if (parsedSkeleton.dimensionsAtRest) {
  73149. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73150. }
  73151. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73152. var index;
  73153. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73154. var parsedBone = parsedSkeleton.bones[index];
  73155. var parentBone = null;
  73156. if (parsedBone.parentBoneIndex > -1) {
  73157. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73158. }
  73159. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73160. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73161. if (parsedBone.length) {
  73162. bone.length = parsedBone.length;
  73163. }
  73164. if (parsedBone.animation) {
  73165. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73166. }
  73167. }
  73168. // placed after bones, so createAnimationRange can cascade down
  73169. if (parsedSkeleton.ranges) {
  73170. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73171. var data = parsedSkeleton.ranges[index];
  73172. skeleton.createAnimationRange(data.name, data.from, data.to);
  73173. }
  73174. }
  73175. return skeleton;
  73176. };
  73177. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73178. if (forceUpdate === void 0) { forceUpdate = false; }
  73179. var renderId = this._scene.getRenderId();
  73180. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73181. this.bones[0].computeAbsoluteTransforms();
  73182. this._lastAbsoluteTransformsUpdateId = renderId;
  73183. }
  73184. };
  73185. Skeleton.prototype.getPoseMatrix = function () {
  73186. var poseMatrix = null;
  73187. if (this._meshesWithPoseMatrix.length > 0) {
  73188. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73189. }
  73190. return poseMatrix;
  73191. };
  73192. Skeleton.prototype.sortBones = function () {
  73193. var bones = new Array();
  73194. var visited = new Array(this.bones.length);
  73195. for (var index = 0; index < this.bones.length; index++) {
  73196. this._sortBones(index, bones, visited);
  73197. }
  73198. this.bones = bones;
  73199. };
  73200. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73201. if (visited[index]) {
  73202. return;
  73203. }
  73204. visited[index] = true;
  73205. var bone = this.bones[index];
  73206. if (bone._index === undefined) {
  73207. bone._index = index;
  73208. }
  73209. var parentBone = bone.getParent();
  73210. if (parentBone) {
  73211. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73212. }
  73213. bones.push(bone);
  73214. };
  73215. return Skeleton;
  73216. }());
  73217. BABYLON.Skeleton = Skeleton;
  73218. })(BABYLON || (BABYLON = {}));
  73219. //# sourceMappingURL=babylon.skeleton.js.map
  73220. var BABYLON;
  73221. (function (BABYLON) {
  73222. var SphericalPolynomial = /** @class */ (function () {
  73223. function SphericalPolynomial() {
  73224. this.x = BABYLON.Vector3.Zero();
  73225. this.y = BABYLON.Vector3.Zero();
  73226. this.z = BABYLON.Vector3.Zero();
  73227. this.xx = BABYLON.Vector3.Zero();
  73228. this.yy = BABYLON.Vector3.Zero();
  73229. this.zz = BABYLON.Vector3.Zero();
  73230. this.xy = BABYLON.Vector3.Zero();
  73231. this.yz = BABYLON.Vector3.Zero();
  73232. this.zx = BABYLON.Vector3.Zero();
  73233. }
  73234. SphericalPolynomial.prototype.addAmbient = function (color) {
  73235. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73236. this.xx = this.xx.add(colorVector);
  73237. this.yy = this.yy.add(colorVector);
  73238. this.zz = this.zz.add(colorVector);
  73239. };
  73240. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73241. var result = new SphericalPolynomial();
  73242. result.x = harmonics.L11.scale(1.02333);
  73243. result.y = harmonics.L1_1.scale(1.02333);
  73244. result.z = harmonics.L10.scale(1.02333);
  73245. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73246. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73247. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73248. result.yz = harmonics.L2_1.scale(0.858086);
  73249. result.zx = harmonics.L21.scale(0.858086);
  73250. result.xy = harmonics.L2_2.scale(0.858086);
  73251. result.scale(1.0 / Math.PI);
  73252. return result;
  73253. };
  73254. SphericalPolynomial.prototype.scale = function (scale) {
  73255. this.x = this.x.scale(scale);
  73256. this.y = this.y.scale(scale);
  73257. this.z = this.z.scale(scale);
  73258. this.xx = this.xx.scale(scale);
  73259. this.yy = this.yy.scale(scale);
  73260. this.zz = this.zz.scale(scale);
  73261. this.yz = this.yz.scale(scale);
  73262. this.zx = this.zx.scale(scale);
  73263. this.xy = this.xy.scale(scale);
  73264. };
  73265. return SphericalPolynomial;
  73266. }());
  73267. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73268. var SphericalHarmonics = /** @class */ (function () {
  73269. function SphericalHarmonics() {
  73270. this.L00 = BABYLON.Vector3.Zero();
  73271. this.L1_1 = BABYLON.Vector3.Zero();
  73272. this.L10 = BABYLON.Vector3.Zero();
  73273. this.L11 = BABYLON.Vector3.Zero();
  73274. this.L2_2 = BABYLON.Vector3.Zero();
  73275. this.L2_1 = BABYLON.Vector3.Zero();
  73276. this.L20 = BABYLON.Vector3.Zero();
  73277. this.L21 = BABYLON.Vector3.Zero();
  73278. this.L22 = BABYLON.Vector3.Zero();
  73279. }
  73280. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73281. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73282. var c = colorVector.scale(deltaSolidAngle);
  73283. this.L00 = this.L00.add(c.scale(0.282095));
  73284. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73285. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73286. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73287. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73288. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73289. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73290. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73291. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73292. };
  73293. SphericalHarmonics.prototype.scale = function (scale) {
  73294. this.L00 = this.L00.scale(scale);
  73295. this.L1_1 = this.L1_1.scale(scale);
  73296. this.L10 = this.L10.scale(scale);
  73297. this.L11 = this.L11.scale(scale);
  73298. this.L2_2 = this.L2_2.scale(scale);
  73299. this.L2_1 = this.L2_1.scale(scale);
  73300. this.L20 = this.L20.scale(scale);
  73301. this.L21 = this.L21.scale(scale);
  73302. this.L22 = this.L22.scale(scale);
  73303. };
  73304. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73305. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73306. //
  73307. // E_lm = A_l * L_lm
  73308. //
  73309. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73310. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73311. // the scaling factors are given in equation 9.
  73312. // Constant (Band 0)
  73313. this.L00 = this.L00.scale(3.141593);
  73314. // Linear (Band 1)
  73315. this.L1_1 = this.L1_1.scale(2.094395);
  73316. this.L10 = this.L10.scale(2.094395);
  73317. this.L11 = this.L11.scale(2.094395);
  73318. // Quadratic (Band 2)
  73319. this.L2_2 = this.L2_2.scale(0.785398);
  73320. this.L2_1 = this.L2_1.scale(0.785398);
  73321. this.L20 = this.L20.scale(0.785398);
  73322. this.L21 = this.L21.scale(0.785398);
  73323. this.L22 = this.L22.scale(0.785398);
  73324. };
  73325. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73326. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73327. // L = (1/pi) * E * rho
  73328. //
  73329. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73330. this.scale(1.0 / Math.PI);
  73331. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73332. // (The pixel shader must apply albedo after texture fetches, etc).
  73333. };
  73334. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73335. var result = new SphericalHarmonics();
  73336. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73337. result.L1_1 = polynomial.y.scale(0.977204);
  73338. result.L10 = polynomial.z.scale(0.977204);
  73339. result.L11 = polynomial.x.scale(0.977204);
  73340. result.L2_2 = polynomial.xy.scale(1.16538);
  73341. result.L2_1 = polynomial.yz.scale(1.16538);
  73342. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73343. result.L21 = polynomial.zx.scale(1.16538);
  73344. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73345. result.scale(Math.PI);
  73346. return result;
  73347. };
  73348. return SphericalHarmonics;
  73349. }());
  73350. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73351. })(BABYLON || (BABYLON = {}));
  73352. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73353. var BABYLON;
  73354. (function (BABYLON) {
  73355. var FileFaceOrientation = /** @class */ (function () {
  73356. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73357. this.name = name;
  73358. this.worldAxisForNormal = worldAxisForNormal;
  73359. this.worldAxisForFileX = worldAxisForFileX;
  73360. this.worldAxisForFileY = worldAxisForFileY;
  73361. }
  73362. return FileFaceOrientation;
  73363. }());
  73364. ;
  73365. /**
  73366. * Helper class dealing with the extraction of spherical polynomial dataArray
  73367. * from a cube map.
  73368. */
  73369. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73370. function CubeMapToSphericalPolynomialTools() {
  73371. }
  73372. /**
  73373. * Converts a texture to the according Spherical Polynomial data.
  73374. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73375. *
  73376. * @param texture The texture to extract the information from.
  73377. * @return The Spherical Polynomial data.
  73378. */
  73379. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73380. if (!texture.isCube) {
  73381. // Only supports cube Textures currently.
  73382. return null;
  73383. }
  73384. var size = texture.getSize().width;
  73385. var right = texture.readPixels(0);
  73386. var left = texture.readPixels(1);
  73387. var up;
  73388. var down;
  73389. if (texture.isRenderTarget) {
  73390. up = texture.readPixels(3);
  73391. down = texture.readPixels(2);
  73392. }
  73393. else {
  73394. up = texture.readPixels(2);
  73395. down = texture.readPixels(3);
  73396. }
  73397. var front = texture.readPixels(4);
  73398. var back = texture.readPixels(5);
  73399. var gammaSpace = texture.gammaSpace;
  73400. // Always read as RGBA.
  73401. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73402. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73403. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73404. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73405. }
  73406. var cubeInfo = {
  73407. size: size,
  73408. right: right,
  73409. left: left,
  73410. up: up,
  73411. down: down,
  73412. front: front,
  73413. back: back,
  73414. format: format,
  73415. type: type,
  73416. gammaSpace: gammaSpace,
  73417. };
  73418. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73419. };
  73420. /**
  73421. * Converts a cubemap to the according Spherical Polynomial data.
  73422. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73423. *
  73424. * @param cubeInfo The Cube map to extract the information from.
  73425. * @return The Spherical Polynomial data.
  73426. */
  73427. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73428. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73429. var totalSolidAngle = 0.0;
  73430. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73431. var du = 2.0 / cubeInfo.size;
  73432. var dv = du;
  73433. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73434. var minUV = du * 0.5 - 1.0;
  73435. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73436. var fileFace = this.FileFaces[faceIndex];
  73437. var dataArray = cubeInfo[fileFace.name];
  73438. var v = minUV;
  73439. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73440. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73441. // Because SP is still linear, so summation is fine in that basis.
  73442. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73443. for (var y = 0; y < cubeInfo.size; y++) {
  73444. var u = minUV;
  73445. for (var x = 0; x < cubeInfo.size; x++) {
  73446. // World direction (not normalised)
  73447. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73448. worldDirection.normalize();
  73449. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73450. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73451. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73452. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73453. // Handle Integer types.
  73454. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73455. r /= 255;
  73456. g /= 255;
  73457. b /= 255;
  73458. }
  73459. // Handle Gamma space textures.
  73460. if (cubeInfo.gammaSpace) {
  73461. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73462. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73463. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73464. }
  73465. var color = new BABYLON.Color3(r, g, b);
  73466. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73467. totalSolidAngle += deltaSolidAngle;
  73468. u += du;
  73469. }
  73470. v += dv;
  73471. }
  73472. }
  73473. // Solid angle for entire sphere is 4*pi
  73474. var sphereSolidAngle = 4.0 * Math.PI;
  73475. // Adjust the solid angle to allow for how many faces we processed.
  73476. var facesProcessed = 6.0;
  73477. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73478. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73479. // This is needed because the numerical integration over the cube uses a
  73480. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73481. // and also to compensate for accumulative error due to float precision in the summation.
  73482. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73483. sphericalHarmonics.scale(correctionFactor);
  73484. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73485. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73486. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73487. };
  73488. CubeMapToSphericalPolynomialTools.FileFaces = [
  73489. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73490. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73491. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73492. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73493. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73494. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73495. ];
  73496. return CubeMapToSphericalPolynomialTools;
  73497. }());
  73498. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73499. })(BABYLON || (BABYLON = {}));
  73500. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73501. var BABYLON;
  73502. (function (BABYLON) {
  73503. /**
  73504. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73505. */
  73506. var PanoramaToCubeMapTools = /** @class */ (function () {
  73507. function PanoramaToCubeMapTools() {
  73508. }
  73509. /**
  73510. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73511. *
  73512. * @param float32Array The source data.
  73513. * @param inputWidth The width of the input panorama.
  73514. * @param inputhHeight The height of the input panorama.
  73515. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73516. * @return The cubemap data
  73517. */
  73518. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73519. if (!float32Array) {
  73520. throw "ConvertPanoramaToCubemap: input cannot be null";
  73521. }
  73522. if (float32Array.length != inputWidth * inputHeight * 3) {
  73523. throw "ConvertPanoramaToCubemap: input size is wrong";
  73524. }
  73525. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73526. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73527. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73528. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73529. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73530. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73531. return {
  73532. front: textureFront,
  73533. back: textureBack,
  73534. left: textureLeft,
  73535. right: textureRight,
  73536. up: textureUp,
  73537. down: textureDown,
  73538. size: size,
  73539. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73540. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73541. gammaSpace: false,
  73542. };
  73543. };
  73544. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73545. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73546. var textureArray = new Float32Array(buffer);
  73547. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73548. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73549. var dy = 1 / texSize;
  73550. var fy = 0;
  73551. for (var y = 0; y < texSize; y++) {
  73552. var xv1 = faceData[0];
  73553. var xv2 = faceData[2];
  73554. for (var x = 0; x < texSize; x++) {
  73555. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73556. v.normalize();
  73557. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73558. // 3 channels per pixels
  73559. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73560. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73561. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73562. xv1 = xv1.add(rotDX1);
  73563. xv2 = xv2.add(rotDX2);
  73564. }
  73565. fy += dy;
  73566. }
  73567. return textureArray;
  73568. };
  73569. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73570. var theta = Math.atan2(vDir.z, vDir.x);
  73571. var phi = Math.acos(vDir.y);
  73572. while (theta < -Math.PI)
  73573. theta += 2 * Math.PI;
  73574. while (theta > Math.PI)
  73575. theta -= 2 * Math.PI;
  73576. var dx = theta / Math.PI;
  73577. var dy = phi / Math.PI;
  73578. // recenter.
  73579. dx = dx * 0.5 + 0.5;
  73580. var px = Math.round(dx * inputWidth);
  73581. if (px < 0)
  73582. px = 0;
  73583. else if (px >= inputWidth)
  73584. px = inputWidth - 1;
  73585. var py = Math.round(dy * inputHeight);
  73586. if (py < 0)
  73587. py = 0;
  73588. else if (py >= inputHeight)
  73589. py = inputHeight - 1;
  73590. var inputY = (inputHeight - py - 1);
  73591. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73592. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73593. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73594. return {
  73595. r: r,
  73596. g: g,
  73597. b: b
  73598. };
  73599. };
  73600. PanoramaToCubeMapTools.FACE_FRONT = [
  73601. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73602. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73603. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73604. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73605. ];
  73606. PanoramaToCubeMapTools.FACE_BACK = [
  73607. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73608. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73609. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73610. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73611. ];
  73612. PanoramaToCubeMapTools.FACE_RIGHT = [
  73613. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73614. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73615. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73616. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73617. ];
  73618. PanoramaToCubeMapTools.FACE_LEFT = [
  73619. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73620. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73621. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73622. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73623. ];
  73624. PanoramaToCubeMapTools.FACE_DOWN = [
  73625. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73626. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73627. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73628. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73629. ];
  73630. PanoramaToCubeMapTools.FACE_UP = [
  73631. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73632. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73633. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73634. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73635. ];
  73636. return PanoramaToCubeMapTools;
  73637. }());
  73638. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73639. })(BABYLON || (BABYLON = {}));
  73640. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73641. var BABYLON;
  73642. (function (BABYLON) {
  73643. ;
  73644. /**
  73645. * This groups tools to convert HDR texture to native colors array.
  73646. */
  73647. var HDRTools = /** @class */ (function () {
  73648. function HDRTools() {
  73649. }
  73650. HDRTools.Ldexp = function (mantissa, exponent) {
  73651. if (exponent > 1023) {
  73652. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73653. }
  73654. if (exponent < -1074) {
  73655. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73656. }
  73657. return mantissa * Math.pow(2, exponent);
  73658. };
  73659. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73660. if (exponent > 0) {
  73661. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73662. float32array[index + 0] = red * exponent;
  73663. float32array[index + 1] = green * exponent;
  73664. float32array[index + 2] = blue * exponent;
  73665. }
  73666. else {
  73667. float32array[index + 0] = 0;
  73668. float32array[index + 1] = 0;
  73669. float32array[index + 2] = 0;
  73670. }
  73671. };
  73672. HDRTools.readStringLine = function (uint8array, startIndex) {
  73673. var line = "";
  73674. var character = "";
  73675. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73676. character = String.fromCharCode(uint8array[i]);
  73677. if (character == "\n") {
  73678. break;
  73679. }
  73680. line += character;
  73681. }
  73682. return line;
  73683. };
  73684. /**
  73685. * Reads header information from an RGBE texture stored in a native array.
  73686. * More information on this format are available here:
  73687. * https://en.wikipedia.org/wiki/RGBE_image_format
  73688. *
  73689. * @param uint8array The binary file stored in native array.
  73690. * @return The header information.
  73691. */
  73692. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73693. var height = 0;
  73694. var width = 0;
  73695. var line = this.readStringLine(uint8array, 0);
  73696. if (line[0] != '#' || line[1] != '?') {
  73697. throw "Bad HDR Format.";
  73698. }
  73699. var endOfHeader = false;
  73700. var findFormat = false;
  73701. var lineIndex = 0;
  73702. do {
  73703. lineIndex += (line.length + 1);
  73704. line = this.readStringLine(uint8array, lineIndex);
  73705. if (line == "FORMAT=32-bit_rle_rgbe") {
  73706. findFormat = true;
  73707. }
  73708. else if (line.length == 0) {
  73709. endOfHeader = true;
  73710. }
  73711. } while (!endOfHeader);
  73712. if (!findFormat) {
  73713. throw "HDR Bad header format, unsupported FORMAT";
  73714. }
  73715. lineIndex += (line.length + 1);
  73716. line = this.readStringLine(uint8array, lineIndex);
  73717. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73718. var match = sizeRegexp.exec(line);
  73719. // TODO. Support +Y and -X if needed.
  73720. if (!match || match.length < 3) {
  73721. throw "HDR Bad header format, no size";
  73722. }
  73723. width = parseInt(match[2]);
  73724. height = parseInt(match[1]);
  73725. if (width < 8 || width > 0x7fff) {
  73726. throw "HDR Bad header format, unsupported size";
  73727. }
  73728. lineIndex += (line.length + 1);
  73729. return {
  73730. height: height,
  73731. width: width,
  73732. dataPosition: lineIndex
  73733. };
  73734. };
  73735. /**
  73736. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73737. * This RGBE texture needs to store the information as a panorama.
  73738. *
  73739. * More information on this format are available here:
  73740. * https://en.wikipedia.org/wiki/RGBE_image_format
  73741. *
  73742. * @param buffer The binary file stored in an array buffer.
  73743. * @param size The expected size of the extracted cubemap.
  73744. * @return The Cube Map information.
  73745. */
  73746. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73747. var uint8array = new Uint8Array(buffer);
  73748. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73749. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73750. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73751. return cubeMapData;
  73752. };
  73753. /**
  73754. * Returns the pixels data extracted from an RGBE texture.
  73755. * This pixels will be stored left to right up to down in the R G B order in one array.
  73756. *
  73757. * More information on this format are available here:
  73758. * https://en.wikipedia.org/wiki/RGBE_image_format
  73759. *
  73760. * @param uint8array The binary file stored in an array buffer.
  73761. * @param hdrInfo The header information of the file.
  73762. * @return The pixels data in RGB right to left up to down order.
  73763. */
  73764. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73765. // Keep for multi format supports.
  73766. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73767. };
  73768. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73769. var num_scanlines = hdrInfo.height;
  73770. var scanline_width = hdrInfo.width;
  73771. var a, b, c, d, count;
  73772. var dataIndex = hdrInfo.dataPosition;
  73773. var index = 0, endIndex = 0, i = 0;
  73774. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73775. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73776. // 3 channels of 4 bytes per pixel in float.
  73777. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73778. var resultArray = new Float32Array(resultBuffer);
  73779. // read in each successive scanline
  73780. while (num_scanlines > 0) {
  73781. a = uint8array[dataIndex++];
  73782. b = uint8array[dataIndex++];
  73783. c = uint8array[dataIndex++];
  73784. d = uint8array[dataIndex++];
  73785. if (a != 2 || b != 2 || (c & 0x80)) {
  73786. // this file is not run length encoded
  73787. throw "HDR Bad header format, not RLE";
  73788. }
  73789. if (((c << 8) | d) != scanline_width) {
  73790. throw "HDR Bad header format, wrong scan line width";
  73791. }
  73792. index = 0;
  73793. // read each of the four channels for the scanline into the buffer
  73794. for (i = 0; i < 4; i++) {
  73795. endIndex = (i + 1) * scanline_width;
  73796. while (index < endIndex) {
  73797. a = uint8array[dataIndex++];
  73798. b = uint8array[dataIndex++];
  73799. if (a > 128) {
  73800. // a run of the same value
  73801. count = a - 128;
  73802. if ((count == 0) || (count > endIndex - index)) {
  73803. throw "HDR Bad Format, bad scanline data (run)";
  73804. }
  73805. while (count-- > 0) {
  73806. scanLineArray[index++] = b;
  73807. }
  73808. }
  73809. else {
  73810. // a non-run
  73811. count = a;
  73812. if ((count == 0) || (count > endIndex - index)) {
  73813. throw "HDR Bad Format, bad scanline data (non-run)";
  73814. }
  73815. scanLineArray[index++] = b;
  73816. if (--count > 0) {
  73817. for (var j = 0; j < count; j++) {
  73818. scanLineArray[index++] = uint8array[dataIndex++];
  73819. }
  73820. }
  73821. }
  73822. }
  73823. }
  73824. // now convert data from buffer into floats
  73825. for (i = 0; i < scanline_width; i++) {
  73826. a = scanLineArray[i];
  73827. b = scanLineArray[i + scanline_width];
  73828. c = scanLineArray[i + 2 * scanline_width];
  73829. d = scanLineArray[i + 3 * scanline_width];
  73830. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73831. }
  73832. num_scanlines--;
  73833. }
  73834. return resultArray;
  73835. };
  73836. return HDRTools;
  73837. }());
  73838. BABYLON.HDRTools = HDRTools;
  73839. })(BABYLON || (BABYLON = {}));
  73840. //# sourceMappingURL=babylon.hdr.js.map
  73841. var BABYLON;
  73842. (function (BABYLON) {
  73843. /**
  73844. * This represents a texture coming from an HDR input.
  73845. *
  73846. * The only supported format is currently panorama picture stored in RGBE format.
  73847. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73848. */
  73849. var HDRCubeTexture = /** @class */ (function (_super) {
  73850. __extends(HDRCubeTexture, _super);
  73851. /**
  73852. * Instantiates an HDRTexture from the following parameters.
  73853. *
  73854. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73855. * @param scene The scene the texture will be used in
  73856. * @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.
  73857. * @param noMipmap Forces to not generate the mipmap if true
  73858. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73859. * @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)
  73860. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73861. */
  73862. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73863. if (noMipmap === void 0) { noMipmap = false; }
  73864. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73865. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73866. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73867. if (onLoad === void 0) { onLoad = null; }
  73868. if (onError === void 0) { onError = null; }
  73869. var _this = _super.call(this, scene) || this;
  73870. _this._useInGammaSpace = false;
  73871. _this._generateHarmonics = true;
  73872. _this._isBABYLONPreprocessed = false;
  73873. _this._onLoad = null;
  73874. _this._onError = null;
  73875. /**
  73876. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73877. */
  73878. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73879. /**
  73880. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73881. * This is usefull at run time to apply the good shader.
  73882. */
  73883. _this.isPMREM = false;
  73884. _this._isBlocking = true;
  73885. /**
  73886. * Gets or sets the center of the bounding box associated with the cube texture
  73887. * It must define where the camera used to render the texture was set
  73888. */
  73889. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73890. if (!url) {
  73891. return _this;
  73892. }
  73893. _this.name = url;
  73894. _this.url = url;
  73895. _this.hasAlpha = false;
  73896. _this.isCube = true;
  73897. _this._textureMatrix = BABYLON.Matrix.Identity();
  73898. _this._onLoad = onLoad;
  73899. _this._onError = onError;
  73900. _this.gammaSpace = false;
  73901. var caps = scene.getEngine().getCaps();
  73902. if (size) {
  73903. _this._isBABYLONPreprocessed = false;
  73904. _this._noMipmap = noMipmap;
  73905. _this._size = size;
  73906. _this._useInGammaSpace = useInGammaSpace;
  73907. _this._usePMREMGenerator = usePMREMGenerator &&
  73908. caps.textureLOD &&
  73909. caps.textureFloat &&
  73910. !_this._useInGammaSpace;
  73911. }
  73912. else {
  73913. _this._isBABYLONPreprocessed = true;
  73914. _this._noMipmap = false;
  73915. _this._useInGammaSpace = false;
  73916. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73917. !_this._useInGammaSpace;
  73918. }
  73919. _this.isPMREM = _this._usePMREMGenerator;
  73920. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73921. if (!_this._texture) {
  73922. if (!scene.useDelayedTextureLoading) {
  73923. _this.loadTexture();
  73924. }
  73925. else {
  73926. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73927. }
  73928. }
  73929. return _this;
  73930. }
  73931. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73932. /**
  73933. * Gets wether or not the texture is blocking during loading.
  73934. */
  73935. get: function () {
  73936. return this._isBlocking;
  73937. },
  73938. /**
  73939. * Sets wether or not the texture is blocking during loading.
  73940. */
  73941. set: function (value) {
  73942. this._isBlocking = value;
  73943. },
  73944. enumerable: true,
  73945. configurable: true
  73946. });
  73947. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73948. get: function () {
  73949. return this._boundingBoxSize;
  73950. },
  73951. /**
  73952. * Gets or sets the size of the bounding box associated with the cube texture
  73953. * When defined, the cubemap will switch to local mode
  73954. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73955. * @example https://www.babylonjs-playground.com/#RNASML
  73956. */
  73957. set: function (value) {
  73958. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73959. return;
  73960. }
  73961. this._boundingBoxSize = value;
  73962. var scene = this.getScene();
  73963. if (scene) {
  73964. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73965. }
  73966. },
  73967. enumerable: true,
  73968. configurable: true
  73969. });
  73970. /**
  73971. * Occurs when the file is a preprocessed .babylon.hdr file.
  73972. */
  73973. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73974. var _this = this;
  73975. var mipLevels = 0;
  73976. var floatArrayView = null;
  73977. var scene = this.getScene();
  73978. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73979. var mips = new Array();
  73980. if (!floatArrayView) {
  73981. return mips;
  73982. }
  73983. var startIndex = 30;
  73984. for (var level = 0; level < mipLevels; level++) {
  73985. mips.push([]);
  73986. // Fill each pixel of the mip level.
  73987. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73988. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73989. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73990. mips[level].push(faceData);
  73991. startIndex += faceSize;
  73992. }
  73993. }
  73994. return mips;
  73995. } : null;
  73996. var callback = function (buffer) {
  73997. var scene = _this.getScene();
  73998. if (!scene) {
  73999. return null;
  74000. }
  74001. // Create Native Array Views
  74002. var intArrayView = new Int32Array(buffer);
  74003. floatArrayView = new Float32Array(buffer);
  74004. // Fill header.
  74005. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74006. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74007. // Update Texture Information.
  74008. if (!_this._texture) {
  74009. return null;
  74010. }
  74011. _this._texture.updateSize(_this._size, _this._size);
  74012. // Fill polynomial information.
  74013. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74014. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74015. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74016. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74017. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74018. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74019. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74020. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74021. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74022. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74023. _this.sphericalPolynomial = sphericalPolynomial;
  74024. // Fill pixel data.
  74025. mipLevels = intArrayView[29]; // Number of mip levels.
  74026. var startIndex = 30;
  74027. var data = [];
  74028. var faceSize = Math.pow(_this._size, 2) * 3;
  74029. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74030. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74031. startIndex += faceSize;
  74032. }
  74033. var results = [];
  74034. var byteArray = null;
  74035. // Push each faces.
  74036. for (var k = 0; k < 6; k++) {
  74037. var dataFace = null;
  74038. // To be deprecated.
  74039. if (version === 1) {
  74040. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74041. dataFace = data[j];
  74042. }
  74043. // If special cases.
  74044. if (!mipmapGenerator && dataFace) {
  74045. if (!scene.getEngine().getCaps().textureFloat) {
  74046. // 3 channels of 1 bytes per pixel in bytes.
  74047. var byteBuffer = new ArrayBuffer(faceSize);
  74048. byteArray = new Uint8Array(byteBuffer);
  74049. }
  74050. for (var i = 0; i < _this._size * _this._size; i++) {
  74051. // Put in gamma space if requested.
  74052. if (_this._useInGammaSpace) {
  74053. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74054. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74055. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74056. }
  74057. // Convert to int texture for fallback.
  74058. if (byteArray) {
  74059. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74060. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74061. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74062. // May use luminance instead if the result is not accurate.
  74063. var max = Math.max(Math.max(r, g), b);
  74064. if (max > 255) {
  74065. var scale = 255 / max;
  74066. r *= scale;
  74067. g *= scale;
  74068. b *= scale;
  74069. }
  74070. byteArray[(i * 3) + 0] = r;
  74071. byteArray[(i * 3) + 1] = g;
  74072. byteArray[(i * 3) + 2] = b;
  74073. }
  74074. }
  74075. }
  74076. // Fill the array accordingly.
  74077. if (byteArray) {
  74078. results.push(byteArray);
  74079. }
  74080. else {
  74081. results.push(dataFace);
  74082. }
  74083. }
  74084. return results;
  74085. };
  74086. if (scene) {
  74087. 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);
  74088. }
  74089. };
  74090. /**
  74091. * Occurs when the file is raw .hdr file.
  74092. */
  74093. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74094. var _this = this;
  74095. var callback = function (buffer) {
  74096. var scene = _this.getScene();
  74097. if (!scene) {
  74098. return null;
  74099. }
  74100. // Extract the raw linear data.
  74101. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74102. // Generate harmonics if needed.
  74103. if (_this._generateHarmonics) {
  74104. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74105. _this.sphericalPolynomial = sphericalPolynomial;
  74106. }
  74107. var results = [];
  74108. var byteArray = null;
  74109. // Push each faces.
  74110. for (var j = 0; j < 6; j++) {
  74111. // Create uintarray fallback.
  74112. if (!scene.getEngine().getCaps().textureFloat) {
  74113. // 3 channels of 1 bytes per pixel in bytes.
  74114. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74115. byteArray = new Uint8Array(byteBuffer);
  74116. }
  74117. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74118. // If special cases.
  74119. if (_this._useInGammaSpace || byteArray) {
  74120. for (var i = 0; i < _this._size * _this._size; i++) {
  74121. // Put in gamma space if requested.
  74122. if (_this._useInGammaSpace) {
  74123. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74124. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74125. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74126. }
  74127. // Convert to int texture for fallback.
  74128. if (byteArray) {
  74129. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74130. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74131. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74132. // May use luminance instead if the result is not accurate.
  74133. var max = Math.max(Math.max(r, g), b);
  74134. if (max > 255) {
  74135. var scale = 255 / max;
  74136. r *= scale;
  74137. g *= scale;
  74138. b *= scale;
  74139. }
  74140. byteArray[(i * 3) + 0] = r;
  74141. byteArray[(i * 3) + 1] = g;
  74142. byteArray[(i * 3) + 2] = b;
  74143. }
  74144. }
  74145. }
  74146. if (byteArray) {
  74147. results.push(byteArray);
  74148. }
  74149. else {
  74150. results.push(dataFace);
  74151. }
  74152. }
  74153. return results;
  74154. };
  74155. var mipmapGenerator = null;
  74156. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74157. // if (!this._noMipmap &&
  74158. // this._usePMREMGenerator) {
  74159. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74160. // // Custom setup of the generator matching with the PBR shader values.
  74161. // var generator = new BABYLON.PMREMGenerator(data,
  74162. // this._size,
  74163. // this._size,
  74164. // 0,
  74165. // 3,
  74166. // this.getScene().getEngine().getCaps().textureFloat,
  74167. // 2048,
  74168. // 0.25,
  74169. // false,
  74170. // true);
  74171. // return generator.filterCubeMap();
  74172. // };
  74173. // }
  74174. var scene = this.getScene();
  74175. if (scene) {
  74176. 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);
  74177. }
  74178. };
  74179. /**
  74180. * Starts the loading process of the texture.
  74181. */
  74182. HDRCubeTexture.prototype.loadTexture = function () {
  74183. if (this._isBABYLONPreprocessed) {
  74184. this.loadBabylonTexture();
  74185. }
  74186. else {
  74187. this.loadHDRTexture();
  74188. }
  74189. };
  74190. HDRCubeTexture.prototype.clone = function () {
  74191. var scene = this.getScene();
  74192. if (!scene) {
  74193. return this;
  74194. }
  74195. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74196. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74197. // Base texture
  74198. newTexture.level = this.level;
  74199. newTexture.wrapU = this.wrapU;
  74200. newTexture.wrapV = this.wrapV;
  74201. newTexture.coordinatesIndex = this.coordinatesIndex;
  74202. newTexture.coordinatesMode = this.coordinatesMode;
  74203. return newTexture;
  74204. };
  74205. // Methods
  74206. HDRCubeTexture.prototype.delayLoad = function () {
  74207. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74208. return;
  74209. }
  74210. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74211. this._texture = this._getFromCache(this.url, this._noMipmap);
  74212. if (!this._texture) {
  74213. this.loadTexture();
  74214. }
  74215. };
  74216. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74217. return this._textureMatrix;
  74218. };
  74219. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74220. this._textureMatrix = value;
  74221. };
  74222. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74223. var texture = null;
  74224. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74225. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74226. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74227. texture.name = parsedTexture.name;
  74228. texture.hasAlpha = parsedTexture.hasAlpha;
  74229. texture.level = parsedTexture.level;
  74230. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74231. texture.isBlocking = parsedTexture.isBlocking;
  74232. }
  74233. if (texture) {
  74234. if (parsedTexture.boundingBoxPosition) {
  74235. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74236. }
  74237. if (parsedTexture.boundingBoxSize) {
  74238. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74239. }
  74240. }
  74241. return texture;
  74242. };
  74243. HDRCubeTexture.prototype.serialize = function () {
  74244. if (!this.name) {
  74245. return null;
  74246. }
  74247. var serializationObject = {};
  74248. serializationObject.name = this.name;
  74249. serializationObject.hasAlpha = this.hasAlpha;
  74250. serializationObject.isCube = true;
  74251. serializationObject.level = this.level;
  74252. serializationObject.size = this._size;
  74253. serializationObject.coordinatesMode = this.coordinatesMode;
  74254. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74255. serializationObject.generateHarmonics = this._generateHarmonics;
  74256. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74257. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74258. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74259. serializationObject.noMipmap = this._noMipmap;
  74260. serializationObject.isBlocking = this._isBlocking;
  74261. return serializationObject;
  74262. };
  74263. /**
  74264. * Saves as a file the data contained in the texture in a binary format.
  74265. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74266. * as the spherical used in the lighting.
  74267. * @param url The HDR file url.
  74268. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74269. * @param onError Method called if any error happens during download.
  74270. * @return The packed binary data.
  74271. */
  74272. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74273. if (onError === void 0) { onError = null; }
  74274. var callback = function (buffer) {
  74275. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74276. // Returns a URL you can use as a href.
  74277. var objUrl = window.URL.createObjectURL(data);
  74278. // Simulates a link to it and click to dowload.
  74279. var a = document.createElement("a");
  74280. document.body.appendChild(a);
  74281. a.style.display = "none";
  74282. a.href = objUrl;
  74283. a.download = "envmap.babylon.hdr";
  74284. a.click();
  74285. };
  74286. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74287. };
  74288. /**
  74289. * Serializes the data contained in the texture in a binary format.
  74290. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74291. * as the spherical used in the lighting.
  74292. * @param url The HDR file url.
  74293. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74294. * @param onError Method called if any error happens during download.
  74295. * @return The packed binary data.
  74296. */
  74297. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74298. if (onError === void 0) { onError = null; }
  74299. // Needs the url tho create the texture.
  74300. if (!url) {
  74301. return;
  74302. }
  74303. // Check Power of two size.
  74304. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74305. return;
  74306. }
  74307. // Coming Back in 3.x.
  74308. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74309. };
  74310. HDRCubeTexture._facesMapping = [
  74311. "right",
  74312. "left",
  74313. "up",
  74314. "down",
  74315. "front",
  74316. "back"
  74317. ];
  74318. return HDRCubeTexture;
  74319. }(BABYLON.BaseTexture));
  74320. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74321. })(BABYLON || (BABYLON = {}));
  74322. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74323. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74324. // Huge respect for a such great lib.
  74325. // Earcut license:
  74326. // Copyright (c) 2016, Mapbox
  74327. //
  74328. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74329. // with or without fee is hereby granted, provided that the above copyright notice
  74330. // and this permission notice appear in all copies.
  74331. //
  74332. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74333. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74334. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74335. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74336. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74337. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74338. // THIS SOFTWARE.
  74339. var Earcut;
  74340. (function (Earcut) {
  74341. /**
  74342. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74343. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74344. * @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).
  74345. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74346. */
  74347. function earcut(data, holeIndices, dim) {
  74348. dim = dim || 2;
  74349. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74350. if (!outerNode)
  74351. return triangles;
  74352. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74353. if (hasHoles)
  74354. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74355. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74356. if (data.length > 80 * dim) {
  74357. minX = maxX = data[0];
  74358. minY = maxY = data[1];
  74359. for (var i = dim; i < outerLen; i += dim) {
  74360. x = data[i];
  74361. y = data[i + 1];
  74362. if (x < minX)
  74363. minX = x;
  74364. if (y < minY)
  74365. minY = y;
  74366. if (x > maxX)
  74367. maxX = x;
  74368. if (y > maxY)
  74369. maxY = y;
  74370. }
  74371. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74372. size = Math.max(maxX - minX, maxY - minY);
  74373. }
  74374. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74375. return triangles;
  74376. }
  74377. Earcut.earcut = earcut;
  74378. var Node = /** @class */ (function () {
  74379. function Node(i, x, y) {
  74380. this.i = i;
  74381. this.x = x;
  74382. this.y = y;
  74383. this.prev = null;
  74384. this.next = null;
  74385. this.z = null;
  74386. this.prevZ = null;
  74387. this.nextZ = null;
  74388. this.steiner = false;
  74389. }
  74390. return Node;
  74391. }());
  74392. // create a circular doubly linked list from polygon points in the specified winding order
  74393. function linkedList(data, start, end, dim, clockwise) {
  74394. var i, last = null;
  74395. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74396. for (i = start; i < end; i += dim)
  74397. last = insertNode(i, data[i], data[i + 1], last);
  74398. }
  74399. else {
  74400. for (i = end - dim; i >= start; i -= dim)
  74401. last = insertNode(i, data[i], data[i + 1], last);
  74402. }
  74403. if (last && equals(last, last.next)) {
  74404. removeNode(last);
  74405. last = last.next;
  74406. }
  74407. return last;
  74408. }
  74409. // eliminate colinear or duplicate points
  74410. function filterPoints(start, end) {
  74411. if (!start)
  74412. return start;
  74413. if (!end)
  74414. end = start;
  74415. var p = start, again;
  74416. do {
  74417. again = false;
  74418. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74419. removeNode(p);
  74420. p = end = p.prev;
  74421. if (p === p.next)
  74422. return undefined;
  74423. again = true;
  74424. }
  74425. else {
  74426. p = p.next;
  74427. }
  74428. } while (again || p !== end);
  74429. return end;
  74430. }
  74431. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74432. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74433. if (!ear)
  74434. return;
  74435. // interlink polygon nodes in z-order
  74436. if (!pass && size)
  74437. indexCurve(ear, minX, minY, size);
  74438. var stop = ear, prev, next;
  74439. // iterate through ears, slicing them one by one
  74440. while (ear.prev !== ear.next) {
  74441. prev = ear.prev;
  74442. next = ear.next;
  74443. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74444. // cut off the triangle
  74445. triangles.push(prev.i / dim);
  74446. triangles.push(ear.i / dim);
  74447. triangles.push(next.i / dim);
  74448. removeNode(ear);
  74449. // skipping the next vertice leads to less sliver triangles
  74450. ear = next.next;
  74451. stop = next.next;
  74452. continue;
  74453. }
  74454. ear = next;
  74455. // if we looped through the whole remaining polygon and can't find any more ears
  74456. if (ear === stop) {
  74457. // try filtering points and slicing again
  74458. if (!pass) {
  74459. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74460. // if this didn't work, try curing all small self-intersections locally
  74461. }
  74462. else if (pass === 1) {
  74463. ear = cureLocalIntersections(ear, triangles, dim);
  74464. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74465. // as a last resort, try splitting the remaining polygon into two
  74466. }
  74467. else if (pass === 2) {
  74468. splitEarcut(ear, triangles, dim, minX, minY, size);
  74469. }
  74470. break;
  74471. }
  74472. }
  74473. }
  74474. // check whether a polygon node forms a valid ear with adjacent nodes
  74475. function isEar(ear) {
  74476. var a = ear.prev, b = ear, c = ear.next;
  74477. if (area(a, b, c) >= 0)
  74478. return false; // reflex, can't be an ear
  74479. // now make sure we don't have other points inside the potential ear
  74480. var p = ear.next.next;
  74481. while (p !== ear.prev) {
  74482. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74483. area(p.prev, p, p.next) >= 0)
  74484. return false;
  74485. p = p.next;
  74486. }
  74487. return true;
  74488. }
  74489. function isEarHashed(ear, minX, minY, size) {
  74490. var a = ear.prev, b = ear, c = ear.next;
  74491. if (area(a, b, c) >= 0)
  74492. return false; // reflex, can't be an ear
  74493. // triangle bbox; min & max are calculated like this for speed
  74494. 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);
  74495. // z-order range for the current triangle bbox;
  74496. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74497. // first look for points inside the triangle in increasing z-order
  74498. var p = ear.nextZ;
  74499. while (p && p.z <= maxZ) {
  74500. if (p !== ear.prev &&
  74501. p !== ear.next &&
  74502. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74503. area(p.prev, p, p.next) >= 0)
  74504. return false;
  74505. p = p.nextZ;
  74506. }
  74507. // then look for points in decreasing z-order
  74508. p = ear.prevZ;
  74509. while (p && p.z >= minZ) {
  74510. if (p !== ear.prev &&
  74511. p !== ear.next &&
  74512. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74513. area(p.prev, p, p.next) >= 0)
  74514. return false;
  74515. p = p.prevZ;
  74516. }
  74517. return true;
  74518. }
  74519. // go through all polygon nodes and cure small local self-intersections
  74520. function cureLocalIntersections(start, triangles, dim) {
  74521. var p = start;
  74522. do {
  74523. var a = p.prev, b = p.next.next;
  74524. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74525. triangles.push(a.i / dim);
  74526. triangles.push(p.i / dim);
  74527. triangles.push(b.i / dim);
  74528. // remove two nodes involved
  74529. removeNode(p);
  74530. removeNode(p.next);
  74531. p = start = b;
  74532. }
  74533. p = p.next;
  74534. } while (p !== start);
  74535. return p;
  74536. }
  74537. // try splitting polygon into two and triangulate them independently
  74538. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74539. // look for a valid diagonal that divides the polygon into two
  74540. var a = start;
  74541. do {
  74542. var b = a.next.next;
  74543. while (b !== a.prev) {
  74544. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74545. // split the polygon in two by the diagonal
  74546. var c = splitPolygon(a, b);
  74547. // filter colinear points around the cuts
  74548. a = filterPoints(a, a.next);
  74549. c = filterPoints(c, c.next);
  74550. // run earcut on each half
  74551. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74552. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74553. return;
  74554. }
  74555. b = b.next;
  74556. }
  74557. a = a.next;
  74558. } while (a !== start);
  74559. }
  74560. // link every hole into the outer loop, producing a single-ring polygon without holes
  74561. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74562. var queue = [], i, len, start, end, list;
  74563. for (i = 0, len = holeIndices.length; i < len; i++) {
  74564. start = holeIndices[i] * dim;
  74565. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74566. list = linkedList(data, start, end, dim, false);
  74567. if (list === list.next)
  74568. list.steiner = true;
  74569. queue.push(getLeftmost(list));
  74570. }
  74571. queue.sort(compareX);
  74572. // process holes from left to right
  74573. for (i = 0; i < queue.length; i++) {
  74574. eliminateHole(queue[i], outerNode);
  74575. outerNode = filterPoints(outerNode, outerNode.next);
  74576. }
  74577. return outerNode;
  74578. }
  74579. function compareX(a, b) {
  74580. return a.x - b.x;
  74581. }
  74582. // find a bridge between vertices that connects hole with an outer ring and and link it
  74583. function eliminateHole(hole, outerNode) {
  74584. outerNode = findHoleBridge(hole, outerNode);
  74585. if (outerNode) {
  74586. var b = splitPolygon(outerNode, hole);
  74587. filterPoints(b, b.next);
  74588. }
  74589. }
  74590. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74591. function findHoleBridge(hole, outerNode) {
  74592. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74593. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74594. // segment's endpoint with lesser x will be potential connection point
  74595. do {
  74596. if (hy <= p.y && hy >= p.next.y) {
  74597. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74598. if (x <= hx && x > qx) {
  74599. qx = x;
  74600. if (x === hx) {
  74601. if (hy === p.y)
  74602. return p;
  74603. if (hy === p.next.y)
  74604. return p.next;
  74605. }
  74606. m = p.x < p.next.x ? p : p.next;
  74607. }
  74608. }
  74609. p = p.next;
  74610. } while (p !== outerNode);
  74611. if (!m)
  74612. return null;
  74613. if (hx === qx)
  74614. return m.prev; // hole touches outer segment; pick lower endpoint
  74615. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74616. // if there are no points found, we have a valid connection;
  74617. // otherwise choose the point of the minimum angle with the ray as connection point
  74618. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74619. p = m.next;
  74620. while (p !== stop) {
  74621. if (hx >= p.x &&
  74622. p.x >= mx &&
  74623. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74624. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74625. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74626. m = p;
  74627. tanMin = tan;
  74628. }
  74629. }
  74630. p = p.next;
  74631. }
  74632. return m;
  74633. }
  74634. // interlink polygon nodes in z-order
  74635. function indexCurve(start, minX, minY, size) {
  74636. var p = start;
  74637. do {
  74638. if (p.z === null)
  74639. p.z = zOrder(p.x, p.y, minX, minY, size);
  74640. p.prevZ = p.prev;
  74641. p.nextZ = p.next;
  74642. p = p.next;
  74643. } while (p !== start);
  74644. p.prevZ.nextZ = null;
  74645. p.prevZ = null;
  74646. sortLinked(p);
  74647. }
  74648. // Simon Tatham's linked list merge sort algorithm
  74649. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74650. function sortLinked(list) {
  74651. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74652. do {
  74653. p = list;
  74654. list = null;
  74655. tail = null;
  74656. numMerges = 0;
  74657. while (p) {
  74658. numMerges++;
  74659. q = p;
  74660. pSize = 0;
  74661. for (i = 0; i < inSize; i++) {
  74662. pSize++;
  74663. q = q.nextZ;
  74664. if (!q)
  74665. break;
  74666. }
  74667. qSize = inSize;
  74668. while (pSize > 0 || (qSize > 0 && q)) {
  74669. if (pSize === 0) {
  74670. e = q;
  74671. q = q.nextZ;
  74672. qSize--;
  74673. }
  74674. else if (qSize === 0 || !q) {
  74675. e = p;
  74676. p = p.nextZ;
  74677. pSize--;
  74678. }
  74679. else if (p.z <= q.z) {
  74680. e = p;
  74681. p = p.nextZ;
  74682. pSize--;
  74683. }
  74684. else {
  74685. e = q;
  74686. q = q.nextZ;
  74687. qSize--;
  74688. }
  74689. if (tail)
  74690. tail.nextZ = e;
  74691. else
  74692. list = e;
  74693. e.prevZ = tail;
  74694. tail = e;
  74695. }
  74696. p = q;
  74697. }
  74698. tail.nextZ = null;
  74699. inSize *= 2;
  74700. } while (numMerges > 1);
  74701. return list;
  74702. }
  74703. // z-order of a point given coords and size of the data bounding box
  74704. function zOrder(x, y, minX, minY, size) {
  74705. // coords are transformed into non-negative 15-bit integer range
  74706. x = 32767 * (x - minX) / size;
  74707. y = 32767 * (y - minY) / size;
  74708. x = (x | (x << 8)) & 0x00FF00FF;
  74709. x = (x | (x << 4)) & 0x0F0F0F0F;
  74710. x = (x | (x << 2)) & 0x33333333;
  74711. x = (x | (x << 1)) & 0x55555555;
  74712. y = (y | (y << 8)) & 0x00FF00FF;
  74713. y = (y | (y << 4)) & 0x0F0F0F0F;
  74714. y = (y | (y << 2)) & 0x33333333;
  74715. y = (y | (y << 1)) & 0x55555555;
  74716. return x | (y << 1);
  74717. }
  74718. // find the leftmost node of a polygon ring
  74719. function getLeftmost(start) {
  74720. var p = start, leftmost = start;
  74721. do {
  74722. if (p.x < leftmost.x)
  74723. leftmost = p;
  74724. p = p.next;
  74725. } while (p !== start);
  74726. return leftmost;
  74727. }
  74728. // check if a point lies within a convex triangle
  74729. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74730. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74731. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74732. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74733. }
  74734. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74735. function isValidDiagonal(a, b) {
  74736. return a.next.i !== b.i &&
  74737. a.prev.i !== b.i &&
  74738. !intersectsPolygon(a, b) &&
  74739. locallyInside(a, b) &&
  74740. locallyInside(b, a) &&
  74741. middleInside(a, b);
  74742. }
  74743. // signed area of a triangle
  74744. function area(p, q, r) {
  74745. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74746. }
  74747. // check if two points are equal
  74748. function equals(p1, p2) {
  74749. return p1.x === p2.x && p1.y === p2.y;
  74750. }
  74751. // check if two segments intersect
  74752. function intersects(p1, q1, p2, q2) {
  74753. if ((equals(p1, q1) && equals(p2, q2)) ||
  74754. (equals(p1, q2) && equals(p2, q1)))
  74755. return true;
  74756. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74757. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74758. }
  74759. // check if a polygon diagonal intersects any polygon segments
  74760. function intersectsPolygon(a, b) {
  74761. var p = a;
  74762. do {
  74763. if (p.i !== a.i &&
  74764. p.next.i !== a.i &&
  74765. p.i !== b.i &&
  74766. p.next.i !== b.i &&
  74767. intersects(p, p.next, a, b))
  74768. return true;
  74769. p = p.next;
  74770. } while (p !== a);
  74771. return false;
  74772. }
  74773. // check if a polygon diagonal is locally inside the polygon
  74774. function locallyInside(a, b) {
  74775. return area(a.prev, a, a.next) < 0
  74776. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74777. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74778. }
  74779. // check if the middle point of a polygon diagonal is inside the polygon
  74780. function middleInside(a, b) {
  74781. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74782. do {
  74783. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74784. inside = !inside;
  74785. p = p.next;
  74786. } while (p !== a);
  74787. return inside;
  74788. }
  74789. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74790. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74791. function splitPolygon(a, b) {
  74792. 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;
  74793. a.next = b;
  74794. b.prev = a;
  74795. a2.next = an;
  74796. an.prev = a2;
  74797. b2.next = a2;
  74798. a2.prev = b2;
  74799. bp.next = b2;
  74800. b2.prev = bp;
  74801. return b2;
  74802. }
  74803. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74804. function insertNode(i, x, y, last) {
  74805. var p = new Node(i, x, y);
  74806. if (!last) {
  74807. p.prev = p;
  74808. p.next = p;
  74809. }
  74810. else {
  74811. p.next = last.next;
  74812. p.prev = last;
  74813. last.next.prev = p;
  74814. last.next = p;
  74815. }
  74816. return p;
  74817. }
  74818. function removeNode(p) {
  74819. p.next.prev = p.prev;
  74820. p.prev.next = p.next;
  74821. if (p.prevZ)
  74822. p.prevZ.nextZ = p.nextZ;
  74823. if (p.nextZ)
  74824. p.nextZ.prevZ = p.prevZ;
  74825. }
  74826. /**
  74827. * return a percentage difference between the polygon area and its triangulation area;
  74828. * used to verify correctness of triangulation
  74829. */
  74830. function deviation(data, holeIndices, dim, triangles) {
  74831. var hasHoles = holeIndices && holeIndices.length;
  74832. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74833. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74834. if (hasHoles) {
  74835. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74836. var start = holeIndices[i] * dim;
  74837. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74838. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74839. }
  74840. }
  74841. var trianglesArea = 0;
  74842. for (i = 0; i < triangles.length; i += 3) {
  74843. var a = triangles[i] * dim;
  74844. var b = triangles[i + 1] * dim;
  74845. var c = triangles[i + 2] * dim;
  74846. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74847. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74848. }
  74849. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74850. }
  74851. Earcut.deviation = deviation;
  74852. ;
  74853. function signedArea(data, start, end, dim) {
  74854. var sum = 0;
  74855. for (var i = start, j = end - dim; i < end; i += dim) {
  74856. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74857. j = i;
  74858. }
  74859. return sum;
  74860. }
  74861. /**
  74862. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74863. */
  74864. function flatten(data) {
  74865. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74866. for (var i = 0; i < data.length; i++) {
  74867. for (var j = 0; j < data[i].length; j++) {
  74868. for (var d = 0; d < dim; d++)
  74869. result.vertices.push(data[i][j][d]);
  74870. }
  74871. if (i > 0) {
  74872. holeIndex += data[i - 1].length;
  74873. result.holes.push(holeIndex);
  74874. }
  74875. }
  74876. return result;
  74877. }
  74878. Earcut.flatten = flatten;
  74879. ;
  74880. })(Earcut || (Earcut = {}));
  74881. //# sourceMappingURL=babylon.earcut.js.map
  74882. var BABYLON;
  74883. (function (BABYLON) {
  74884. var IndexedVector2 = /** @class */ (function (_super) {
  74885. __extends(IndexedVector2, _super);
  74886. function IndexedVector2(original, index) {
  74887. var _this = _super.call(this, original.x, original.y) || this;
  74888. _this.index = index;
  74889. return _this;
  74890. }
  74891. return IndexedVector2;
  74892. }(BABYLON.Vector2));
  74893. var PolygonPoints = /** @class */ (function () {
  74894. function PolygonPoints() {
  74895. this.elements = new Array();
  74896. }
  74897. PolygonPoints.prototype.add = function (originalPoints) {
  74898. var _this = this;
  74899. var result = new Array();
  74900. originalPoints.forEach(function (point) {
  74901. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74902. var newPoint = new IndexedVector2(point, _this.elements.length);
  74903. result.push(newPoint);
  74904. _this.elements.push(newPoint);
  74905. }
  74906. });
  74907. return result;
  74908. };
  74909. PolygonPoints.prototype.computeBounds = function () {
  74910. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74911. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74912. this.elements.forEach(function (point) {
  74913. // x
  74914. if (point.x < lmin.x) {
  74915. lmin.x = point.x;
  74916. }
  74917. else if (point.x > lmax.x) {
  74918. lmax.x = point.x;
  74919. }
  74920. // y
  74921. if (point.y < lmin.y) {
  74922. lmin.y = point.y;
  74923. }
  74924. else if (point.y > lmax.y) {
  74925. lmax.y = point.y;
  74926. }
  74927. });
  74928. return {
  74929. min: lmin,
  74930. max: lmax,
  74931. width: lmax.x - lmin.x,
  74932. height: lmax.y - lmin.y
  74933. };
  74934. };
  74935. return PolygonPoints;
  74936. }());
  74937. var Polygon = /** @class */ (function () {
  74938. function Polygon() {
  74939. }
  74940. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74941. return [
  74942. new BABYLON.Vector2(xmin, ymin),
  74943. new BABYLON.Vector2(xmax, ymin),
  74944. new BABYLON.Vector2(xmax, ymax),
  74945. new BABYLON.Vector2(xmin, ymax)
  74946. ];
  74947. };
  74948. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74949. if (cx === void 0) { cx = 0; }
  74950. if (cy === void 0) { cy = 0; }
  74951. if (numberOfSides === void 0) { numberOfSides = 32; }
  74952. var result = new Array();
  74953. var angle = 0;
  74954. var increment = (Math.PI * 2) / numberOfSides;
  74955. for (var i = 0; i < numberOfSides; i++) {
  74956. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74957. angle -= increment;
  74958. }
  74959. return result;
  74960. };
  74961. Polygon.Parse = function (input) {
  74962. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74963. var i, result = [];
  74964. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74965. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74966. }
  74967. return result;
  74968. };
  74969. Polygon.StartingAt = function (x, y) {
  74970. return BABYLON.Path2.StartingAt(x, y);
  74971. };
  74972. return Polygon;
  74973. }());
  74974. BABYLON.Polygon = Polygon;
  74975. var PolygonMeshBuilder = /** @class */ (function () {
  74976. function PolygonMeshBuilder(name, contours, scene) {
  74977. this._points = new PolygonPoints();
  74978. this._outlinepoints = new PolygonPoints();
  74979. this._holes = new Array();
  74980. this._epoints = new Array();
  74981. this._eholes = new Array();
  74982. this._name = name;
  74983. this._scene = scene;
  74984. var points;
  74985. if (contours instanceof BABYLON.Path2) {
  74986. points = contours.getPoints();
  74987. }
  74988. else {
  74989. points = contours;
  74990. }
  74991. this._addToepoint(points);
  74992. this._points.add(points);
  74993. this._outlinepoints.add(points);
  74994. }
  74995. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74996. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74997. var p = points_1[_i];
  74998. this._epoints.push(p.x, p.y);
  74999. }
  75000. };
  75001. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75002. this._points.add(hole);
  75003. var holepoints = new PolygonPoints();
  75004. holepoints.add(hole);
  75005. this._holes.push(holepoints);
  75006. this._eholes.push(this._epoints.length / 2);
  75007. this._addToepoint(hole);
  75008. return this;
  75009. };
  75010. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75011. var _this = this;
  75012. if (updatable === void 0) { updatable = false; }
  75013. if (depth === void 0) { depth = 0; }
  75014. var result = new BABYLON.Mesh(this._name, this._scene);
  75015. var normals = new Array();
  75016. var positions = new Array();
  75017. var uvs = new Array();
  75018. var bounds = this._points.computeBounds();
  75019. this._points.elements.forEach(function (p) {
  75020. normals.push(0, 1.0, 0);
  75021. positions.push(p.x, 0, p.y);
  75022. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75023. });
  75024. var indices = new Array();
  75025. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75026. for (var i = 0; i < res.length; i++) {
  75027. indices.push(res[i]);
  75028. }
  75029. if (depth > 0) {
  75030. var positionscount = (positions.length / 3); //get the current pointcount
  75031. this._points.elements.forEach(function (p) {
  75032. normals.push(0, -1.0, 0);
  75033. positions.push(p.x, -depth, p.y);
  75034. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75035. });
  75036. var totalCount = indices.length;
  75037. for (var i = 0; i < totalCount; i += 3) {
  75038. var i0 = indices[i + 0];
  75039. var i1 = indices[i + 1];
  75040. var i2 = indices[i + 2];
  75041. indices.push(i2 + positionscount);
  75042. indices.push(i1 + positionscount);
  75043. indices.push(i0 + positionscount);
  75044. }
  75045. //Add the sides
  75046. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75047. this._holes.forEach(function (hole) {
  75048. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75049. });
  75050. }
  75051. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75052. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75053. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75054. result.setIndices(indices);
  75055. return result;
  75056. };
  75057. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75058. var StartIndex = positions.length / 3;
  75059. var ulength = 0;
  75060. for (var i = 0; i < points.elements.length; i++) {
  75061. var p = points.elements[i];
  75062. var p1;
  75063. if ((i + 1) > points.elements.length - 1) {
  75064. p1 = points.elements[0];
  75065. }
  75066. else {
  75067. p1 = points.elements[i + 1];
  75068. }
  75069. positions.push(p.x, 0, p.y);
  75070. positions.push(p.x, -depth, p.y);
  75071. positions.push(p1.x, 0, p1.y);
  75072. positions.push(p1.x, -depth, p1.y);
  75073. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75074. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75075. var v3 = v2.subtract(v1);
  75076. var v4 = new BABYLON.Vector3(0, 1, 0);
  75077. var vn = BABYLON.Vector3.Cross(v3, v4);
  75078. vn = vn.normalize();
  75079. uvs.push(ulength / bounds.width, 0);
  75080. uvs.push(ulength / bounds.width, 1);
  75081. ulength += v3.length();
  75082. uvs.push((ulength / bounds.width), 0);
  75083. uvs.push((ulength / bounds.width), 1);
  75084. if (!flip) {
  75085. normals.push(-vn.x, -vn.y, -vn.z);
  75086. normals.push(-vn.x, -vn.y, -vn.z);
  75087. normals.push(-vn.x, -vn.y, -vn.z);
  75088. normals.push(-vn.x, -vn.y, -vn.z);
  75089. indices.push(StartIndex);
  75090. indices.push(StartIndex + 1);
  75091. indices.push(StartIndex + 2);
  75092. indices.push(StartIndex + 1);
  75093. indices.push(StartIndex + 3);
  75094. indices.push(StartIndex + 2);
  75095. }
  75096. else {
  75097. normals.push(vn.x, vn.y, vn.z);
  75098. normals.push(vn.x, vn.y, vn.z);
  75099. normals.push(vn.x, vn.y, vn.z);
  75100. normals.push(vn.x, vn.y, vn.z);
  75101. indices.push(StartIndex);
  75102. indices.push(StartIndex + 2);
  75103. indices.push(StartIndex + 1);
  75104. indices.push(StartIndex + 1);
  75105. indices.push(StartIndex + 2);
  75106. indices.push(StartIndex + 3);
  75107. }
  75108. StartIndex += 4;
  75109. }
  75110. ;
  75111. };
  75112. return PolygonMeshBuilder;
  75113. }());
  75114. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75115. })(BABYLON || (BABYLON = {}));
  75116. //# sourceMappingURL=babylon.polygonMesh.js.map
  75117. var BABYLON;
  75118. (function (BABYLON) {
  75119. // Unique ID when we import meshes from Babylon to CSG
  75120. var currentCSGMeshId = 0;
  75121. // # class Vertex
  75122. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75123. // one to provide additional features like texture coordinates and vertex
  75124. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75125. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75126. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75127. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75128. // is not used anywhere else.
  75129. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75130. var Vertex = /** @class */ (function () {
  75131. function Vertex(pos, normal, uv) {
  75132. this.pos = pos;
  75133. this.normal = normal;
  75134. this.uv = uv;
  75135. }
  75136. Vertex.prototype.clone = function () {
  75137. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75138. };
  75139. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75140. // orientation of a polygon is flipped.
  75141. Vertex.prototype.flip = function () {
  75142. this.normal = this.normal.scale(-1);
  75143. };
  75144. // Create a new vertex between this vertex and `other` by linearly
  75145. // interpolating all properties using a parameter of `t`. Subclasses should
  75146. // override this to interpolate additional properties.
  75147. Vertex.prototype.interpolate = function (other, t) {
  75148. 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));
  75149. };
  75150. return Vertex;
  75151. }());
  75152. // # class Plane
  75153. // Represents a plane in 3D space.
  75154. var Plane = /** @class */ (function () {
  75155. function Plane(normal, w) {
  75156. this.normal = normal;
  75157. this.w = w;
  75158. }
  75159. Plane.FromPoints = function (a, b, c) {
  75160. var v0 = c.subtract(a);
  75161. var v1 = b.subtract(a);
  75162. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75163. return null;
  75164. }
  75165. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75166. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75167. };
  75168. Plane.prototype.clone = function () {
  75169. return new Plane(this.normal.clone(), this.w);
  75170. };
  75171. Plane.prototype.flip = function () {
  75172. this.normal.scaleInPlace(-1);
  75173. this.w = -this.w;
  75174. };
  75175. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75176. // fragments in the appropriate lists. Coplanar polygons go into either
  75177. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75178. // respect to this plane. Polygons in front or in back of this plane go into
  75179. // either `front` or `back`.
  75180. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75181. var COPLANAR = 0;
  75182. var FRONT = 1;
  75183. var BACK = 2;
  75184. var SPANNING = 3;
  75185. // Classify each point as well as the entire polygon into one of the above
  75186. // four classes.
  75187. var polygonType = 0;
  75188. var types = [];
  75189. var i;
  75190. var t;
  75191. for (i = 0; i < polygon.vertices.length; i++) {
  75192. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75193. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75194. polygonType |= type;
  75195. types.push(type);
  75196. }
  75197. // Put the polygon in the correct list, splitting it when necessary.
  75198. switch (polygonType) {
  75199. case COPLANAR:
  75200. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75201. break;
  75202. case FRONT:
  75203. front.push(polygon);
  75204. break;
  75205. case BACK:
  75206. back.push(polygon);
  75207. break;
  75208. case SPANNING:
  75209. var f = [], b = [];
  75210. for (i = 0; i < polygon.vertices.length; i++) {
  75211. var j = (i + 1) % polygon.vertices.length;
  75212. var ti = types[i], tj = types[j];
  75213. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75214. if (ti !== BACK)
  75215. f.push(vi);
  75216. if (ti !== FRONT)
  75217. b.push(ti !== BACK ? vi.clone() : vi);
  75218. if ((ti | tj) === SPANNING) {
  75219. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75220. var v = vi.interpolate(vj, t);
  75221. f.push(v);
  75222. b.push(v.clone());
  75223. }
  75224. }
  75225. var poly;
  75226. if (f.length >= 3) {
  75227. poly = new Polygon(f, polygon.shared);
  75228. if (poly.plane)
  75229. front.push(poly);
  75230. }
  75231. if (b.length >= 3) {
  75232. poly = new Polygon(b, polygon.shared);
  75233. if (poly.plane)
  75234. back.push(poly);
  75235. }
  75236. break;
  75237. }
  75238. };
  75239. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75240. // point is on the plane.
  75241. Plane.EPSILON = 1e-5;
  75242. return Plane;
  75243. }());
  75244. // # class Polygon
  75245. // Represents a convex polygon. The vertices used to initialize a polygon must
  75246. // be coplanar and form a convex loop.
  75247. //
  75248. // Each convex polygon has a `shared` property, which is shared between all
  75249. // polygons that are clones of each other or were split from the same polygon.
  75250. // This can be used to define per-polygon properties (such as surface color).
  75251. var Polygon = /** @class */ (function () {
  75252. function Polygon(vertices, shared) {
  75253. this.vertices = vertices;
  75254. this.shared = shared;
  75255. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75256. }
  75257. Polygon.prototype.clone = function () {
  75258. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75259. return new Polygon(vertices, this.shared);
  75260. };
  75261. Polygon.prototype.flip = function () {
  75262. this.vertices.reverse().map(function (v) { v.flip(); });
  75263. this.plane.flip();
  75264. };
  75265. return Polygon;
  75266. }());
  75267. // # class Node
  75268. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75269. // by picking a polygon to split along. That polygon (and all other coplanar
  75270. // polygons) are added directly to that node and the other polygons are added to
  75271. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75272. // no distinction between internal and leaf nodes.
  75273. var Node = /** @class */ (function () {
  75274. function Node(polygons) {
  75275. this.plane = null;
  75276. this.front = null;
  75277. this.back = null;
  75278. this.polygons = new Array();
  75279. if (polygons) {
  75280. this.build(polygons);
  75281. }
  75282. }
  75283. Node.prototype.clone = function () {
  75284. var node = new Node();
  75285. node.plane = this.plane && this.plane.clone();
  75286. node.front = this.front && this.front.clone();
  75287. node.back = this.back && this.back.clone();
  75288. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75289. return node;
  75290. };
  75291. // Convert solid space to empty space and empty space to solid space.
  75292. Node.prototype.invert = function () {
  75293. for (var i = 0; i < this.polygons.length; i++) {
  75294. this.polygons[i].flip();
  75295. }
  75296. if (this.plane) {
  75297. this.plane.flip();
  75298. }
  75299. if (this.front) {
  75300. this.front.invert();
  75301. }
  75302. if (this.back) {
  75303. this.back.invert();
  75304. }
  75305. var temp = this.front;
  75306. this.front = this.back;
  75307. this.back = temp;
  75308. };
  75309. // Recursively remove all polygons in `polygons` that are inside this BSP
  75310. // tree.
  75311. Node.prototype.clipPolygons = function (polygons) {
  75312. if (!this.plane)
  75313. return polygons.slice();
  75314. var front = new Array(), back = new Array();
  75315. for (var i = 0; i < polygons.length; i++) {
  75316. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75317. }
  75318. if (this.front) {
  75319. front = this.front.clipPolygons(front);
  75320. }
  75321. if (this.back) {
  75322. back = this.back.clipPolygons(back);
  75323. }
  75324. else {
  75325. back = [];
  75326. }
  75327. return front.concat(back);
  75328. };
  75329. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75330. // `bsp`.
  75331. Node.prototype.clipTo = function (bsp) {
  75332. this.polygons = bsp.clipPolygons(this.polygons);
  75333. if (this.front)
  75334. this.front.clipTo(bsp);
  75335. if (this.back)
  75336. this.back.clipTo(bsp);
  75337. };
  75338. // Return a list of all polygons in this BSP tree.
  75339. Node.prototype.allPolygons = function () {
  75340. var polygons = this.polygons.slice();
  75341. if (this.front)
  75342. polygons = polygons.concat(this.front.allPolygons());
  75343. if (this.back)
  75344. polygons = polygons.concat(this.back.allPolygons());
  75345. return polygons;
  75346. };
  75347. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75348. // new polygons are filtered down to the bottom of the tree and become new
  75349. // nodes there. Each set of polygons is partitioned using the first polygon
  75350. // (no heuristic is used to pick a good split).
  75351. Node.prototype.build = function (polygons) {
  75352. if (!polygons.length)
  75353. return;
  75354. if (!this.plane)
  75355. this.plane = polygons[0].plane.clone();
  75356. var front = new Array(), back = new Array();
  75357. for (var i = 0; i < polygons.length; i++) {
  75358. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75359. }
  75360. if (front.length) {
  75361. if (!this.front)
  75362. this.front = new Node();
  75363. this.front.build(front);
  75364. }
  75365. if (back.length) {
  75366. if (!this.back)
  75367. this.back = new Node();
  75368. this.back.build(back);
  75369. }
  75370. };
  75371. return Node;
  75372. }());
  75373. var CSG = /** @class */ (function () {
  75374. function CSG() {
  75375. this.polygons = new Array();
  75376. }
  75377. // Convert BABYLON.Mesh to BABYLON.CSG
  75378. CSG.FromMesh = function (mesh) {
  75379. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75380. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75381. if (mesh instanceof BABYLON.Mesh) {
  75382. mesh.computeWorldMatrix(true);
  75383. matrix = mesh.getWorldMatrix();
  75384. meshPosition = mesh.position.clone();
  75385. meshRotation = mesh.rotation.clone();
  75386. if (mesh.rotationQuaternion) {
  75387. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75388. }
  75389. meshScaling = mesh.scaling.clone();
  75390. }
  75391. else {
  75392. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75393. }
  75394. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75395. var subMeshes = mesh.subMeshes;
  75396. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75397. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75398. vertices = [];
  75399. for (var j = 0; j < 3; j++) {
  75400. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75401. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75402. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75403. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75404. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75405. vertex = new Vertex(position, normal, uv);
  75406. vertices.push(vertex);
  75407. }
  75408. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75409. // To handle the case of degenerated triangle
  75410. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75411. if (polygon.plane)
  75412. polygons.push(polygon);
  75413. }
  75414. }
  75415. var csg = CSG.FromPolygons(polygons);
  75416. csg.matrix = matrix;
  75417. csg.position = meshPosition;
  75418. csg.rotation = meshRotation;
  75419. csg.scaling = meshScaling;
  75420. csg.rotationQuaternion = meshRotationQuaternion;
  75421. currentCSGMeshId++;
  75422. return csg;
  75423. };
  75424. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75425. CSG.FromPolygons = function (polygons) {
  75426. var csg = new CSG();
  75427. csg.polygons = polygons;
  75428. return csg;
  75429. };
  75430. CSG.prototype.clone = function () {
  75431. var csg = new CSG();
  75432. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75433. csg.copyTransformAttributes(this);
  75434. return csg;
  75435. };
  75436. CSG.prototype.union = function (csg) {
  75437. var a = new Node(this.clone().polygons);
  75438. var b = new Node(csg.clone().polygons);
  75439. a.clipTo(b);
  75440. b.clipTo(a);
  75441. b.invert();
  75442. b.clipTo(a);
  75443. b.invert();
  75444. a.build(b.allPolygons());
  75445. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75446. };
  75447. CSG.prototype.unionInPlace = function (csg) {
  75448. var a = new Node(this.polygons);
  75449. var b = new Node(csg.polygons);
  75450. a.clipTo(b);
  75451. b.clipTo(a);
  75452. b.invert();
  75453. b.clipTo(a);
  75454. b.invert();
  75455. a.build(b.allPolygons());
  75456. this.polygons = a.allPolygons();
  75457. };
  75458. CSG.prototype.subtract = function (csg) {
  75459. var a = new Node(this.clone().polygons);
  75460. var b = new Node(csg.clone().polygons);
  75461. a.invert();
  75462. a.clipTo(b);
  75463. b.clipTo(a);
  75464. b.invert();
  75465. b.clipTo(a);
  75466. b.invert();
  75467. a.build(b.allPolygons());
  75468. a.invert();
  75469. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75470. };
  75471. CSG.prototype.subtractInPlace = function (csg) {
  75472. var a = new Node(this.polygons);
  75473. var b = new Node(csg.polygons);
  75474. a.invert();
  75475. a.clipTo(b);
  75476. b.clipTo(a);
  75477. b.invert();
  75478. b.clipTo(a);
  75479. b.invert();
  75480. a.build(b.allPolygons());
  75481. a.invert();
  75482. this.polygons = a.allPolygons();
  75483. };
  75484. CSG.prototype.intersect = function (csg) {
  75485. var a = new Node(this.clone().polygons);
  75486. var b = new Node(csg.clone().polygons);
  75487. a.invert();
  75488. b.clipTo(a);
  75489. b.invert();
  75490. a.clipTo(b);
  75491. b.clipTo(a);
  75492. a.build(b.allPolygons());
  75493. a.invert();
  75494. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75495. };
  75496. CSG.prototype.intersectInPlace = function (csg) {
  75497. var a = new Node(this.polygons);
  75498. var b = new Node(csg.polygons);
  75499. a.invert();
  75500. b.clipTo(a);
  75501. b.invert();
  75502. a.clipTo(b);
  75503. b.clipTo(a);
  75504. a.build(b.allPolygons());
  75505. a.invert();
  75506. this.polygons = a.allPolygons();
  75507. };
  75508. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75509. // not modified.
  75510. CSG.prototype.inverse = function () {
  75511. var csg = this.clone();
  75512. csg.inverseInPlace();
  75513. return csg;
  75514. };
  75515. CSG.prototype.inverseInPlace = function () {
  75516. this.polygons.map(function (p) { p.flip(); });
  75517. };
  75518. // This is used to keep meshes transformations so they can be restored
  75519. // when we build back a Babylon Mesh
  75520. // NB : All CSG operations are performed in world coordinates
  75521. CSG.prototype.copyTransformAttributes = function (csg) {
  75522. this.matrix = csg.matrix;
  75523. this.position = csg.position;
  75524. this.rotation = csg.rotation;
  75525. this.scaling = csg.scaling;
  75526. this.rotationQuaternion = csg.rotationQuaternion;
  75527. return this;
  75528. };
  75529. // Build Raw mesh from CSG
  75530. // Coordinates here are in world space
  75531. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75532. var matrix = this.matrix.clone();
  75533. matrix.invert();
  75534. 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;
  75535. if (keepSubMeshes) {
  75536. // Sort Polygons, since subMeshes are indices range
  75537. polygons.sort(function (a, b) {
  75538. if (a.shared.meshId === b.shared.meshId) {
  75539. return a.shared.subMeshId - b.shared.subMeshId;
  75540. }
  75541. else {
  75542. return a.shared.meshId - b.shared.meshId;
  75543. }
  75544. });
  75545. }
  75546. for (var i = 0, il = polygons.length; i < il; i++) {
  75547. polygon = polygons[i];
  75548. // Building SubMeshes
  75549. if (!subMesh_dict[polygon.shared.meshId]) {
  75550. subMesh_dict[polygon.shared.meshId] = {};
  75551. }
  75552. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75553. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75554. indexStart: +Infinity,
  75555. indexEnd: -Infinity,
  75556. materialIndex: polygon.shared.materialIndex
  75557. };
  75558. }
  75559. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75560. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75561. polygonIndices[0] = 0;
  75562. polygonIndices[1] = j - 1;
  75563. polygonIndices[2] = j;
  75564. for (var k = 0; k < 3; k++) {
  75565. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75566. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75567. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75568. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75569. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75570. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75571. // Check if 2 points can be merged
  75572. if (!(typeof vertex_idx !== 'undefined' &&
  75573. normals[vertex_idx * 3] === localNormal.x &&
  75574. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75575. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75576. uvs[vertex_idx * 2] === uv.x &&
  75577. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75578. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75579. uvs.push(uv.x, uv.y);
  75580. normals.push(normal.x, normal.y, normal.z);
  75581. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75582. }
  75583. indices.push(vertex_idx);
  75584. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75585. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75586. currentIndex++;
  75587. }
  75588. }
  75589. }
  75590. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75591. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75592. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75593. mesh.setIndices(indices, null);
  75594. if (keepSubMeshes) {
  75595. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75596. var materialIndexOffset = 0, materialMaxIndex;
  75597. mesh.subMeshes = new Array();
  75598. for (var m in subMesh_dict) {
  75599. materialMaxIndex = -1;
  75600. for (var sm in subMesh_dict[m]) {
  75601. subMesh_obj = subMesh_dict[m][sm];
  75602. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75603. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75604. }
  75605. materialIndexOffset += ++materialMaxIndex;
  75606. }
  75607. }
  75608. return mesh;
  75609. };
  75610. // Build Mesh from CSG taking material and transforms into account
  75611. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75612. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75613. mesh.material = material;
  75614. mesh.position.copyFrom(this.position);
  75615. mesh.rotation.copyFrom(this.rotation);
  75616. if (this.rotationQuaternion) {
  75617. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75618. }
  75619. mesh.scaling.copyFrom(this.scaling);
  75620. mesh.computeWorldMatrix(true);
  75621. return mesh;
  75622. };
  75623. return CSG;
  75624. }());
  75625. BABYLON.CSG = CSG;
  75626. })(BABYLON || (BABYLON = {}));
  75627. //# sourceMappingURL=babylon.csg.js.map
  75628. var BABYLON;
  75629. (function (BABYLON) {
  75630. var LensFlare = /** @class */ (function () {
  75631. function LensFlare(size, position, color, imgUrl, system) {
  75632. this.size = size;
  75633. this.position = position;
  75634. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75635. this.color = color || new BABYLON.Color3(1, 1, 1);
  75636. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75637. this._system = system;
  75638. system.lensFlares.push(this);
  75639. }
  75640. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75641. return new LensFlare(size, position, color, imgUrl, system);
  75642. };
  75643. LensFlare.prototype.dispose = function () {
  75644. if (this.texture) {
  75645. this.texture.dispose();
  75646. }
  75647. // Remove from scene
  75648. var index = this._system.lensFlares.indexOf(this);
  75649. this._system.lensFlares.splice(index, 1);
  75650. };
  75651. ;
  75652. return LensFlare;
  75653. }());
  75654. BABYLON.LensFlare = LensFlare;
  75655. })(BABYLON || (BABYLON = {}));
  75656. //# sourceMappingURL=babylon.lensFlare.js.map
  75657. var BABYLON;
  75658. (function (BABYLON) {
  75659. var LensFlareSystem = /** @class */ (function () {
  75660. function LensFlareSystem(name, emitter, scene) {
  75661. this.name = name;
  75662. this.lensFlares = new Array();
  75663. this.borderLimit = 300;
  75664. this.viewportBorder = 0;
  75665. this.layerMask = 0x0FFFFFFF;
  75666. this._vertexBuffers = {};
  75667. this._isEnabled = true;
  75668. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75669. this._emitter = emitter;
  75670. this.id = name;
  75671. scene.lensFlareSystems.push(this);
  75672. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75673. var engine = scene.getEngine();
  75674. // VBO
  75675. var vertices = [];
  75676. vertices.push(1, 1);
  75677. vertices.push(-1, 1);
  75678. vertices.push(-1, -1);
  75679. vertices.push(1, -1);
  75680. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75681. // Indices
  75682. var indices = [];
  75683. indices.push(0);
  75684. indices.push(1);
  75685. indices.push(2);
  75686. indices.push(0);
  75687. indices.push(2);
  75688. indices.push(3);
  75689. this._indexBuffer = engine.createIndexBuffer(indices);
  75690. // Effects
  75691. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75692. }
  75693. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75694. get: function () {
  75695. return this._isEnabled;
  75696. },
  75697. set: function (value) {
  75698. this._isEnabled = value;
  75699. },
  75700. enumerable: true,
  75701. configurable: true
  75702. });
  75703. LensFlareSystem.prototype.getScene = function () {
  75704. return this._scene;
  75705. };
  75706. LensFlareSystem.prototype.getEmitter = function () {
  75707. return this._emitter;
  75708. };
  75709. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75710. this._emitter = newEmitter;
  75711. };
  75712. LensFlareSystem.prototype.getEmitterPosition = function () {
  75713. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75714. };
  75715. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75716. var position = this.getEmitterPosition();
  75717. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75718. this._positionX = position.x;
  75719. this._positionY = position.y;
  75720. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75721. if (this.viewportBorder > 0) {
  75722. globalViewport.x -= this.viewportBorder;
  75723. globalViewport.y -= this.viewportBorder;
  75724. globalViewport.width += this.viewportBorder * 2;
  75725. globalViewport.height += this.viewportBorder * 2;
  75726. position.x += this.viewportBorder;
  75727. position.y += this.viewportBorder;
  75728. this._positionX += this.viewportBorder;
  75729. this._positionY += this.viewportBorder;
  75730. }
  75731. if (position.z > 0) {
  75732. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75733. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75734. return true;
  75735. }
  75736. return true;
  75737. }
  75738. return false;
  75739. };
  75740. LensFlareSystem.prototype._isVisible = function () {
  75741. if (!this._isEnabled || !this._scene.activeCamera) {
  75742. return false;
  75743. }
  75744. var emitterPosition = this.getEmitterPosition();
  75745. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75746. var distance = direction.length();
  75747. direction.normalize();
  75748. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75749. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75750. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75751. };
  75752. LensFlareSystem.prototype.render = function () {
  75753. if (!this._effect.isReady() || !this._scene.activeCamera)
  75754. return false;
  75755. var engine = this._scene.getEngine();
  75756. var viewport = this._scene.activeCamera.viewport;
  75757. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75758. // Position
  75759. if (!this.computeEffectivePosition(globalViewport)) {
  75760. return false;
  75761. }
  75762. // Visibility
  75763. if (!this._isVisible()) {
  75764. return false;
  75765. }
  75766. // Intensity
  75767. var awayX;
  75768. var awayY;
  75769. if (this._positionX < this.borderLimit + globalViewport.x) {
  75770. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75771. }
  75772. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75773. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75774. }
  75775. else {
  75776. awayX = 0;
  75777. }
  75778. if (this._positionY < this.borderLimit + globalViewport.y) {
  75779. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75780. }
  75781. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75782. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75783. }
  75784. else {
  75785. awayY = 0;
  75786. }
  75787. var away = (awayX > awayY) ? awayX : awayY;
  75788. away -= this.viewportBorder;
  75789. if (away > this.borderLimit) {
  75790. away = this.borderLimit;
  75791. }
  75792. var intensity = 1.0 - (away / this.borderLimit);
  75793. if (intensity < 0) {
  75794. return false;
  75795. }
  75796. if (intensity > 1.0) {
  75797. intensity = 1.0;
  75798. }
  75799. if (this.viewportBorder > 0) {
  75800. globalViewport.x += this.viewportBorder;
  75801. globalViewport.y += this.viewportBorder;
  75802. globalViewport.width -= this.viewportBorder * 2;
  75803. globalViewport.height -= this.viewportBorder * 2;
  75804. this._positionX -= this.viewportBorder;
  75805. this._positionY -= this.viewportBorder;
  75806. }
  75807. // Position
  75808. var centerX = globalViewport.x + globalViewport.width / 2;
  75809. var centerY = globalViewport.y + globalViewport.height / 2;
  75810. var distX = centerX - this._positionX;
  75811. var distY = centerY - this._positionY;
  75812. // Effects
  75813. engine.enableEffect(this._effect);
  75814. engine.setState(false);
  75815. engine.setDepthBuffer(false);
  75816. // VBOs
  75817. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75818. // Flares
  75819. for (var index = 0; index < this.lensFlares.length; index++) {
  75820. var flare = this.lensFlares[index];
  75821. engine.setAlphaMode(flare.alphaMode);
  75822. var x = centerX - (distX * flare.position);
  75823. var y = centerY - (distY * flare.position);
  75824. var cw = flare.size;
  75825. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75826. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75827. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75828. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75829. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75830. // Texture
  75831. this._effect.setTexture("textureSampler", flare.texture);
  75832. // Color
  75833. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75834. // Draw order
  75835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75836. }
  75837. engine.setDepthBuffer(true);
  75838. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75839. return true;
  75840. };
  75841. LensFlareSystem.prototype.dispose = function () {
  75842. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75843. if (vertexBuffer) {
  75844. vertexBuffer.dispose();
  75845. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75846. }
  75847. if (this._indexBuffer) {
  75848. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75849. this._indexBuffer = null;
  75850. }
  75851. while (this.lensFlares.length) {
  75852. this.lensFlares[0].dispose();
  75853. }
  75854. // Remove from scene
  75855. var index = this._scene.lensFlareSystems.indexOf(this);
  75856. this._scene.lensFlareSystems.splice(index, 1);
  75857. };
  75858. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75859. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75860. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75861. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75862. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75863. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75864. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75865. var parsedFlare = parsedLensFlareSystem.flares[index];
  75866. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75867. }
  75868. return lensFlareSystem;
  75869. };
  75870. LensFlareSystem.prototype.serialize = function () {
  75871. var serializationObject = {};
  75872. serializationObject.id = this.id;
  75873. serializationObject.name = this.name;
  75874. serializationObject.emitterId = this.getEmitter().id;
  75875. serializationObject.borderLimit = this.borderLimit;
  75876. serializationObject.flares = [];
  75877. for (var index = 0; index < this.lensFlares.length; index++) {
  75878. var flare = this.lensFlares[index];
  75879. serializationObject.flares.push({
  75880. size: flare.size,
  75881. position: flare.position,
  75882. color: flare.color.asArray(),
  75883. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75884. });
  75885. }
  75886. return serializationObject;
  75887. };
  75888. return LensFlareSystem;
  75889. }());
  75890. BABYLON.LensFlareSystem = LensFlareSystem;
  75891. })(BABYLON || (BABYLON = {}));
  75892. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75893. var BABYLON;
  75894. (function (BABYLON) {
  75895. /**
  75896. * This is a holder class for the physics joint created by the physics plugin.
  75897. * It holds a set of functions to control the underlying joint.
  75898. */
  75899. var PhysicsJoint = /** @class */ (function () {
  75900. function PhysicsJoint(type, jointData) {
  75901. this.type = type;
  75902. this.jointData = jointData;
  75903. jointData.nativeParams = jointData.nativeParams || {};
  75904. }
  75905. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75906. get: function () {
  75907. return this._physicsJoint;
  75908. },
  75909. set: function (newJoint) {
  75910. if (this._physicsJoint) {
  75911. //remove from the wolrd
  75912. }
  75913. this._physicsJoint = newJoint;
  75914. },
  75915. enumerable: true,
  75916. configurable: true
  75917. });
  75918. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75919. set: function (physicsPlugin) {
  75920. this._physicsPlugin = physicsPlugin;
  75921. },
  75922. enumerable: true,
  75923. configurable: true
  75924. });
  75925. /**
  75926. * Execute a function that is physics-plugin specific.
  75927. * @param {Function} func the function that will be executed.
  75928. * It accepts two parameters: the physics world and the physics joint.
  75929. */
  75930. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75931. func(this._physicsPlugin.world, this._physicsJoint);
  75932. };
  75933. //TODO check if the native joints are the same
  75934. //Joint Types
  75935. PhysicsJoint.DistanceJoint = 0;
  75936. PhysicsJoint.HingeJoint = 1;
  75937. PhysicsJoint.BallAndSocketJoint = 2;
  75938. PhysicsJoint.WheelJoint = 3;
  75939. PhysicsJoint.SliderJoint = 4;
  75940. //OIMO
  75941. PhysicsJoint.PrismaticJoint = 5;
  75942. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75943. PhysicsJoint.UniversalJoint = 6;
  75944. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75945. //Cannon
  75946. //Similar to a Ball-Joint. Different in params
  75947. PhysicsJoint.PointToPointJoint = 8;
  75948. //Cannon only at the moment
  75949. PhysicsJoint.SpringJoint = 9;
  75950. PhysicsJoint.LockJoint = 10;
  75951. return PhysicsJoint;
  75952. }());
  75953. BABYLON.PhysicsJoint = PhysicsJoint;
  75954. /**
  75955. * A class representing a physics distance joint.
  75956. */
  75957. var DistanceJoint = /** @class */ (function (_super) {
  75958. __extends(DistanceJoint, _super);
  75959. function DistanceJoint(jointData) {
  75960. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75961. }
  75962. /**
  75963. * Update the predefined distance.
  75964. */
  75965. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75966. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75967. };
  75968. return DistanceJoint;
  75969. }(PhysicsJoint));
  75970. BABYLON.DistanceJoint = DistanceJoint;
  75971. var MotorEnabledJoint = /** @class */ (function (_super) {
  75972. __extends(MotorEnabledJoint, _super);
  75973. function MotorEnabledJoint(type, jointData) {
  75974. return _super.call(this, type, jointData) || this;
  75975. }
  75976. /**
  75977. * Set the motor values.
  75978. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75979. * @param {number} force the force to apply
  75980. * @param {number} maxForce max force for this motor.
  75981. */
  75982. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75983. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75984. };
  75985. /**
  75986. * Set the motor's limits.
  75987. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75988. */
  75989. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75990. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75991. };
  75992. return MotorEnabledJoint;
  75993. }(PhysicsJoint));
  75994. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75995. /**
  75996. * This class represents a single hinge physics joint
  75997. */
  75998. var HingeJoint = /** @class */ (function (_super) {
  75999. __extends(HingeJoint, _super);
  76000. function HingeJoint(jointData) {
  76001. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76002. }
  76003. /**
  76004. * Set the motor values.
  76005. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76006. * @param {number} force the force to apply
  76007. * @param {number} maxForce max force for this motor.
  76008. */
  76009. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76010. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76011. };
  76012. /**
  76013. * Set the motor's limits.
  76014. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76015. */
  76016. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76017. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76018. };
  76019. return HingeJoint;
  76020. }(MotorEnabledJoint));
  76021. BABYLON.HingeJoint = HingeJoint;
  76022. /**
  76023. * This class represents a dual hinge physics joint (same as wheel joint)
  76024. */
  76025. var Hinge2Joint = /** @class */ (function (_super) {
  76026. __extends(Hinge2Joint, _super);
  76027. function Hinge2Joint(jointData) {
  76028. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76029. }
  76030. /**
  76031. * Set the motor values.
  76032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76033. * @param {number} force the force to apply
  76034. * @param {number} maxForce max force for this motor.
  76035. * @param {motorIndex} the motor's index, 0 or 1.
  76036. */
  76037. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76038. if (motorIndex === void 0) { motorIndex = 0; }
  76039. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76040. };
  76041. /**
  76042. * Set the motor limits.
  76043. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76044. * @param {number} upperLimit the upper limit
  76045. * @param {number} lowerLimit lower limit
  76046. * @param {motorIndex} the motor's index, 0 or 1.
  76047. */
  76048. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76049. if (motorIndex === void 0) { motorIndex = 0; }
  76050. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76051. };
  76052. return Hinge2Joint;
  76053. }(MotorEnabledJoint));
  76054. BABYLON.Hinge2Joint = Hinge2Joint;
  76055. })(BABYLON || (BABYLON = {}));
  76056. //# sourceMappingURL=babylon.physicsJoint.js.map
  76057. var BABYLON;
  76058. (function (BABYLON) {
  76059. var PhysicsImpostor = /** @class */ (function () {
  76060. function PhysicsImpostor(object, type, _options, _scene) {
  76061. if (_options === void 0) { _options = { mass: 0 }; }
  76062. var _this = this;
  76063. this.object = object;
  76064. this.type = type;
  76065. this._options = _options;
  76066. this._scene = _scene;
  76067. this._bodyUpdateRequired = false;
  76068. this._onBeforePhysicsStepCallbacks = new Array();
  76069. this._onAfterPhysicsStepCallbacks = new Array();
  76070. this._onPhysicsCollideCallbacks = [];
  76071. this._deltaPosition = BABYLON.Vector3.Zero();
  76072. this._isDisposed = false;
  76073. //temp variables for parent rotation calculations
  76074. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76075. this._tmpQuat = new BABYLON.Quaternion();
  76076. this._tmpQuat2 = new BABYLON.Quaternion();
  76077. /**
  76078. * this function is executed by the physics engine.
  76079. */
  76080. this.beforeStep = function () {
  76081. if (!_this._physicsEngine) {
  76082. return;
  76083. }
  76084. _this.object.translate(_this._deltaPosition, -1);
  76085. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76086. _this.object.computeWorldMatrix(false);
  76087. if (_this.object.parent && _this.object.rotationQuaternion) {
  76088. _this.getParentsRotation();
  76089. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76090. }
  76091. else {
  76092. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76093. }
  76094. if (!_this._options.disableBidirectionalTransformation) {
  76095. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76096. }
  76097. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76098. func(_this);
  76099. });
  76100. };
  76101. /**
  76102. * this function is executed by the physics engine.
  76103. */
  76104. this.afterStep = function () {
  76105. if (!_this._physicsEngine) {
  76106. return;
  76107. }
  76108. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76109. func(_this);
  76110. });
  76111. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76112. // object has now its world rotation. needs to be converted to local.
  76113. if (_this.object.parent && _this.object.rotationQuaternion) {
  76114. _this.getParentsRotation();
  76115. _this._tmpQuat.conjugateInPlace();
  76116. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76117. }
  76118. // take the position set and make it the absolute position of this object.
  76119. _this.object.setAbsolutePosition(_this.object.position);
  76120. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76121. _this.object.translate(_this._deltaPosition, 1);
  76122. };
  76123. /**
  76124. * Legacy collision detection event support
  76125. */
  76126. this.onCollideEvent = null;
  76127. //event and body object due to cannon's event-based architecture.
  76128. this.onCollide = function (e) {
  76129. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76130. return;
  76131. }
  76132. if (!_this._physicsEngine) {
  76133. return;
  76134. }
  76135. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76136. if (otherImpostor) {
  76137. // Legacy collision detection event support
  76138. if (_this.onCollideEvent) {
  76139. _this.onCollideEvent(_this, otherImpostor);
  76140. }
  76141. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76142. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76143. }).forEach(function (obj) {
  76144. obj.callback(_this, otherImpostor);
  76145. });
  76146. }
  76147. };
  76148. //sanity check!
  76149. if (!this.object) {
  76150. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76151. return;
  76152. }
  76153. //legacy support for old syntax.
  76154. if (!this._scene && object.getScene) {
  76155. this._scene = object.getScene();
  76156. }
  76157. if (!this._scene) {
  76158. return;
  76159. }
  76160. this._physicsEngine = this._scene.getPhysicsEngine();
  76161. if (!this._physicsEngine) {
  76162. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76163. }
  76164. else {
  76165. //set the object's quaternion, if not set
  76166. if (!this.object.rotationQuaternion) {
  76167. if (this.object.rotation) {
  76168. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76169. }
  76170. else {
  76171. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76172. }
  76173. }
  76174. //default options params
  76175. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76176. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76177. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76178. this._joints = [];
  76179. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76180. if (!this.object.parent || this._options.ignoreParent) {
  76181. this._init();
  76182. }
  76183. else if (this.object.parent.physicsImpostor) {
  76184. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76185. }
  76186. }
  76187. }
  76188. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76189. get: function () {
  76190. return this._isDisposed;
  76191. },
  76192. enumerable: true,
  76193. configurable: true
  76194. });
  76195. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76196. get: function () {
  76197. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76198. },
  76199. set: function (value) {
  76200. this.setMass(value);
  76201. },
  76202. enumerable: true,
  76203. configurable: true
  76204. });
  76205. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76206. get: function () {
  76207. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76208. },
  76209. set: function (value) {
  76210. if (!this._physicsEngine) {
  76211. return;
  76212. }
  76213. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76214. },
  76215. enumerable: true,
  76216. configurable: true
  76217. });
  76218. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76219. get: function () {
  76220. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76221. },
  76222. set: function (value) {
  76223. if (!this._physicsEngine) {
  76224. return;
  76225. }
  76226. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76227. },
  76228. enumerable: true,
  76229. configurable: true
  76230. });
  76231. /**
  76232. * This function will completly initialize this impostor.
  76233. * It will create a new body - but only if this mesh has no parent.
  76234. * If it has, this impostor will not be used other than to define the impostor
  76235. * of the child mesh.
  76236. */
  76237. PhysicsImpostor.prototype._init = function () {
  76238. if (!this._physicsEngine) {
  76239. return;
  76240. }
  76241. this._physicsEngine.removeImpostor(this);
  76242. this.physicsBody = null;
  76243. this._parent = this._parent || this._getPhysicsParent();
  76244. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76245. this._physicsEngine.addImpostor(this);
  76246. }
  76247. };
  76248. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76249. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76250. var parentMesh = this.object.parent;
  76251. return parentMesh.physicsImpostor;
  76252. }
  76253. return null;
  76254. };
  76255. /**
  76256. * Should a new body be generated.
  76257. */
  76258. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76259. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76260. };
  76261. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76262. this.forceUpdate();
  76263. };
  76264. /**
  76265. * Force a regeneration of this or the parent's impostor's body.
  76266. * Use under cautious - This will remove all joints already implemented.
  76267. */
  76268. PhysicsImpostor.prototype.forceUpdate = function () {
  76269. this._init();
  76270. if (this.parent && !this._options.ignoreParent) {
  76271. this.parent.forceUpdate();
  76272. }
  76273. };
  76274. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76275. /*public get mesh(): AbstractMesh {
  76276. return this._mesh;
  76277. }*/
  76278. /**
  76279. * Gets the body that holds this impostor. Either its own, or its parent.
  76280. */
  76281. get: function () {
  76282. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76283. },
  76284. /**
  76285. * Set the physics body. Used mainly by the physics engine/plugin
  76286. */
  76287. set: function (physicsBody) {
  76288. if (this._physicsBody && this._physicsEngine) {
  76289. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76290. }
  76291. this._physicsBody = physicsBody;
  76292. this.resetUpdateFlags();
  76293. },
  76294. enumerable: true,
  76295. configurable: true
  76296. });
  76297. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76298. get: function () {
  76299. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76300. },
  76301. set: function (value) {
  76302. this._parent = value;
  76303. },
  76304. enumerable: true,
  76305. configurable: true
  76306. });
  76307. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76308. this._bodyUpdateRequired = false;
  76309. };
  76310. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76311. if (this.object.getBoundingInfo) {
  76312. var q = this.object.rotationQuaternion;
  76313. //reset rotation
  76314. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76315. //calculate the world matrix with no rotation
  76316. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76317. var boundingInfo = this.object.getBoundingInfo();
  76318. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76319. //bring back the rotation
  76320. this.object.rotationQuaternion = q;
  76321. //calculate the world matrix with the new rotation
  76322. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76323. return size;
  76324. }
  76325. else {
  76326. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76327. }
  76328. };
  76329. PhysicsImpostor.prototype.getObjectCenter = function () {
  76330. if (this.object.getBoundingInfo) {
  76331. var boundingInfo = this.object.getBoundingInfo();
  76332. return boundingInfo.boundingBox.centerWorld;
  76333. }
  76334. else {
  76335. return this.object.position;
  76336. }
  76337. };
  76338. /**
  76339. * Get a specific parametes from the options parameter.
  76340. */
  76341. PhysicsImpostor.prototype.getParam = function (paramName) {
  76342. return this._options[paramName];
  76343. };
  76344. /**
  76345. * Sets a specific parameter in the options given to the physics plugin
  76346. */
  76347. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76348. this._options[paramName] = value;
  76349. this._bodyUpdateRequired = true;
  76350. };
  76351. /**
  76352. * Specifically change the body's mass option. Won't recreate the physics body object
  76353. */
  76354. PhysicsImpostor.prototype.setMass = function (mass) {
  76355. if (this.getParam("mass") !== mass) {
  76356. this.setParam("mass", mass);
  76357. }
  76358. if (this._physicsEngine) {
  76359. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76360. }
  76361. };
  76362. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76363. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76364. };
  76365. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76366. if (this._physicsEngine) {
  76367. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76368. }
  76369. };
  76370. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76371. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76372. };
  76373. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76374. if (this._physicsEngine) {
  76375. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76376. }
  76377. };
  76378. /**
  76379. * Execute a function with the physics plugin native code.
  76380. * Provide a function the will have two variables - the world object and the physics body object.
  76381. */
  76382. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76383. if (this._physicsEngine) {
  76384. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76385. }
  76386. };
  76387. /**
  76388. * Register a function that will be executed before the physics world is stepping forward.
  76389. */
  76390. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76391. this._onBeforePhysicsStepCallbacks.push(func);
  76392. };
  76393. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76394. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76395. if (index > -1) {
  76396. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76397. }
  76398. else {
  76399. BABYLON.Tools.Warn("Function to remove was not found");
  76400. }
  76401. };
  76402. /**
  76403. * Register a function that will be executed after the physics step
  76404. */
  76405. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76406. this._onAfterPhysicsStepCallbacks.push(func);
  76407. };
  76408. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76409. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76410. if (index > -1) {
  76411. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76412. }
  76413. else {
  76414. BABYLON.Tools.Warn("Function to remove was not found");
  76415. }
  76416. };
  76417. /**
  76418. * register a function that will be executed when this impostor collides against a different body.
  76419. */
  76420. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76421. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76422. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76423. };
  76424. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76425. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76426. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76427. if (index > -1) {
  76428. this._onPhysicsCollideCallbacks.splice(index, 1);
  76429. }
  76430. else {
  76431. BABYLON.Tools.Warn("Function to remove was not found");
  76432. }
  76433. };
  76434. PhysicsImpostor.prototype.getParentsRotation = function () {
  76435. var parent = this.object.parent;
  76436. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76437. while (parent) {
  76438. if (parent.rotationQuaternion) {
  76439. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76440. }
  76441. else {
  76442. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76443. }
  76444. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76445. parent = parent.parent;
  76446. }
  76447. return this._tmpQuat;
  76448. };
  76449. /**
  76450. * Apply a force
  76451. */
  76452. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76453. if (this._physicsEngine) {
  76454. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76455. }
  76456. return this;
  76457. };
  76458. /**
  76459. * Apply an impulse
  76460. */
  76461. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76462. if (this._physicsEngine) {
  76463. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76464. }
  76465. return this;
  76466. };
  76467. /**
  76468. * A help function to create a joint.
  76469. */
  76470. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76471. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76472. this.addJoint(otherImpostor, joint);
  76473. return this;
  76474. };
  76475. /**
  76476. * Add a joint to this impostor with a different impostor.
  76477. */
  76478. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76479. this._joints.push({
  76480. otherImpostor: otherImpostor,
  76481. joint: joint
  76482. });
  76483. if (this._physicsEngine) {
  76484. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76485. }
  76486. return this;
  76487. };
  76488. /**
  76489. * Will keep this body still, in a sleep mode.
  76490. */
  76491. PhysicsImpostor.prototype.sleep = function () {
  76492. if (this._physicsEngine) {
  76493. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76494. }
  76495. return this;
  76496. };
  76497. /**
  76498. * Wake the body up.
  76499. */
  76500. PhysicsImpostor.prototype.wakeUp = function () {
  76501. if (this._physicsEngine) {
  76502. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76503. }
  76504. return this;
  76505. };
  76506. PhysicsImpostor.prototype.clone = function (newObject) {
  76507. if (!newObject)
  76508. return null;
  76509. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76510. };
  76511. PhysicsImpostor.prototype.dispose = function () {
  76512. var _this = this;
  76513. //no dispose if no physics engine is available.
  76514. if (!this._physicsEngine) {
  76515. return;
  76516. }
  76517. this._joints.forEach(function (j) {
  76518. if (_this._physicsEngine) {
  76519. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76520. }
  76521. });
  76522. //dispose the physics body
  76523. this._physicsEngine.removeImpostor(this);
  76524. if (this.parent) {
  76525. this.parent.forceUpdate();
  76526. }
  76527. else {
  76528. /*this._object.getChildMeshes().forEach(function(mesh) {
  76529. if (mesh.physicsImpostor) {
  76530. if (disposeChildren) {
  76531. mesh.physicsImpostor.dispose();
  76532. mesh.physicsImpostor = null;
  76533. }
  76534. }
  76535. })*/
  76536. }
  76537. this._isDisposed = true;
  76538. };
  76539. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76540. this._deltaPosition.copyFrom(position);
  76541. };
  76542. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76543. if (!this._deltaRotation) {
  76544. this._deltaRotation = new BABYLON.Quaternion();
  76545. }
  76546. this._deltaRotation.copyFrom(rotation);
  76547. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76548. };
  76549. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76550. if (this._physicsEngine) {
  76551. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76552. }
  76553. return this;
  76554. };
  76555. PhysicsImpostor.prototype.getRadius = function () {
  76556. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76557. };
  76558. /**
  76559. * Sync a bone with this impostor
  76560. * @param bone The bone to sync to the impostor.
  76561. * @param boneMesh The mesh that the bone is influencing.
  76562. * @param jointPivot The pivot of the joint / bone in local space.
  76563. * @param distToJoint Optional distance from the impostor to the joint.
  76564. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76565. */
  76566. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76567. var tempVec = PhysicsImpostor._tmpVecs[0];
  76568. var mesh = this.object;
  76569. if (mesh.rotationQuaternion) {
  76570. if (adjustRotation) {
  76571. var tempQuat = PhysicsImpostor._tmpQuat;
  76572. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76573. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76574. }
  76575. else {
  76576. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76577. }
  76578. }
  76579. tempVec.x = 0;
  76580. tempVec.y = 0;
  76581. tempVec.z = 0;
  76582. if (jointPivot) {
  76583. tempVec.x = jointPivot.x;
  76584. tempVec.y = jointPivot.y;
  76585. tempVec.z = jointPivot.z;
  76586. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76587. if (distToJoint === undefined || distToJoint === null) {
  76588. distToJoint = jointPivot.length();
  76589. }
  76590. tempVec.x *= distToJoint;
  76591. tempVec.y *= distToJoint;
  76592. tempVec.z *= distToJoint;
  76593. }
  76594. if (bone.getParent()) {
  76595. tempVec.addInPlace(mesh.getAbsolutePosition());
  76596. bone.setAbsolutePosition(tempVec, boneMesh);
  76597. }
  76598. else {
  76599. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76600. boneMesh.position.x -= tempVec.x;
  76601. boneMesh.position.y -= tempVec.y;
  76602. boneMesh.position.z -= tempVec.z;
  76603. }
  76604. };
  76605. /**
  76606. * Sync impostor to a bone
  76607. * @param bone The bone that the impostor will be synced to.
  76608. * @param boneMesh The mesh that the bone is influencing.
  76609. * @param jointPivot The pivot of the joint / bone in local space.
  76610. * @param distToJoint Optional distance from the impostor to the joint.
  76611. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76612. * @param boneAxis Optional vector3 axis the bone is aligned with
  76613. */
  76614. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76615. var mesh = this.object;
  76616. if (mesh.rotationQuaternion) {
  76617. if (adjustRotation) {
  76618. var tempQuat = PhysicsImpostor._tmpQuat;
  76619. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76620. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76621. }
  76622. else {
  76623. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76624. }
  76625. }
  76626. var pos = PhysicsImpostor._tmpVecs[0];
  76627. var boneDir = PhysicsImpostor._tmpVecs[1];
  76628. if (!boneAxis) {
  76629. boneAxis = PhysicsImpostor._tmpVecs[2];
  76630. boneAxis.x = 0;
  76631. boneAxis.y = 1;
  76632. boneAxis.z = 0;
  76633. }
  76634. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76635. bone.getAbsolutePositionToRef(boneMesh, pos);
  76636. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76637. distToJoint = jointPivot.length();
  76638. }
  76639. if (distToJoint !== undefined && distToJoint !== null) {
  76640. pos.x += boneDir.x * distToJoint;
  76641. pos.y += boneDir.y * distToJoint;
  76642. pos.z += boneDir.z * distToJoint;
  76643. }
  76644. mesh.setAbsolutePosition(pos);
  76645. };
  76646. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76647. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76648. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76649. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76650. //Impostor types
  76651. PhysicsImpostor.NoImpostor = 0;
  76652. PhysicsImpostor.SphereImpostor = 1;
  76653. PhysicsImpostor.BoxImpostor = 2;
  76654. PhysicsImpostor.PlaneImpostor = 3;
  76655. PhysicsImpostor.MeshImpostor = 4;
  76656. PhysicsImpostor.CylinderImpostor = 7;
  76657. PhysicsImpostor.ParticleImpostor = 8;
  76658. PhysicsImpostor.HeightmapImpostor = 9;
  76659. return PhysicsImpostor;
  76660. }());
  76661. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76662. })(BABYLON || (BABYLON = {}));
  76663. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76664. var BABYLON;
  76665. (function (BABYLON) {
  76666. var PhysicsEngine = /** @class */ (function () {
  76667. function PhysicsEngine(gravity, _physicsPlugin) {
  76668. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76669. this._physicsPlugin = _physicsPlugin;
  76670. //new methods and parameters
  76671. this._impostors = [];
  76672. this._joints = [];
  76673. if (!this._physicsPlugin.isSupported()) {
  76674. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76675. + "Please make sure it is included.");
  76676. }
  76677. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76678. this.setGravity(gravity);
  76679. this.setTimeStep();
  76680. }
  76681. PhysicsEngine.prototype.setGravity = function (gravity) {
  76682. this.gravity = gravity;
  76683. this._physicsPlugin.setGravity(this.gravity);
  76684. };
  76685. /**
  76686. * Set the time step of the physics engine.
  76687. * default is 1/60.
  76688. * To slow it down, enter 1/600 for example.
  76689. * To speed it up, 1/30
  76690. * @param {number} newTimeStep the new timestep to apply to this world.
  76691. */
  76692. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76693. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76694. this._physicsPlugin.setTimeStep(newTimeStep);
  76695. };
  76696. /**
  76697. * Get the time step of the physics engine.
  76698. */
  76699. PhysicsEngine.prototype.getTimeStep = function () {
  76700. return this._physicsPlugin.getTimeStep();
  76701. };
  76702. PhysicsEngine.prototype.dispose = function () {
  76703. this._impostors.forEach(function (impostor) {
  76704. impostor.dispose();
  76705. });
  76706. this._physicsPlugin.dispose();
  76707. };
  76708. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76709. return this._physicsPlugin.name;
  76710. };
  76711. /**
  76712. * Adding a new impostor for the impostor tracking.
  76713. * This will be done by the impostor itself.
  76714. * @param {PhysicsImpostor} impostor the impostor to add
  76715. */
  76716. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76717. impostor.uniqueId = this._impostors.push(impostor);
  76718. //if no parent, generate the body
  76719. if (!impostor.parent) {
  76720. this._physicsPlugin.generatePhysicsBody(impostor);
  76721. }
  76722. };
  76723. /**
  76724. * Remove an impostor from the engine.
  76725. * This impostor and its mesh will not longer be updated by the physics engine.
  76726. * @param {PhysicsImpostor} impostor the impostor to remove
  76727. */
  76728. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76729. var index = this._impostors.indexOf(impostor);
  76730. if (index > -1) {
  76731. var removed = this._impostors.splice(index, 1);
  76732. //Is it needed?
  76733. if (removed.length) {
  76734. //this will also remove it from the world.
  76735. removed[0].physicsBody = null;
  76736. }
  76737. }
  76738. };
  76739. /**
  76740. * Add a joint to the physics engine
  76741. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76742. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76743. * @param {PhysicsJoint} the joint that will connect both impostors.
  76744. */
  76745. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76746. var impostorJoint = {
  76747. mainImpostor: mainImpostor,
  76748. connectedImpostor: connectedImpostor,
  76749. joint: joint
  76750. };
  76751. joint.physicsPlugin = this._physicsPlugin;
  76752. this._joints.push(impostorJoint);
  76753. this._physicsPlugin.generateJoint(impostorJoint);
  76754. };
  76755. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76756. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76757. return (impostorJoint.connectedImpostor === connectedImpostor
  76758. && impostorJoint.joint === joint
  76759. && impostorJoint.mainImpostor === mainImpostor);
  76760. });
  76761. if (matchingJoints.length) {
  76762. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76763. //TODO remove it from the list as well
  76764. }
  76765. };
  76766. /**
  76767. * Called by the scene. no need to call it.
  76768. */
  76769. PhysicsEngine.prototype._step = function (delta) {
  76770. var _this = this;
  76771. //check if any mesh has no body / requires an update
  76772. this._impostors.forEach(function (impostor) {
  76773. if (impostor.isBodyInitRequired()) {
  76774. _this._physicsPlugin.generatePhysicsBody(impostor);
  76775. }
  76776. });
  76777. if (delta > 0.1) {
  76778. delta = 0.1;
  76779. }
  76780. else if (delta <= 0) {
  76781. delta = 1.0 / 60.0;
  76782. }
  76783. this._physicsPlugin.executeStep(delta, this._impostors);
  76784. };
  76785. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76786. return this._physicsPlugin;
  76787. };
  76788. PhysicsEngine.prototype.getImpostors = function () {
  76789. return this._impostors;
  76790. };
  76791. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76792. for (var i = 0; i < this._impostors.length; ++i) {
  76793. if (this._impostors[i].object === object) {
  76794. return this._impostors[i];
  76795. }
  76796. }
  76797. return null;
  76798. };
  76799. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76800. for (var i = 0; i < this._impostors.length; ++i) {
  76801. if (this._impostors[i].physicsBody === body) {
  76802. return this._impostors[i];
  76803. }
  76804. }
  76805. return null;
  76806. };
  76807. // Statics
  76808. PhysicsEngine.Epsilon = 0.001;
  76809. return PhysicsEngine;
  76810. }());
  76811. BABYLON.PhysicsEngine = PhysicsEngine;
  76812. })(BABYLON || (BABYLON = {}));
  76813. //# sourceMappingURL=babylon.physicsEngine.js.map
  76814. var BABYLON;
  76815. (function (BABYLON) {
  76816. var PhysicsHelper = /** @class */ (function () {
  76817. function PhysicsHelper(scene) {
  76818. this._scene = scene;
  76819. this._physicsEngine = this._scene.getPhysicsEngine();
  76820. if (!this._physicsEngine) {
  76821. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76822. }
  76823. }
  76824. /**
  76825. * @param {Vector3} origin the origin of the explosion
  76826. * @param {number} radius the explosion radius
  76827. * @param {number} strength the explosion strength
  76828. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76829. */
  76830. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76831. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76832. if (!this._physicsEngine) {
  76833. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76834. return null;
  76835. }
  76836. var impostors = this._physicsEngine.getImpostors();
  76837. if (impostors.length === 0) {
  76838. return null;
  76839. }
  76840. var event = new PhysicsRadialExplosionEvent(this._scene);
  76841. impostors.forEach(function (impostor) {
  76842. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76843. if (!impostorForceAndContactPoint) {
  76844. return;
  76845. }
  76846. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76847. });
  76848. event.dispose(false);
  76849. return event;
  76850. };
  76851. /**
  76852. * @param {Vector3} origin the origin of the explosion
  76853. * @param {number} radius the explosion radius
  76854. * @param {number} strength the explosion strength
  76855. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76856. */
  76857. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76858. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76859. if (!this._physicsEngine) {
  76860. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76861. return null;
  76862. }
  76863. var impostors = this._physicsEngine.getImpostors();
  76864. if (impostors.length === 0) {
  76865. return null;
  76866. }
  76867. var event = new PhysicsRadialExplosionEvent(this._scene);
  76868. impostors.forEach(function (impostor) {
  76869. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76870. if (!impostorForceAndContactPoint) {
  76871. return;
  76872. }
  76873. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76874. });
  76875. event.dispose(false);
  76876. return event;
  76877. };
  76878. /**
  76879. * @param {Vector3} origin the origin of the explosion
  76880. * @param {number} radius the explosion radius
  76881. * @param {number} strength the explosion strength
  76882. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76883. */
  76884. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76885. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76886. if (!this._physicsEngine) {
  76887. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76888. return null;
  76889. }
  76890. var impostors = this._physicsEngine.getImpostors();
  76891. if (impostors.length === 0) {
  76892. return null;
  76893. }
  76894. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76895. event.dispose(false);
  76896. return event;
  76897. };
  76898. /**
  76899. * @param {Vector3} origin the origin of the updraft
  76900. * @param {number} radius the radius of the updraft
  76901. * @param {number} strength the strength of the updraft
  76902. * @param {number} height the height of the updraft
  76903. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76904. */
  76905. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76906. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76907. if (!this._physicsEngine) {
  76908. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76909. return null;
  76910. }
  76911. if (this._physicsEngine.getImpostors().length === 0) {
  76912. return null;
  76913. }
  76914. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76915. event.dispose(false);
  76916. return event;
  76917. };
  76918. /**
  76919. * @param {Vector3} origin the of the vortex
  76920. * @param {number} radius the radius of the vortex
  76921. * @param {number} strength the strength of the vortex
  76922. * @param {number} height the height of the vortex
  76923. */
  76924. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76925. if (!this._physicsEngine) {
  76926. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76927. return null;
  76928. }
  76929. if (this._physicsEngine.getImpostors().length === 0) {
  76930. return null;
  76931. }
  76932. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76933. event.dispose(false);
  76934. return event;
  76935. };
  76936. return PhysicsHelper;
  76937. }());
  76938. BABYLON.PhysicsHelper = PhysicsHelper;
  76939. /***** Radial explosion *****/
  76940. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76941. function PhysicsRadialExplosionEvent(scene) {
  76942. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76943. this._rays = [];
  76944. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76945. this._scene = scene;
  76946. }
  76947. /**
  76948. * Returns the data related to the radial explosion event (sphere & rays).
  76949. * @returns {PhysicsRadialExplosionEventData}
  76950. */
  76951. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76952. this._dataFetched = true;
  76953. return {
  76954. sphere: this._sphere,
  76955. rays: this._rays,
  76956. };
  76957. };
  76958. /**
  76959. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76960. * @param impostor
  76961. * @param {Vector3} origin the origin of the explosion
  76962. * @param {number} radius the explosion radius
  76963. * @param {number} strength the explosion strength
  76964. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76965. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76966. */
  76967. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76968. if (impostor.mass === 0) {
  76969. return null;
  76970. }
  76971. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76972. return null;
  76973. }
  76974. if (impostor.object.getClassName() !== 'Mesh') {
  76975. return null;
  76976. }
  76977. var impostorObject = impostor.object;
  76978. var impostorObjectCenter = impostor.getObjectCenter();
  76979. var direction = impostorObjectCenter.subtract(origin);
  76980. var ray = new BABYLON.Ray(origin, direction, radius);
  76981. this._rays.push(ray);
  76982. var hit = ray.intersectsMesh(impostorObject);
  76983. var contactPoint = hit.pickedPoint;
  76984. if (!contactPoint) {
  76985. return null;
  76986. }
  76987. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76988. if (distanceFromOrigin > radius) {
  76989. return null;
  76990. }
  76991. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76992. ? strength
  76993. : strength * (1 - (distanceFromOrigin / radius));
  76994. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76995. return { force: force, contactPoint: contactPoint };
  76996. };
  76997. /**
  76998. * Disposes the sphere.
  76999. * @param {bolean} force
  77000. */
  77001. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77002. var _this = this;
  77003. if (force === void 0) { force = true; }
  77004. if (force) {
  77005. this._sphere.dispose();
  77006. }
  77007. else {
  77008. setTimeout(function () {
  77009. if (!_this._dataFetched) {
  77010. _this._sphere.dispose();
  77011. }
  77012. }, 0);
  77013. }
  77014. };
  77015. /*** Helpers ***/
  77016. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77017. if (!this._sphere) {
  77018. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77019. this._sphere.isVisible = false;
  77020. }
  77021. };
  77022. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77023. var impostorObject = impostor.object;
  77024. this._prepareSphere();
  77025. this._sphere.position = origin;
  77026. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77027. this._sphere._updateBoundingInfo();
  77028. this._sphere.computeWorldMatrix(true);
  77029. return this._sphere.intersectsMesh(impostorObject, true);
  77030. };
  77031. return PhysicsRadialExplosionEvent;
  77032. }());
  77033. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77034. /***** Gravitational Field *****/
  77035. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77036. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77037. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77038. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77039. this._physicsHelper = physicsHelper;
  77040. this._scene = scene;
  77041. this._origin = origin;
  77042. this._radius = radius;
  77043. this._strength = strength;
  77044. this._falloff = falloff;
  77045. this._tickCallback = this._tick.bind(this);
  77046. }
  77047. /**
  77048. * Returns the data related to the gravitational field event (sphere).
  77049. * @returns {PhysicsGravitationalFieldEventData}
  77050. */
  77051. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77052. this._dataFetched = true;
  77053. return {
  77054. sphere: this._sphere,
  77055. };
  77056. };
  77057. /**
  77058. * Enables the gravitational field.
  77059. */
  77060. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77061. this._tickCallback.call(this);
  77062. this._scene.registerBeforeRender(this._tickCallback);
  77063. };
  77064. /**
  77065. * Disables the gravitational field.
  77066. */
  77067. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77068. this._scene.unregisterBeforeRender(this._tickCallback);
  77069. };
  77070. /**
  77071. * Disposes the sphere.
  77072. * @param {bolean} force
  77073. */
  77074. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77075. var _this = this;
  77076. if (force === void 0) { force = true; }
  77077. if (force) {
  77078. this._sphere.dispose();
  77079. }
  77080. else {
  77081. setTimeout(function () {
  77082. if (!_this._dataFetched) {
  77083. _this._sphere.dispose();
  77084. }
  77085. }, 0);
  77086. }
  77087. };
  77088. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77089. // Since the params won't change, we fetch the event only once
  77090. if (this._sphere) {
  77091. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77092. }
  77093. else {
  77094. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77095. if (radialExplosionEvent) {
  77096. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77097. }
  77098. }
  77099. };
  77100. return PhysicsGravitationalFieldEvent;
  77101. }());
  77102. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77103. /***** Updraft *****/
  77104. var PhysicsUpdraftEvent = /** @class */ (function () {
  77105. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77106. this._scene = _scene;
  77107. this._origin = _origin;
  77108. this._radius = _radius;
  77109. this._strength = _strength;
  77110. this._height = _height;
  77111. this._updraftMode = _updraftMode;
  77112. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77113. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77114. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77115. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77116. this._physicsEngine = this._scene.getPhysicsEngine();
  77117. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77118. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77119. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77120. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77121. }
  77122. this._tickCallback = this._tick.bind(this);
  77123. }
  77124. /**
  77125. * Returns the data related to the updraft event (cylinder).
  77126. * @returns {PhysicsUpdraftEventData}
  77127. */
  77128. PhysicsUpdraftEvent.prototype.getData = function () {
  77129. this._dataFetched = true;
  77130. return {
  77131. cylinder: this._cylinder,
  77132. };
  77133. };
  77134. /**
  77135. * Enables the updraft.
  77136. */
  77137. PhysicsUpdraftEvent.prototype.enable = function () {
  77138. this._tickCallback.call(this);
  77139. this._scene.registerBeforeRender(this._tickCallback);
  77140. };
  77141. /**
  77142. * Disables the cortex.
  77143. */
  77144. PhysicsUpdraftEvent.prototype.disable = function () {
  77145. this._scene.unregisterBeforeRender(this._tickCallback);
  77146. };
  77147. /**
  77148. * Disposes the sphere.
  77149. * @param {bolean} force
  77150. */
  77151. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77152. var _this = this;
  77153. if (force === void 0) { force = true; }
  77154. if (force) {
  77155. this._cylinder.dispose();
  77156. }
  77157. else {
  77158. setTimeout(function () {
  77159. if (!_this._dataFetched) {
  77160. _this._cylinder.dispose();
  77161. }
  77162. }, 0);
  77163. }
  77164. };
  77165. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77166. if (impostor.mass === 0) {
  77167. return null;
  77168. }
  77169. if (!this._intersectsWithCylinder(impostor)) {
  77170. return null;
  77171. }
  77172. var impostorObjectCenter = impostor.getObjectCenter();
  77173. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77174. var direction = this._originDirection;
  77175. }
  77176. else {
  77177. var direction = impostorObjectCenter.subtract(this._originTop);
  77178. }
  77179. var multiplier = this._strength * -1;
  77180. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77181. return { force: force, contactPoint: impostorObjectCenter };
  77182. };
  77183. PhysicsUpdraftEvent.prototype._tick = function () {
  77184. var _this = this;
  77185. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77186. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77187. if (!impostorForceAndContactPoint) {
  77188. return;
  77189. }
  77190. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77191. });
  77192. };
  77193. /*** Helpers ***/
  77194. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77195. if (!this._cylinder) {
  77196. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77197. height: this._height,
  77198. diameter: this._radius * 2,
  77199. }, this._scene);
  77200. this._cylinder.isVisible = false;
  77201. }
  77202. };
  77203. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77204. var impostorObject = impostor.object;
  77205. this._prepareCylinder();
  77206. this._cylinder.position = this._cylinderPosition;
  77207. return this._cylinder.intersectsMesh(impostorObject, true);
  77208. };
  77209. return PhysicsUpdraftEvent;
  77210. }());
  77211. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77212. /***** Vortex *****/
  77213. var PhysicsVortexEvent = /** @class */ (function () {
  77214. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77215. this._scene = _scene;
  77216. this._origin = _origin;
  77217. this._radius = _radius;
  77218. this._strength = _strength;
  77219. this._height = _height;
  77220. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77221. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77222. this._updraftMultiplier = 0.02;
  77223. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77224. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77225. this._physicsEngine = this._scene.getPhysicsEngine();
  77226. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77227. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77228. this._tickCallback = this._tick.bind(this);
  77229. }
  77230. /**
  77231. * Returns the data related to the vortex event (cylinder).
  77232. * @returns {PhysicsVortexEventData}
  77233. */
  77234. PhysicsVortexEvent.prototype.getData = function () {
  77235. this._dataFetched = true;
  77236. return {
  77237. cylinder: this._cylinder,
  77238. };
  77239. };
  77240. /**
  77241. * Enables the vortex.
  77242. */
  77243. PhysicsVortexEvent.prototype.enable = function () {
  77244. this._tickCallback.call(this);
  77245. this._scene.registerBeforeRender(this._tickCallback);
  77246. };
  77247. /**
  77248. * Disables the cortex.
  77249. */
  77250. PhysicsVortexEvent.prototype.disable = function () {
  77251. this._scene.unregisterBeforeRender(this._tickCallback);
  77252. };
  77253. /**
  77254. * Disposes the sphere.
  77255. * @param {bolean} force
  77256. */
  77257. PhysicsVortexEvent.prototype.dispose = function (force) {
  77258. var _this = this;
  77259. if (force === void 0) { force = true; }
  77260. if (force) {
  77261. this._cylinder.dispose();
  77262. }
  77263. else {
  77264. setTimeout(function () {
  77265. if (!_this._dataFetched) {
  77266. _this._cylinder.dispose();
  77267. }
  77268. }, 0);
  77269. }
  77270. };
  77271. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77272. if (impostor.mass === 0) {
  77273. return null;
  77274. }
  77275. if (!this._intersectsWithCylinder(impostor)) {
  77276. return null;
  77277. }
  77278. if (impostor.object.getClassName() !== 'Mesh') {
  77279. return null;
  77280. }
  77281. var impostorObject = impostor.object;
  77282. var impostorObjectCenter = impostor.getObjectCenter();
  77283. 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)
  77284. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77285. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77286. var hit = ray.intersectsMesh(impostorObject);
  77287. var contactPoint = hit.pickedPoint;
  77288. if (!contactPoint) {
  77289. return null;
  77290. }
  77291. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77292. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77293. var directionToOrigin = contactPoint.normalize();
  77294. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77295. directionToOrigin = directionToOrigin.negate();
  77296. }
  77297. // TODO: find a more physically based solution
  77298. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77299. var forceX = directionToOrigin.x * this._strength / 8;
  77300. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77301. var forceZ = directionToOrigin.z * this._strength / 8;
  77302. }
  77303. else {
  77304. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77305. var forceY = this._originTop.y * this._updraftMultiplier;
  77306. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77307. }
  77308. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77309. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77310. return { force: force, contactPoint: impostorObjectCenter };
  77311. };
  77312. PhysicsVortexEvent.prototype._tick = function () {
  77313. var _this = this;
  77314. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77315. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77316. if (!impostorForceAndContactPoint) {
  77317. return;
  77318. }
  77319. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77320. });
  77321. };
  77322. /*** Helpers ***/
  77323. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77324. if (!this._cylinder) {
  77325. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77326. height: this._height,
  77327. diameter: this._radius * 2,
  77328. }, this._scene);
  77329. this._cylinder.isVisible = false;
  77330. }
  77331. };
  77332. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77333. var impostorObject = impostor.object;
  77334. this._prepareCylinder();
  77335. this._cylinder.position = this._cylinderPosition;
  77336. return this._cylinder.intersectsMesh(impostorObject, true);
  77337. };
  77338. return PhysicsVortexEvent;
  77339. }());
  77340. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77341. /***** Enums *****/
  77342. /**
  77343. * The strenght of the force in correspondence to the distance of the affected object
  77344. */
  77345. var PhysicsRadialImpulseFalloff;
  77346. (function (PhysicsRadialImpulseFalloff) {
  77347. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77348. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77349. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77350. /**
  77351. * The strenght of the force in correspondence to the distance of the affected object
  77352. */
  77353. var PhysicsUpdraftMode;
  77354. (function (PhysicsUpdraftMode) {
  77355. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77356. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77357. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77358. })(BABYLON || (BABYLON = {}));
  77359. //# sourceMappingURL=babylon.physicsHelper.js.map
  77360. var BABYLON;
  77361. (function (BABYLON) {
  77362. var CannonJSPlugin = /** @class */ (function () {
  77363. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77364. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77365. if (iterations === void 0) { iterations = 10; }
  77366. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77367. this.name = "CannonJSPlugin";
  77368. this._physicsMaterials = new Array();
  77369. this._fixedTimeStep = 1 / 60;
  77370. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77371. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77372. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77373. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77374. this._tmpPosition = BABYLON.Vector3.Zero();
  77375. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77376. this._tmpUnityRotation = new BABYLON.Quaternion();
  77377. if (!this.isSupported()) {
  77378. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77379. return;
  77380. }
  77381. this._extendNamespace();
  77382. this.world = new this.BJSCANNON.World();
  77383. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77384. this.world.solver.iterations = iterations;
  77385. }
  77386. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77387. this.world.gravity.copy(gravity);
  77388. };
  77389. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77390. this._fixedTimeStep = timeStep;
  77391. };
  77392. CannonJSPlugin.prototype.getTimeStep = function () {
  77393. return this._fixedTimeStep;
  77394. };
  77395. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77396. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77397. };
  77398. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77399. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77400. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77401. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77402. };
  77403. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77404. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77405. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77406. impostor.physicsBody.applyForce(impulse, worldPoint);
  77407. };
  77408. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77409. //parent-child relationship. Does this impostor has a parent impostor?
  77410. if (impostor.parent) {
  77411. if (impostor.physicsBody) {
  77412. this.removePhysicsBody(impostor);
  77413. //TODO is that needed?
  77414. impostor.forceUpdate();
  77415. }
  77416. return;
  77417. }
  77418. //should a new body be created for this impostor?
  77419. if (impostor.isBodyInitRequired()) {
  77420. var shape = this._createShape(impostor);
  77421. //unregister events, if body is being changed
  77422. var oldBody = impostor.physicsBody;
  77423. if (oldBody) {
  77424. this.removePhysicsBody(impostor);
  77425. }
  77426. //create the body and material
  77427. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77428. var bodyCreationObject = {
  77429. mass: impostor.getParam("mass"),
  77430. material: material
  77431. };
  77432. // A simple extend, in case native options were used.
  77433. var nativeOptions = impostor.getParam("nativeOptions");
  77434. for (var key in nativeOptions) {
  77435. if (nativeOptions.hasOwnProperty(key)) {
  77436. bodyCreationObject[key] = nativeOptions[key];
  77437. }
  77438. }
  77439. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77440. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77441. this.world.addEventListener("preStep", impostor.beforeStep);
  77442. this.world.addEventListener("postStep", impostor.afterStep);
  77443. impostor.physicsBody.addShape(shape);
  77444. this.world.add(impostor.physicsBody);
  77445. //try to keep the body moving in the right direction by taking old properties.
  77446. //Should be tested!
  77447. if (oldBody) {
  77448. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77449. impostor.physicsBody[param].copy(oldBody[param]);
  77450. });
  77451. }
  77452. this._processChildMeshes(impostor);
  77453. }
  77454. //now update the body's transformation
  77455. this._updatePhysicsBodyTransformation(impostor);
  77456. };
  77457. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77458. var _this = this;
  77459. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77460. var currentRotation = mainImpostor.object.rotationQuaternion;
  77461. if (meshChildren.length) {
  77462. var processMesh = function (localPosition, mesh) {
  77463. if (!currentRotation || !mesh.rotationQuaternion) {
  77464. return;
  77465. }
  77466. var childImpostor = mesh.getPhysicsImpostor();
  77467. if (childImpostor) {
  77468. var parent = childImpostor.parent;
  77469. if (parent !== mainImpostor) {
  77470. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77471. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77472. if (childImpostor.physicsBody) {
  77473. _this.removePhysicsBody(childImpostor);
  77474. childImpostor.physicsBody = null;
  77475. }
  77476. childImpostor.parent = mainImpostor;
  77477. childImpostor.resetUpdateFlags();
  77478. 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));
  77479. //Add the mass of the children.
  77480. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77481. }
  77482. }
  77483. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77484. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77485. };
  77486. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77487. }
  77488. };
  77489. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77490. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77491. this.world.removeEventListener("preStep", impostor.beforeStep);
  77492. this.world.removeEventListener("postStep", impostor.afterStep);
  77493. this.world.remove(impostor.physicsBody);
  77494. };
  77495. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77496. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77497. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77498. if (!mainBody || !connectedBody) {
  77499. return;
  77500. }
  77501. var constraint;
  77502. var jointData = impostorJoint.joint.jointData;
  77503. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77504. var constraintData = {
  77505. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77506. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77507. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77508. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77509. maxForce: jointData.nativeParams.maxForce,
  77510. collideConnected: !!jointData.collision
  77511. };
  77512. switch (impostorJoint.joint.type) {
  77513. case BABYLON.PhysicsJoint.HingeJoint:
  77514. case BABYLON.PhysicsJoint.Hinge2Joint:
  77515. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77516. break;
  77517. case BABYLON.PhysicsJoint.DistanceJoint:
  77518. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77519. break;
  77520. case BABYLON.PhysicsJoint.SpringJoint:
  77521. var springData = jointData;
  77522. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77523. restLength: springData.length,
  77524. stiffness: springData.stiffness,
  77525. damping: springData.damping,
  77526. localAnchorA: constraintData.pivotA,
  77527. localAnchorB: constraintData.pivotB
  77528. });
  77529. break;
  77530. case BABYLON.PhysicsJoint.LockJoint:
  77531. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77532. break;
  77533. case BABYLON.PhysicsJoint.PointToPointJoint:
  77534. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77535. default:
  77536. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77537. break;
  77538. }
  77539. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77540. constraint.collideConnected = !!jointData.collision;
  77541. impostorJoint.joint.physicsJoint = constraint;
  77542. //don't add spring as constraint, as it is not one.
  77543. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77544. this.world.addConstraint(constraint);
  77545. }
  77546. else {
  77547. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77548. constraint.applyForce();
  77549. });
  77550. }
  77551. };
  77552. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77553. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77554. };
  77555. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77556. var index;
  77557. var mat;
  77558. for (index = 0; index < this._physicsMaterials.length; index++) {
  77559. mat = this._physicsMaterials[index];
  77560. if (mat.friction === friction && mat.restitution === restitution) {
  77561. return mat;
  77562. }
  77563. }
  77564. var currentMat = new this.BJSCANNON.Material(name);
  77565. currentMat.friction = friction;
  77566. currentMat.restitution = restitution;
  77567. this._physicsMaterials.push(currentMat);
  77568. return currentMat;
  77569. };
  77570. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77571. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77572. };
  77573. CannonJSPlugin.prototype._createShape = function (impostor) {
  77574. var object = impostor.object;
  77575. var returnValue;
  77576. var extendSize = impostor.getObjectExtendSize();
  77577. switch (impostor.type) {
  77578. case BABYLON.PhysicsImpostor.SphereImpostor:
  77579. var radiusX = extendSize.x;
  77580. var radiusY = extendSize.y;
  77581. var radiusZ = extendSize.z;
  77582. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77583. break;
  77584. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77585. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77586. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77587. break;
  77588. case BABYLON.PhysicsImpostor.BoxImpostor:
  77589. var box = extendSize.scale(0.5);
  77590. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77591. break;
  77592. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77593. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77594. returnValue = new this.BJSCANNON.Plane();
  77595. break;
  77596. case BABYLON.PhysicsImpostor.MeshImpostor:
  77597. // should transform the vertex data to world coordinates!!
  77598. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77599. var rawFaces = object.getIndices ? object.getIndices() : [];
  77600. if (!rawVerts)
  77601. return;
  77602. // get only scale! so the object could transform correctly.
  77603. var oldPosition = object.position.clone();
  77604. var oldRotation = object.rotation && object.rotation.clone();
  77605. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77606. object.position.copyFromFloats(0, 0, 0);
  77607. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77608. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77609. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77610. var transform = object.computeWorldMatrix(true);
  77611. // convert rawVerts to object space
  77612. var temp = new Array();
  77613. var index;
  77614. for (index = 0; index < rawVerts.length; index += 3) {
  77615. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77616. }
  77617. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77618. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77619. //now set back the transformation!
  77620. object.position.copyFrom(oldPosition);
  77621. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77622. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77623. break;
  77624. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77625. var oldPosition2 = object.position.clone();
  77626. var oldRotation2 = object.rotation && object.rotation.clone();
  77627. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77628. object.position.copyFromFloats(0, 0, 0);
  77629. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77630. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77631. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77632. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77633. returnValue = this._createHeightmap(object);
  77634. object.position.copyFrom(oldPosition2);
  77635. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77636. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77637. object.computeWorldMatrix(true);
  77638. break;
  77639. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77640. returnValue = new this.BJSCANNON.Particle();
  77641. break;
  77642. }
  77643. return returnValue;
  77644. };
  77645. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77646. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77647. var transform = object.computeWorldMatrix(true);
  77648. // convert rawVerts to object space
  77649. var temp = new Array();
  77650. var index;
  77651. for (index = 0; index < pos.length; index += 3) {
  77652. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77653. }
  77654. pos = temp;
  77655. var matrix = new Array();
  77656. //For now pointDepth will not be used and will be automatically calculated.
  77657. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77658. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77659. var boundingInfo = object.getBoundingInfo();
  77660. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77661. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77662. var elementSize = dim * 2 / arraySize;
  77663. for (var i = 0; i < pos.length; i = i + 3) {
  77664. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77665. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77666. var y = -pos[i + 2] + minY;
  77667. if (!matrix[x]) {
  77668. matrix[x] = [];
  77669. }
  77670. if (!matrix[x][z]) {
  77671. matrix[x][z] = y;
  77672. }
  77673. matrix[x][z] = Math.max(y, matrix[x][z]);
  77674. }
  77675. for (var x = 0; x <= arraySize; ++x) {
  77676. if (!matrix[x]) {
  77677. var loc = 1;
  77678. while (!matrix[(x + loc) % arraySize]) {
  77679. loc++;
  77680. }
  77681. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77682. //console.log("missing x", x);
  77683. }
  77684. for (var z = 0; z <= arraySize; ++z) {
  77685. if (!matrix[x][z]) {
  77686. var loc = 1;
  77687. var newValue;
  77688. while (newValue === undefined) {
  77689. newValue = matrix[x][(z + loc++) % arraySize];
  77690. }
  77691. matrix[x][z] = newValue;
  77692. }
  77693. }
  77694. }
  77695. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77696. elementSize: elementSize
  77697. });
  77698. //For future reference, needed for body transformation
  77699. shape.minY = minY;
  77700. return shape;
  77701. };
  77702. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77703. var object = impostor.object;
  77704. //make sure it is updated...
  77705. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77706. // The delta between the mesh position and the mesh bounding box center
  77707. var bInfo = object.getBoundingInfo();
  77708. if (!bInfo)
  77709. return;
  77710. var center = impostor.getObjectCenter();
  77711. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77712. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77713. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77714. this._tmpPosition.copyFrom(center);
  77715. var quaternion = object.rotationQuaternion;
  77716. if (!quaternion) {
  77717. return;
  77718. }
  77719. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77720. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77721. //-90 DEG in X, precalculated
  77722. quaternion = quaternion.multiply(this._minus90X);
  77723. //Invert! (Precalculated, 90 deg in X)
  77724. //No need to clone. this will never change.
  77725. impostor.setDeltaRotation(this._plus90X);
  77726. }
  77727. //If it is a heightfield, if should be centered.
  77728. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77729. var mesh = object;
  77730. var boundingInfo = mesh.getBoundingInfo();
  77731. //calculate the correct body position:
  77732. var rotationQuaternion = mesh.rotationQuaternion;
  77733. mesh.rotationQuaternion = this._tmpUnityRotation;
  77734. mesh.computeWorldMatrix(true);
  77735. //get original center with no rotation
  77736. var c = center.clone();
  77737. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77738. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77739. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77740. mesh.setPreTransformMatrix(p);
  77741. mesh.computeWorldMatrix(true);
  77742. //calculate the translation
  77743. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77744. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77745. //add it inverted to the delta
  77746. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77747. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77748. //rotation is back
  77749. mesh.rotationQuaternion = rotationQuaternion;
  77750. mesh.setPreTransformMatrix(oldPivot);
  77751. mesh.computeWorldMatrix(true);
  77752. }
  77753. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77754. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77755. //this._tmpPosition.copyFrom(object.position);
  77756. }
  77757. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77758. //Now update the impostor object
  77759. impostor.physicsBody.position.copy(this._tmpPosition);
  77760. impostor.physicsBody.quaternion.copy(quaternion);
  77761. };
  77762. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77763. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77764. if (impostor.object.rotationQuaternion) {
  77765. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77766. }
  77767. };
  77768. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77769. impostor.physicsBody.position.copy(newPosition);
  77770. impostor.physicsBody.quaternion.copy(newRotation);
  77771. };
  77772. CannonJSPlugin.prototype.isSupported = function () {
  77773. return this.BJSCANNON !== undefined;
  77774. };
  77775. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77776. impostor.physicsBody.velocity.copy(velocity);
  77777. };
  77778. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77779. impostor.physicsBody.angularVelocity.copy(velocity);
  77780. };
  77781. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77782. var v = impostor.physicsBody.velocity;
  77783. if (!v) {
  77784. return null;
  77785. }
  77786. return new BABYLON.Vector3(v.x, v.y, v.z);
  77787. };
  77788. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77789. var v = impostor.physicsBody.angularVelocity;
  77790. if (!v) {
  77791. return null;
  77792. }
  77793. return new BABYLON.Vector3(v.x, v.y, v.z);
  77794. };
  77795. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77796. impostor.physicsBody.mass = mass;
  77797. impostor.physicsBody.updateMassProperties();
  77798. };
  77799. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77800. return impostor.physicsBody.mass;
  77801. };
  77802. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77803. return impostor.physicsBody.material.friction;
  77804. };
  77805. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77806. impostor.physicsBody.material.friction = friction;
  77807. };
  77808. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77809. return impostor.physicsBody.material.restitution;
  77810. };
  77811. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77812. impostor.physicsBody.material.restitution = restitution;
  77813. };
  77814. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77815. impostor.physicsBody.sleep();
  77816. };
  77817. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77818. impostor.physicsBody.wakeUp();
  77819. };
  77820. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77821. joint.physicsJoint.distance = maxDistance;
  77822. };
  77823. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77824. // if (!motorIndex) {
  77825. // joint.physicsJoint.enableMotor();
  77826. // }
  77827. // }
  77828. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77829. // if (!motorIndex) {
  77830. // joint.physicsJoint.disableMotor();
  77831. // }
  77832. // }
  77833. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77834. if (!motorIndex) {
  77835. joint.physicsJoint.enableMotor();
  77836. joint.physicsJoint.setMotorSpeed(speed);
  77837. if (maxForce) {
  77838. this.setLimit(joint, maxForce);
  77839. }
  77840. }
  77841. };
  77842. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77843. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77844. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77845. };
  77846. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77847. var body = impostor.physicsBody;
  77848. mesh.position.x = body.position.x;
  77849. mesh.position.y = body.position.y;
  77850. mesh.position.z = body.position.z;
  77851. if (mesh.rotationQuaternion) {
  77852. mesh.rotationQuaternion.x = body.quaternion.x;
  77853. mesh.rotationQuaternion.y = body.quaternion.y;
  77854. mesh.rotationQuaternion.z = body.quaternion.z;
  77855. mesh.rotationQuaternion.w = body.quaternion.w;
  77856. }
  77857. };
  77858. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77859. var shape = impostor.physicsBody.shapes[0];
  77860. return shape.boundingSphereRadius;
  77861. };
  77862. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77863. var shape = impostor.physicsBody.shapes[0];
  77864. result.x = shape.halfExtents.x * 2;
  77865. result.y = shape.halfExtents.y * 2;
  77866. result.z = shape.halfExtents.z * 2;
  77867. };
  77868. CannonJSPlugin.prototype.dispose = function () {
  77869. };
  77870. CannonJSPlugin.prototype._extendNamespace = function () {
  77871. //this will force cannon to execute at least one step when using interpolation
  77872. var step_tmp1 = new this.BJSCANNON.Vec3();
  77873. var Engine = this.BJSCANNON;
  77874. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77875. maxSubSteps = maxSubSteps || 10;
  77876. timeSinceLastCalled = timeSinceLastCalled || 0;
  77877. if (timeSinceLastCalled === 0) {
  77878. this.internalStep(dt);
  77879. this.time += dt;
  77880. }
  77881. else {
  77882. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77883. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77884. var t0 = performance.now();
  77885. for (var i = 0; i !== internalSteps; i++) {
  77886. this.internalStep(dt);
  77887. if (performance.now() - t0 > dt * 1000) {
  77888. break;
  77889. }
  77890. }
  77891. this.time += timeSinceLastCalled;
  77892. var h = this.time % dt;
  77893. var h_div_dt = h / dt;
  77894. var interpvelo = step_tmp1;
  77895. var bodies = this.bodies;
  77896. for (var j = 0; j !== bodies.length; j++) {
  77897. var b = bodies[j];
  77898. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77899. b.position.vsub(b.previousPosition, interpvelo);
  77900. interpvelo.scale(h_div_dt, interpvelo);
  77901. b.position.vadd(interpvelo, b.interpolatedPosition);
  77902. }
  77903. else {
  77904. b.interpolatedPosition.copy(b.position);
  77905. b.interpolatedQuaternion.copy(b.quaternion);
  77906. }
  77907. }
  77908. }
  77909. };
  77910. };
  77911. return CannonJSPlugin;
  77912. }());
  77913. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77914. })(BABYLON || (BABYLON = {}));
  77915. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77916. var BABYLON;
  77917. (function (BABYLON) {
  77918. var OimoJSPlugin = /** @class */ (function () {
  77919. function OimoJSPlugin(iterations) {
  77920. this.name = "OimoJSPlugin";
  77921. this._tmpImpostorsArray = [];
  77922. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77923. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77924. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77925. this.world.worldscale(1);
  77926. this.world.clear();
  77927. //making sure no stats are calculated
  77928. this.world.isNoStat = true;
  77929. }
  77930. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77931. this.world.gravity.copy(gravity);
  77932. };
  77933. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77934. this.world.timeStep = timeStep;
  77935. };
  77936. OimoJSPlugin.prototype.getTimeStep = function () {
  77937. return this.world.timeStep;
  77938. };
  77939. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77940. var _this = this;
  77941. impostors.forEach(function (impostor) {
  77942. impostor.beforeStep();
  77943. });
  77944. this.world.step();
  77945. impostors.forEach(function (impostor) {
  77946. impostor.afterStep();
  77947. //update the ordered impostors array
  77948. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77949. });
  77950. //check for collisions
  77951. var contact = this.world.contacts;
  77952. while (contact !== null) {
  77953. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77954. contact = contact.next;
  77955. continue;
  77956. }
  77957. //is this body colliding with any other? get the impostor
  77958. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77959. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77960. if (!mainImpostor || !collidingImpostor) {
  77961. contact = contact.next;
  77962. continue;
  77963. }
  77964. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77965. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77966. contact = contact.next;
  77967. }
  77968. };
  77969. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77970. var mass = impostor.physicsBody.massInfo.mass;
  77971. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77972. };
  77973. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77974. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77975. this.applyImpulse(impostor, force, contactPoint);
  77976. };
  77977. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77978. var _this = this;
  77979. //parent-child relationship. Does this impostor has a parent impostor?
  77980. if (impostor.parent) {
  77981. if (impostor.physicsBody) {
  77982. this.removePhysicsBody(impostor);
  77983. //TODO is that needed?
  77984. impostor.forceUpdate();
  77985. }
  77986. return;
  77987. }
  77988. if (impostor.isBodyInitRequired()) {
  77989. var bodyConfig = {
  77990. name: impostor.uniqueId,
  77991. //Oimo must have mass, also for static objects.
  77992. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77993. size: [],
  77994. type: [],
  77995. pos: [],
  77996. rot: [],
  77997. move: impostor.getParam("mass") !== 0,
  77998. //Supporting older versions of Oimo
  77999. world: this.world
  78000. };
  78001. var impostors = [impostor];
  78002. var addToArray = function (parent) {
  78003. if (!parent.getChildMeshes)
  78004. return;
  78005. parent.getChildMeshes().forEach(function (m) {
  78006. if (m.physicsImpostor) {
  78007. impostors.push(m.physicsImpostor);
  78008. //m.physicsImpostor._init();
  78009. }
  78010. });
  78011. };
  78012. addToArray(impostor.object);
  78013. var checkWithEpsilon_1 = function (value) {
  78014. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78015. };
  78016. impostors.forEach(function (i) {
  78017. if (!impostor.object.rotationQuaternion) {
  78018. return;
  78019. }
  78020. //get the correct bounding box
  78021. var oldQuaternion = i.object.rotationQuaternion;
  78022. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78023. x: impostor.object.rotationQuaternion.x,
  78024. y: impostor.object.rotationQuaternion.y,
  78025. z: impostor.object.rotationQuaternion.z,
  78026. s: impostor.object.rotationQuaternion.w
  78027. });
  78028. var extendSize = i.getObjectExtendSize();
  78029. if (i === impostor) {
  78030. var center = impostor.getObjectCenter();
  78031. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78032. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78033. //Can also use Array.prototype.push.apply
  78034. bodyConfig.pos.push(center.x);
  78035. bodyConfig.pos.push(center.y);
  78036. bodyConfig.pos.push(center.z);
  78037. //tmp solution
  78038. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78039. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78040. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78041. }
  78042. else {
  78043. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78044. bodyConfig.pos.push(localPosition.x);
  78045. bodyConfig.pos.push(localPosition.y);
  78046. bodyConfig.pos.push(localPosition.z);
  78047. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78048. bodyConfig.rot.push(0);
  78049. bodyConfig.rot.push(0);
  78050. bodyConfig.rot.push(0);
  78051. }
  78052. // register mesh
  78053. switch (i.type) {
  78054. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78055. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78056. case BABYLON.PhysicsImpostor.SphereImpostor:
  78057. var radiusX = extendSize.x;
  78058. var radiusY = extendSize.y;
  78059. var radiusZ = extendSize.z;
  78060. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78061. bodyConfig.type.push('sphere');
  78062. //due to the way oimo works with compounds, add 3 times
  78063. bodyConfig.size.push(size);
  78064. bodyConfig.size.push(size);
  78065. bodyConfig.size.push(size);
  78066. break;
  78067. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78068. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78069. var sizeY = checkWithEpsilon_1(extendSize.y);
  78070. bodyConfig.type.push('cylinder');
  78071. bodyConfig.size.push(sizeX);
  78072. bodyConfig.size.push(sizeY);
  78073. //due to the way oimo works with compounds, add one more value.
  78074. bodyConfig.size.push(sizeY);
  78075. break;
  78076. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78077. case BABYLON.PhysicsImpostor.BoxImpostor:
  78078. default:
  78079. var sizeX = checkWithEpsilon_1(extendSize.x);
  78080. var sizeY = checkWithEpsilon_1(extendSize.y);
  78081. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78082. bodyConfig.type.push('box');
  78083. bodyConfig.size.push(sizeX);
  78084. bodyConfig.size.push(sizeY);
  78085. bodyConfig.size.push(sizeZ);
  78086. break;
  78087. }
  78088. //actually not needed, but hey...
  78089. i.object.rotationQuaternion = oldQuaternion;
  78090. });
  78091. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78092. }
  78093. else {
  78094. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78095. }
  78096. impostor.setDeltaPosition(this._tmpPositionVector);
  78097. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78098. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78099. };
  78100. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78101. //impostor.physicsBody.dispose();
  78102. //Same as : (older oimo versions)
  78103. this.world.removeRigidBody(impostor.physicsBody);
  78104. };
  78105. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78106. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78107. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78108. if (!mainBody || !connectedBody) {
  78109. return;
  78110. }
  78111. var jointData = impostorJoint.joint.jointData;
  78112. var options = jointData.nativeParams || {};
  78113. var type;
  78114. var nativeJointData = {
  78115. body1: mainBody,
  78116. body2: connectedBody,
  78117. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78118. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78119. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78120. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78121. min: options.min,
  78122. max: options.max,
  78123. collision: options.collision || jointData.collision,
  78124. spring: options.spring,
  78125. //supporting older version of Oimo
  78126. world: this.world
  78127. };
  78128. switch (impostorJoint.joint.type) {
  78129. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78130. type = "jointBall";
  78131. break;
  78132. case BABYLON.PhysicsJoint.SpringJoint:
  78133. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78134. var springData = jointData;
  78135. nativeJointData.min = springData.length || nativeJointData.min;
  78136. //Max should also be set, just make sure it is at least min
  78137. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78138. case BABYLON.PhysicsJoint.DistanceJoint:
  78139. type = "jointDistance";
  78140. nativeJointData.max = jointData.maxDistance;
  78141. break;
  78142. case BABYLON.PhysicsJoint.PrismaticJoint:
  78143. type = "jointPrisme";
  78144. break;
  78145. case BABYLON.PhysicsJoint.SliderJoint:
  78146. type = "jointSlide";
  78147. break;
  78148. case BABYLON.PhysicsJoint.WheelJoint:
  78149. type = "jointWheel";
  78150. break;
  78151. case BABYLON.PhysicsJoint.HingeJoint:
  78152. default:
  78153. type = "jointHinge";
  78154. break;
  78155. }
  78156. nativeJointData.type = type;
  78157. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78158. };
  78159. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78160. //Bug in Oimo prevents us from disposing a joint in the playground
  78161. //joint.joint.physicsJoint.dispose();
  78162. //So we will bruteforce it!
  78163. try {
  78164. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78165. }
  78166. catch (e) {
  78167. BABYLON.Tools.Warn(e);
  78168. }
  78169. };
  78170. OimoJSPlugin.prototype.isSupported = function () {
  78171. return this.BJSOIMO !== undefined;
  78172. };
  78173. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78174. if (!impostor.physicsBody.sleeping) {
  78175. //TODO check that
  78176. if (impostor.physicsBody.shapes.next) {
  78177. var parentShape = this._getLastShape(impostor.physicsBody);
  78178. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78179. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78180. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78181. }
  78182. else {
  78183. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78184. }
  78185. if (impostor.object.rotationQuaternion) {
  78186. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78187. impostor.object.rotationQuaternion.normalize();
  78188. }
  78189. }
  78190. };
  78191. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78192. var body = impostor.physicsBody;
  78193. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78194. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78195. body.syncShapes();
  78196. body.awake();
  78197. };
  78198. OimoJSPlugin.prototype._getLastShape = function (body) {
  78199. var lastShape = body.shapes;
  78200. while (lastShape.next) {
  78201. lastShape = lastShape.next;
  78202. }
  78203. return lastShape;
  78204. };
  78205. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78206. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78207. };
  78208. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78209. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78210. };
  78211. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78212. var v = impostor.physicsBody.linearVelocity;
  78213. if (!v) {
  78214. return null;
  78215. }
  78216. return new BABYLON.Vector3(v.x, v.y, v.z);
  78217. };
  78218. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78219. var v = impostor.physicsBody.angularVelocity;
  78220. if (!v) {
  78221. return null;
  78222. }
  78223. return new BABYLON.Vector3(v.x, v.y, v.z);
  78224. };
  78225. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78226. var staticBody = mass === 0;
  78227. //this will actually set the body's density and not its mass.
  78228. //But this is how oimo treats the mass variable.
  78229. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78230. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78231. };
  78232. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78233. return impostor.physicsBody.shapes.density;
  78234. };
  78235. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78236. return impostor.physicsBody.shapes.friction;
  78237. };
  78238. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78239. impostor.physicsBody.shapes.friction = friction;
  78240. };
  78241. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78242. return impostor.physicsBody.shapes.restitution;
  78243. };
  78244. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78245. impostor.physicsBody.shapes.restitution = restitution;
  78246. };
  78247. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78248. impostor.physicsBody.sleep();
  78249. };
  78250. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78251. impostor.physicsBody.awake();
  78252. };
  78253. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78254. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78255. if (minDistance !== void 0) {
  78256. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78257. }
  78258. };
  78259. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78260. //TODO separate rotational and transational motors.
  78261. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78262. if (motor) {
  78263. motor.setMotor(speed, maxForce);
  78264. }
  78265. };
  78266. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78267. //TODO separate rotational and transational motors.
  78268. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78269. if (motor) {
  78270. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78271. }
  78272. };
  78273. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78274. var body = impostor.physicsBody;
  78275. mesh.position.x = body.position.x;
  78276. mesh.position.y = body.position.y;
  78277. mesh.position.z = body.position.z;
  78278. if (mesh.rotationQuaternion) {
  78279. mesh.rotationQuaternion.x = body.orientation.x;
  78280. mesh.rotationQuaternion.y = body.orientation.y;
  78281. mesh.rotationQuaternion.z = body.orientation.z;
  78282. mesh.rotationQuaternion.w = body.orientation.s;
  78283. }
  78284. };
  78285. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78286. return impostor.physicsBody.shapes.radius;
  78287. };
  78288. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78289. var shape = impostor.physicsBody.shapes;
  78290. result.x = shape.halfWidth * 2;
  78291. result.y = shape.halfHeight * 2;
  78292. result.z = shape.halfDepth * 2;
  78293. };
  78294. OimoJSPlugin.prototype.dispose = function () {
  78295. this.world.clear();
  78296. };
  78297. return OimoJSPlugin;
  78298. }());
  78299. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78300. })(BABYLON || (BABYLON = {}));
  78301. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78302. var BABYLON;
  78303. (function (BABYLON) {
  78304. /*
  78305. * Based on jsTGALoader - Javascript loader for TGA file
  78306. * By Vincent Thibault
  78307. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78308. */
  78309. var TGATools = /** @class */ (function () {
  78310. function TGATools() {
  78311. }
  78312. TGATools.GetTGAHeader = function (data) {
  78313. var offset = 0;
  78314. var header = {
  78315. id_length: data[offset++],
  78316. colormap_type: data[offset++],
  78317. image_type: data[offset++],
  78318. colormap_index: data[offset++] | data[offset++] << 8,
  78319. colormap_length: data[offset++] | data[offset++] << 8,
  78320. colormap_size: data[offset++],
  78321. origin: [
  78322. data[offset++] | data[offset++] << 8,
  78323. data[offset++] | data[offset++] << 8
  78324. ],
  78325. width: data[offset++] | data[offset++] << 8,
  78326. height: data[offset++] | data[offset++] << 8,
  78327. pixel_size: data[offset++],
  78328. flags: data[offset++]
  78329. };
  78330. return header;
  78331. };
  78332. TGATools.UploadContent = function (gl, data) {
  78333. // Not enough data to contain header ?
  78334. if (data.length < 19) {
  78335. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78336. return;
  78337. }
  78338. // Read Header
  78339. var offset = 18;
  78340. var header = TGATools.GetTGAHeader(data);
  78341. // Assume it's a valid Targa file.
  78342. if (header.id_length + offset > data.length) {
  78343. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78344. return;
  78345. }
  78346. // Skip not needed data
  78347. offset += header.id_length;
  78348. var use_rle = false;
  78349. var use_pal = false;
  78350. var use_grey = false;
  78351. // Get some informations.
  78352. switch (header.image_type) {
  78353. case TGATools._TYPE_RLE_INDEXED:
  78354. use_rle = true;
  78355. case TGATools._TYPE_INDEXED:
  78356. use_pal = true;
  78357. break;
  78358. case TGATools._TYPE_RLE_RGB:
  78359. use_rle = true;
  78360. case TGATools._TYPE_RGB:
  78361. // use_rgb = true;
  78362. break;
  78363. case TGATools._TYPE_RLE_GREY:
  78364. use_rle = true;
  78365. case TGATools._TYPE_GREY:
  78366. use_grey = true;
  78367. break;
  78368. }
  78369. var pixel_data;
  78370. // var numAlphaBits = header.flags & 0xf;
  78371. var pixel_size = header.pixel_size >> 3;
  78372. var pixel_total = header.width * header.height * pixel_size;
  78373. // Read palettes
  78374. var palettes;
  78375. if (use_pal) {
  78376. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78377. }
  78378. // Read LRE
  78379. if (use_rle) {
  78380. pixel_data = new Uint8Array(pixel_total);
  78381. var c, count, i;
  78382. var localOffset = 0;
  78383. var pixels = new Uint8Array(pixel_size);
  78384. while (offset < pixel_total && localOffset < pixel_total) {
  78385. c = data[offset++];
  78386. count = (c & 0x7f) + 1;
  78387. // RLE pixels
  78388. if (c & 0x80) {
  78389. // Bind pixel tmp array
  78390. for (i = 0; i < pixel_size; ++i) {
  78391. pixels[i] = data[offset++];
  78392. }
  78393. // Copy pixel array
  78394. for (i = 0; i < count; ++i) {
  78395. pixel_data.set(pixels, localOffset + i * pixel_size);
  78396. }
  78397. localOffset += pixel_size * count;
  78398. }
  78399. else {
  78400. count *= pixel_size;
  78401. for (i = 0; i < count; ++i) {
  78402. pixel_data[localOffset + i] = data[offset++];
  78403. }
  78404. localOffset += count;
  78405. }
  78406. }
  78407. }
  78408. else {
  78409. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78410. }
  78411. // Load to texture
  78412. var x_start, y_start, x_step, y_step, y_end, x_end;
  78413. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78414. default:
  78415. case TGATools._ORIGIN_UL:
  78416. x_start = 0;
  78417. x_step = 1;
  78418. x_end = header.width;
  78419. y_start = 0;
  78420. y_step = 1;
  78421. y_end = header.height;
  78422. break;
  78423. case TGATools._ORIGIN_BL:
  78424. x_start = 0;
  78425. x_step = 1;
  78426. x_end = header.width;
  78427. y_start = header.height - 1;
  78428. y_step = -1;
  78429. y_end = -1;
  78430. break;
  78431. case TGATools._ORIGIN_UR:
  78432. x_start = header.width - 1;
  78433. x_step = -1;
  78434. x_end = -1;
  78435. y_start = 0;
  78436. y_step = 1;
  78437. y_end = header.height;
  78438. break;
  78439. case TGATools._ORIGIN_BR:
  78440. x_start = header.width - 1;
  78441. x_step = -1;
  78442. x_end = -1;
  78443. y_start = header.height - 1;
  78444. y_step = -1;
  78445. y_end = -1;
  78446. break;
  78447. }
  78448. // Load the specify method
  78449. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78450. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78451. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78452. };
  78453. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78454. var image = pixel_data, colormap = palettes;
  78455. var width = header.width, height = header.height;
  78456. var color, i = 0, x, y;
  78457. var imageData = new Uint8Array(width * height * 4);
  78458. for (y = y_start; y !== y_end; y += y_step) {
  78459. for (x = x_start; x !== x_end; x += x_step, i++) {
  78460. color = image[i];
  78461. imageData[(x + width * y) * 4 + 3] = 255;
  78462. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78463. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78464. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78465. }
  78466. }
  78467. return imageData;
  78468. };
  78469. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78470. var image = pixel_data;
  78471. var width = header.width, height = header.height;
  78472. var color, i = 0, x, y;
  78473. var imageData = new Uint8Array(width * height * 4);
  78474. for (y = y_start; y !== y_end; y += y_step) {
  78475. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78476. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78477. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78478. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78479. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78480. imageData[(x + width * y) * 4 + 0] = r;
  78481. imageData[(x + width * y) * 4 + 1] = g;
  78482. imageData[(x + width * y) * 4 + 2] = b;
  78483. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78484. }
  78485. }
  78486. return imageData;
  78487. };
  78488. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78489. var image = pixel_data;
  78490. var width = header.width, height = header.height;
  78491. var i = 0, x, y;
  78492. var imageData = new Uint8Array(width * height * 4);
  78493. for (y = y_start; y !== y_end; y += y_step) {
  78494. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78495. imageData[(x + width * y) * 4 + 3] = 255;
  78496. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78497. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78498. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78499. }
  78500. }
  78501. return imageData;
  78502. };
  78503. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78504. var image = pixel_data;
  78505. var width = header.width, height = header.height;
  78506. var i = 0, x, y;
  78507. var imageData = new Uint8Array(width * height * 4);
  78508. for (y = y_start; y !== y_end; y += y_step) {
  78509. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78510. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78511. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78512. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78513. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78514. }
  78515. }
  78516. return imageData;
  78517. };
  78518. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78519. var image = pixel_data;
  78520. var width = header.width, height = header.height;
  78521. var color, i = 0, x, y;
  78522. var imageData = new Uint8Array(width * height * 4);
  78523. for (y = y_start; y !== y_end; y += y_step) {
  78524. for (x = x_start; x !== x_end; x += x_step, i++) {
  78525. color = image[i];
  78526. imageData[(x + width * y) * 4 + 0] = color;
  78527. imageData[(x + width * y) * 4 + 1] = color;
  78528. imageData[(x + width * y) * 4 + 2] = color;
  78529. imageData[(x + width * y) * 4 + 3] = 255;
  78530. }
  78531. }
  78532. return imageData;
  78533. };
  78534. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78535. var image = pixel_data;
  78536. var width = header.width, height = header.height;
  78537. var i = 0, x, y;
  78538. var imageData = new Uint8Array(width * height * 4);
  78539. for (y = y_start; y !== y_end; y += y_step) {
  78540. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78541. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78542. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78543. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78544. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78545. }
  78546. }
  78547. return imageData;
  78548. };
  78549. //private static _TYPE_NO_DATA = 0;
  78550. TGATools._TYPE_INDEXED = 1;
  78551. TGATools._TYPE_RGB = 2;
  78552. TGATools._TYPE_GREY = 3;
  78553. TGATools._TYPE_RLE_INDEXED = 9;
  78554. TGATools._TYPE_RLE_RGB = 10;
  78555. TGATools._TYPE_RLE_GREY = 11;
  78556. TGATools._ORIGIN_MASK = 0x30;
  78557. TGATools._ORIGIN_SHIFT = 0x04;
  78558. TGATools._ORIGIN_BL = 0x00;
  78559. TGATools._ORIGIN_BR = 0x01;
  78560. TGATools._ORIGIN_UL = 0x02;
  78561. TGATools._ORIGIN_UR = 0x03;
  78562. return TGATools;
  78563. }());
  78564. BABYLON.TGATools = TGATools;
  78565. })(BABYLON || (BABYLON = {}));
  78566. //# sourceMappingURL=babylon.tga.js.map
  78567. var BABYLON;
  78568. (function (BABYLON) {
  78569. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78570. // All values and structures referenced from:
  78571. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78572. var DDS_MAGIC = 0x20534444;
  78573. var
  78574. //DDSD_CAPS = 0x1,
  78575. //DDSD_HEIGHT = 0x2,
  78576. //DDSD_WIDTH = 0x4,
  78577. //DDSD_PITCH = 0x8,
  78578. //DDSD_PIXELFORMAT = 0x1000,
  78579. DDSD_MIPMAPCOUNT = 0x20000;
  78580. //DDSD_LINEARSIZE = 0x80000,
  78581. //DDSD_DEPTH = 0x800000;
  78582. // var DDSCAPS_COMPLEX = 0x8,
  78583. // DDSCAPS_MIPMAP = 0x400000,
  78584. // DDSCAPS_TEXTURE = 0x1000;
  78585. var DDSCAPS2_CUBEMAP = 0x200;
  78586. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78587. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78588. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78589. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78590. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78591. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78592. // DDSCAPS2_VOLUME = 0x200000;
  78593. var
  78594. //DDPF_ALPHAPIXELS = 0x1,
  78595. //DDPF_ALPHA = 0x2,
  78596. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78597. //DDPF_YUV = 0x200,
  78598. DDPF_LUMINANCE = 0x20000;
  78599. function FourCCToInt32(value) {
  78600. return value.charCodeAt(0) +
  78601. (value.charCodeAt(1) << 8) +
  78602. (value.charCodeAt(2) << 16) +
  78603. (value.charCodeAt(3) << 24);
  78604. }
  78605. function Int32ToFourCC(value) {
  78606. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78607. }
  78608. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78609. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78610. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78611. var FOURCC_DX10 = FourCCToInt32("DX10");
  78612. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78613. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78614. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78615. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78616. var headerLengthInt = 31; // The header length in 32 bit ints
  78617. // Offsets into the header array
  78618. var off_magic = 0;
  78619. var off_size = 1;
  78620. var off_flags = 2;
  78621. var off_height = 3;
  78622. var off_width = 4;
  78623. var off_mipmapCount = 7;
  78624. var off_pfFlags = 20;
  78625. var off_pfFourCC = 21;
  78626. var off_RGBbpp = 22;
  78627. var off_RMask = 23;
  78628. var off_GMask = 24;
  78629. var off_BMask = 25;
  78630. var off_AMask = 26;
  78631. // var off_caps1 = 27;
  78632. var off_caps2 = 28;
  78633. // var off_caps3 = 29;
  78634. // var off_caps4 = 30;
  78635. var off_dxgiFormat = 32;
  78636. ;
  78637. var DDSTools = /** @class */ (function () {
  78638. function DDSTools() {
  78639. }
  78640. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78641. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78642. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78643. var mipmapCount = 1;
  78644. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78645. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78646. }
  78647. var fourCC = header[off_pfFourCC];
  78648. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78649. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78650. switch (fourCC) {
  78651. case FOURCC_D3DFMT_R16G16B16A16F:
  78652. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78653. break;
  78654. case FOURCC_D3DFMT_R32G32B32A32F:
  78655. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78656. break;
  78657. case FOURCC_DX10:
  78658. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78659. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78660. break;
  78661. }
  78662. }
  78663. return {
  78664. width: header[off_width],
  78665. height: header[off_height],
  78666. mipmapCount: mipmapCount,
  78667. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78668. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78669. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78670. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78671. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78672. dxgiFormat: dxgiFormat,
  78673. textureType: textureType
  78674. };
  78675. };
  78676. DDSTools._ToHalfFloat = function (value) {
  78677. if (!DDSTools._FloatView) {
  78678. DDSTools._FloatView = new Float32Array(1);
  78679. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78680. }
  78681. DDSTools._FloatView[0] = value;
  78682. var x = DDSTools._Int32View[0];
  78683. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78684. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78685. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78686. /* If zero, or denormal, or exponent underflows too much for a denormal
  78687. * half, return signed zero. */
  78688. if (e < 103) {
  78689. return bits;
  78690. }
  78691. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78692. if (e > 142) {
  78693. bits |= 0x7c00;
  78694. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78695. * not Inf, so make sure we set one mantissa bit too. */
  78696. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78697. return bits;
  78698. }
  78699. /* If exponent underflows but not too much, return a denormal */
  78700. if (e < 113) {
  78701. m |= 0x0800;
  78702. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78703. * to 1, which is OK. */
  78704. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78705. return bits;
  78706. }
  78707. bits |= ((e - 112) << 10) | (m >> 1);
  78708. bits += m & 1;
  78709. return bits;
  78710. };
  78711. DDSTools._FromHalfFloat = function (value) {
  78712. var s = (value & 0x8000) >> 15;
  78713. var e = (value & 0x7C00) >> 10;
  78714. var f = value & 0x03FF;
  78715. if (e === 0) {
  78716. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78717. }
  78718. else if (e == 0x1F) {
  78719. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78720. }
  78721. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78722. };
  78723. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78724. var destArray = new Float32Array(dataLength);
  78725. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78726. var index = 0;
  78727. for (var y = 0; y < height; y++) {
  78728. for (var x = 0; x < width; x++) {
  78729. var srcPos = (x + y * width) * 4;
  78730. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78731. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78732. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78733. if (DDSTools.StoreLODInAlphaChannel) {
  78734. destArray[index + 3] = lod;
  78735. }
  78736. else {
  78737. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78738. }
  78739. index += 4;
  78740. }
  78741. }
  78742. return destArray;
  78743. };
  78744. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78745. if (DDSTools.StoreLODInAlphaChannel) {
  78746. var destArray = new Uint16Array(dataLength);
  78747. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78748. var index = 0;
  78749. for (var y = 0; y < height; y++) {
  78750. for (var x = 0; x < width; x++) {
  78751. var srcPos = (x + y * width) * 4;
  78752. destArray[index] = srcData[srcPos];
  78753. destArray[index + 1] = srcData[srcPos + 1];
  78754. destArray[index + 2] = srcData[srcPos + 2];
  78755. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78756. index += 4;
  78757. }
  78758. }
  78759. return destArray;
  78760. }
  78761. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78762. };
  78763. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78764. if (DDSTools.StoreLODInAlphaChannel) {
  78765. var destArray = new Float32Array(dataLength);
  78766. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78767. var index = 0;
  78768. for (var y = 0; y < height; y++) {
  78769. for (var x = 0; x < width; x++) {
  78770. var srcPos = (x + y * width) * 4;
  78771. destArray[index] = srcData[srcPos];
  78772. destArray[index + 1] = srcData[srcPos + 1];
  78773. destArray[index + 2] = srcData[srcPos + 2];
  78774. destArray[index + 3] = lod;
  78775. index += 4;
  78776. }
  78777. }
  78778. return destArray;
  78779. }
  78780. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78781. };
  78782. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78783. var destArray = new Uint8Array(dataLength);
  78784. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78785. var index = 0;
  78786. for (var y = 0; y < height; y++) {
  78787. for (var x = 0; x < width; x++) {
  78788. var srcPos = (x + y * width) * 4;
  78789. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78790. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78791. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78792. if (DDSTools.StoreLODInAlphaChannel) {
  78793. destArray[index + 3] = lod;
  78794. }
  78795. else {
  78796. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78797. }
  78798. index += 4;
  78799. }
  78800. }
  78801. return destArray;
  78802. };
  78803. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78804. var destArray = new Uint8Array(dataLength);
  78805. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78806. var index = 0;
  78807. for (var y = 0; y < height; y++) {
  78808. for (var x = 0; x < width; x++) {
  78809. var srcPos = (x + y * width) * 4;
  78810. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78811. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78812. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78813. if (DDSTools.StoreLODInAlphaChannel) {
  78814. destArray[index + 3] = lod;
  78815. }
  78816. else {
  78817. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78818. }
  78819. index += 4;
  78820. }
  78821. }
  78822. return destArray;
  78823. };
  78824. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78825. var byteArray = new Uint8Array(dataLength);
  78826. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78827. var index = 0;
  78828. for (var y = 0; y < height; y++) {
  78829. for (var x = 0; x < width; x++) {
  78830. var srcPos = (x + y * width) * 4;
  78831. byteArray[index] = srcData[srcPos + rOffset];
  78832. byteArray[index + 1] = srcData[srcPos + gOffset];
  78833. byteArray[index + 2] = srcData[srcPos + bOffset];
  78834. byteArray[index + 3] = srcData[srcPos + aOffset];
  78835. index += 4;
  78836. }
  78837. }
  78838. return byteArray;
  78839. };
  78840. DDSTools._ExtractLongWordOrder = function (value) {
  78841. if (value === 0 || value === 255 || value === -16777216) {
  78842. return 0;
  78843. }
  78844. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78845. };
  78846. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78847. var byteArray = new Uint8Array(dataLength);
  78848. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78849. var index = 0;
  78850. for (var y = 0; y < height; y++) {
  78851. for (var x = 0; x < width; x++) {
  78852. var srcPos = (x + y * width) * 3;
  78853. byteArray[index] = srcData[srcPos + rOffset];
  78854. byteArray[index + 1] = srcData[srcPos + gOffset];
  78855. byteArray[index + 2] = srcData[srcPos + bOffset];
  78856. index += 3;
  78857. }
  78858. }
  78859. return byteArray;
  78860. };
  78861. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78862. var byteArray = new Uint8Array(dataLength);
  78863. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78864. var index = 0;
  78865. for (var y = 0; y < height; y++) {
  78866. for (var x = 0; x < width; x++) {
  78867. var srcPos = (x + y * width);
  78868. byteArray[index] = srcData[srcPos];
  78869. index++;
  78870. }
  78871. }
  78872. return byteArray;
  78873. };
  78874. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78875. if (lodIndex === void 0) { lodIndex = -1; }
  78876. var ext = engine.getCaps().s3tc;
  78877. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78878. var fourCC, width, height, dataLength = 0, dataOffset;
  78879. var byteArray, mipmapCount, mip;
  78880. var internalFormat = 0;
  78881. var format = 0;
  78882. var blockBytes = 1;
  78883. if (header[off_magic] !== DDS_MAGIC) {
  78884. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78885. return;
  78886. }
  78887. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78888. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78889. return;
  78890. }
  78891. if (info.isCompressed && !ext) {
  78892. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78893. return;
  78894. }
  78895. var bpp = header[off_RGBbpp];
  78896. dataOffset = header[off_size] + 4;
  78897. var computeFormats = false;
  78898. if (info.isFourCC) {
  78899. fourCC = header[off_pfFourCC];
  78900. switch (fourCC) {
  78901. case FOURCC_DXT1:
  78902. blockBytes = 8;
  78903. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78904. break;
  78905. case FOURCC_DXT3:
  78906. blockBytes = 16;
  78907. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78908. break;
  78909. case FOURCC_DXT5:
  78910. blockBytes = 16;
  78911. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78912. break;
  78913. case FOURCC_D3DFMT_R16G16B16A16F:
  78914. computeFormats = true;
  78915. break;
  78916. case FOURCC_D3DFMT_R32G32B32A32F:
  78917. computeFormats = true;
  78918. break;
  78919. case FOURCC_DX10:
  78920. // There is an additionnal header so dataOffset need to be changed
  78921. dataOffset += 5 * 4; // 5 uints
  78922. var supported = false;
  78923. switch (info.dxgiFormat) {
  78924. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78925. computeFormats = true;
  78926. supported = true;
  78927. break;
  78928. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78929. info.isRGB = true;
  78930. info.isFourCC = false;
  78931. bpp = 32;
  78932. supported = true;
  78933. break;
  78934. }
  78935. if (supported) {
  78936. break;
  78937. }
  78938. default:
  78939. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78940. return;
  78941. }
  78942. }
  78943. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78944. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78945. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78946. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78947. if (computeFormats) {
  78948. format = engine._getWebGLTextureType(info.textureType);
  78949. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78950. }
  78951. mipmapCount = 1;
  78952. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78953. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78954. }
  78955. for (var face = 0; face < faces; face++) {
  78956. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78957. width = header[off_width];
  78958. height = header[off_height];
  78959. for (mip = 0; mip < mipmapCount; ++mip) {
  78960. if (lodIndex === -1 || lodIndex === mip) {
  78961. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78962. var i = (lodIndex === -1) ? mip : 0;
  78963. if (!info.isCompressed && info.isFourCC) {
  78964. dataLength = width * height * 4;
  78965. var floatArray = null;
  78966. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78967. if (bpp === 128) {
  78968. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78969. }
  78970. else if (bpp === 64) {
  78971. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78972. }
  78973. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78974. format = engine._getWebGLTextureType(info.textureType);
  78975. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78976. }
  78977. else {
  78978. if (bpp === 128) {
  78979. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78980. }
  78981. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78982. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78983. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78984. format = engine._getWebGLTextureType(info.textureType);
  78985. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78986. }
  78987. else {
  78988. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78989. }
  78990. }
  78991. if (floatArray) {
  78992. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78993. }
  78994. }
  78995. else if (info.isRGB) {
  78996. if (bpp === 24) {
  78997. dataLength = width * height * 3;
  78998. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78999. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79000. }
  79001. else {
  79002. dataLength = width * height * 4;
  79003. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79004. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79005. }
  79006. }
  79007. else if (info.isLuminance) {
  79008. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79009. var unpaddedRowSize = width;
  79010. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79011. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79012. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79013. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79014. }
  79015. else {
  79016. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79017. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79018. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79019. }
  79020. }
  79021. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79022. width *= 0.5;
  79023. height *= 0.5;
  79024. width = Math.max(1.0, width);
  79025. height = Math.max(1.0, height);
  79026. }
  79027. if (currentFace !== undefined) {
  79028. // Loading a single face
  79029. break;
  79030. }
  79031. }
  79032. };
  79033. DDSTools.StoreLODInAlphaChannel = false;
  79034. return DDSTools;
  79035. }());
  79036. BABYLON.DDSTools = DDSTools;
  79037. })(BABYLON || (BABYLON = {}));
  79038. //# sourceMappingURL=babylon.dds.js.map
  79039. var BABYLON;
  79040. (function (BABYLON) {
  79041. /**
  79042. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79043. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79044. */
  79045. var KhronosTextureContainer = /** @class */ (function () {
  79046. /**
  79047. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79048. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79049. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79050. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79051. */
  79052. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79053. this.arrayBuffer = arrayBuffer;
  79054. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79055. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79056. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79057. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79058. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79059. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79060. BABYLON.Tools.Error("texture missing KTX identifier");
  79061. return;
  79062. }
  79063. // load the reset of the header in native 32 bit int
  79064. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79065. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79066. var oppositeEndianess = header[0] === 0x01020304;
  79067. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79068. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79069. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79070. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79071. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79072. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79073. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79074. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79075. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79076. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79077. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79078. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79079. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79080. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79081. if (this.glType !== 0) {
  79082. BABYLON.Tools.Error("only compressed formats currently supported");
  79083. return;
  79084. }
  79085. else {
  79086. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79087. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79088. }
  79089. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79090. BABYLON.Tools.Error("only 2D textures currently supported");
  79091. return;
  79092. }
  79093. if (this.numberOfArrayElements !== 0) {
  79094. BABYLON.Tools.Error("texture arrays not currently supported");
  79095. return;
  79096. }
  79097. if (this.numberOfFaces !== facesExpected) {
  79098. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79099. return;
  79100. }
  79101. // we now have a completely validated file, so could use existence of loadType as success
  79102. // would need to make this more elaborate & adjust checks above to support more than one load type
  79103. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79104. }
  79105. // not as fast hardware based, but will probably never need to use
  79106. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79107. return ((val & 0xFF) << 24)
  79108. | ((val & 0xFF00) << 8)
  79109. | ((val >> 8) & 0xFF00)
  79110. | ((val >> 24) & 0xFF);
  79111. };
  79112. /**
  79113. * It is assumed that the texture has already been created & is currently bound
  79114. */
  79115. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79116. switch (this.loadType) {
  79117. case KhronosTextureContainer.COMPRESSED_2D:
  79118. this._upload2DCompressedLevels(gl, loadMipmaps);
  79119. break;
  79120. case KhronosTextureContainer.TEX_2D:
  79121. case KhronosTextureContainer.COMPRESSED_3D:
  79122. case KhronosTextureContainer.TEX_3D:
  79123. }
  79124. };
  79125. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79126. // initialize width & height for level 1
  79127. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79128. var width = this.pixelWidth;
  79129. var height = this.pixelHeight;
  79130. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79131. for (var level = 0; level < mipmapCount; level++) {
  79132. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79133. for (var face = 0; face < this.numberOfFaces; face++) {
  79134. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79135. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79136. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79137. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79138. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79139. }
  79140. width = Math.max(1.0, width * 0.5);
  79141. height = Math.max(1.0, height * 0.5);
  79142. }
  79143. };
  79144. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79145. // load types
  79146. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79147. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79148. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79149. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79150. return KhronosTextureContainer;
  79151. }());
  79152. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79153. })(BABYLON || (BABYLON = {}));
  79154. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79155. var BABYLON;
  79156. (function (BABYLON) {
  79157. var Debug = /** @class */ (function () {
  79158. function Debug() {
  79159. }
  79160. Debug.AxesViewer = /** @class */ (function () {
  79161. function AxesViewer(scene, scaleLines) {
  79162. if (scaleLines === void 0) { scaleLines = 1; }
  79163. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79164. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79165. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79166. this.scaleLines = 1;
  79167. this.scaleLines = scaleLines;
  79168. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79169. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79170. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79171. this._xmesh.renderingGroupId = 2;
  79172. this._ymesh.renderingGroupId = 2;
  79173. this._zmesh.renderingGroupId = 2;
  79174. this._xmesh.material.checkReadyOnlyOnce = true;
  79175. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79176. this._ymesh.material.checkReadyOnlyOnce = true;
  79177. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79178. this._zmesh.material.checkReadyOnlyOnce = true;
  79179. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79180. this.scene = scene;
  79181. }
  79182. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79183. var scaleLines = this.scaleLines;
  79184. if (this._xmesh) {
  79185. this._xmesh.position.copyFrom(position);
  79186. }
  79187. if (this._ymesh) {
  79188. this._ymesh.position.copyFrom(position);
  79189. }
  79190. if (this._zmesh) {
  79191. this._zmesh.position.copyFrom(position);
  79192. }
  79193. var point2 = this._xline[1];
  79194. point2.x = xaxis.x * scaleLines;
  79195. point2.y = xaxis.y * scaleLines;
  79196. point2.z = xaxis.z * scaleLines;
  79197. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79198. point2 = this._yline[1];
  79199. point2.x = yaxis.x * scaleLines;
  79200. point2.y = yaxis.y * scaleLines;
  79201. point2.z = yaxis.z * scaleLines;
  79202. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79203. point2 = this._zline[1];
  79204. point2.x = zaxis.x * scaleLines;
  79205. point2.y = zaxis.y * scaleLines;
  79206. point2.z = zaxis.z * scaleLines;
  79207. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79208. };
  79209. AxesViewer.prototype.dispose = function () {
  79210. if (this._xmesh) {
  79211. this._xmesh.dispose();
  79212. }
  79213. if (this._ymesh) {
  79214. this._ymesh.dispose();
  79215. }
  79216. if (this._zmesh) {
  79217. this._zmesh.dispose();
  79218. }
  79219. this._xmesh = null;
  79220. this._ymesh = null;
  79221. this._zmesh = null;
  79222. this.scene = null;
  79223. };
  79224. return AxesViewer;
  79225. }());
  79226. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79227. __extends(BoneAxesViewer, _super);
  79228. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79229. if (scaleLines === void 0) { scaleLines = 1; }
  79230. var _this = _super.call(this, scene, scaleLines) || this;
  79231. _this.pos = BABYLON.Vector3.Zero();
  79232. _this.xaxis = BABYLON.Vector3.Zero();
  79233. _this.yaxis = BABYLON.Vector3.Zero();
  79234. _this.zaxis = BABYLON.Vector3.Zero();
  79235. _this.mesh = mesh;
  79236. _this.bone = bone;
  79237. return _this;
  79238. }
  79239. BoneAxesViewer.prototype.update = function () {
  79240. if (!this.mesh || !this.bone) {
  79241. return;
  79242. }
  79243. var bone = this.bone;
  79244. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79245. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79246. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79247. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79248. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79249. };
  79250. BoneAxesViewer.prototype.dispose = function () {
  79251. if (this.mesh) {
  79252. this.mesh = null;
  79253. this.bone = null;
  79254. _super.prototype.dispose.call(this);
  79255. }
  79256. };
  79257. return BoneAxesViewer;
  79258. }(Debug.AxesViewer));
  79259. Debug.PhysicsViewer = /** @class */ (function () {
  79260. function PhysicsViewer(scene) {
  79261. this._impostors = [];
  79262. this._meshes = [];
  79263. this._numMeshes = 0;
  79264. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79265. var physicEngine = this._scene.getPhysicsEngine();
  79266. if (physicEngine) {
  79267. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79268. }
  79269. }
  79270. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79271. var plugin = this._physicsEnginePlugin;
  79272. for (var i = 0; i < this._numMeshes; i++) {
  79273. var impostor = this._impostors[i];
  79274. if (!impostor) {
  79275. continue;
  79276. }
  79277. if (impostor.isDisposed) {
  79278. this.hideImpostor(this._impostors[i--]);
  79279. }
  79280. else {
  79281. var mesh = this._meshes[i];
  79282. if (mesh && plugin) {
  79283. plugin.syncMeshWithImpostor(mesh, impostor);
  79284. }
  79285. }
  79286. }
  79287. };
  79288. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79289. if (!this._scene) {
  79290. return;
  79291. }
  79292. for (var i = 0; i < this._numMeshes; i++) {
  79293. if (this._impostors[i] == impostor) {
  79294. return;
  79295. }
  79296. }
  79297. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79298. if (debugMesh) {
  79299. this._impostors[this._numMeshes] = impostor;
  79300. this._meshes[this._numMeshes] = debugMesh;
  79301. if (this._numMeshes === 0) {
  79302. this._renderFunction = this._updateDebugMeshes.bind(this);
  79303. this._scene.registerBeforeRender(this._renderFunction);
  79304. }
  79305. this._numMeshes++;
  79306. }
  79307. };
  79308. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79309. if (!impostor || !this._scene) {
  79310. return;
  79311. }
  79312. var removed = false;
  79313. for (var i = 0; i < this._numMeshes; i++) {
  79314. if (this._impostors[i] == impostor) {
  79315. var mesh = this._meshes[i];
  79316. if (!mesh) {
  79317. continue;
  79318. }
  79319. this._scene.removeMesh(mesh);
  79320. mesh.dispose();
  79321. this._numMeshes--;
  79322. if (this._numMeshes > 0) {
  79323. this._meshes[i] = this._meshes[this._numMeshes];
  79324. this._impostors[i] = this._impostors[this._numMeshes];
  79325. this._meshes[this._numMeshes] = null;
  79326. this._impostors[this._numMeshes] = null;
  79327. }
  79328. else {
  79329. this._meshes[0] = null;
  79330. this._impostors[0] = null;
  79331. }
  79332. removed = true;
  79333. break;
  79334. }
  79335. }
  79336. if (removed && this._numMeshes === 0) {
  79337. this._scene.unregisterBeforeRender(this._renderFunction);
  79338. }
  79339. };
  79340. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79341. if (!this._debugMaterial) {
  79342. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79343. this._debugMaterial.wireframe = true;
  79344. }
  79345. return this._debugMaterial;
  79346. };
  79347. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79348. if (!this._debugBoxMesh) {
  79349. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79350. this._debugBoxMesh.renderingGroupId = 1;
  79351. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79352. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79353. scene.removeMesh(this._debugBoxMesh);
  79354. }
  79355. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79356. };
  79357. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79358. if (!this._debugSphereMesh) {
  79359. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79360. this._debugSphereMesh.renderingGroupId = 1;
  79361. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79362. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79363. scene.removeMesh(this._debugSphereMesh);
  79364. }
  79365. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79366. };
  79367. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79368. var mesh = null;
  79369. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79370. mesh = this._getDebugBoxMesh(scene);
  79371. impostor.getBoxSizeToRef(mesh.scaling);
  79372. }
  79373. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79374. mesh = this._getDebugSphereMesh(scene);
  79375. var radius = impostor.getRadius();
  79376. mesh.scaling.x = radius * 2;
  79377. mesh.scaling.y = radius * 2;
  79378. mesh.scaling.z = radius * 2;
  79379. }
  79380. return mesh;
  79381. };
  79382. PhysicsViewer.prototype.dispose = function () {
  79383. for (var i = 0; i < this._numMeshes; i++) {
  79384. this.hideImpostor(this._impostors[i]);
  79385. }
  79386. if (this._debugBoxMesh) {
  79387. this._debugBoxMesh.dispose();
  79388. }
  79389. if (this._debugSphereMesh) {
  79390. this._debugSphereMesh.dispose();
  79391. }
  79392. if (this._debugMaterial) {
  79393. this._debugMaterial.dispose();
  79394. }
  79395. this._impostors.length = 0;
  79396. this._scene = null;
  79397. this._physicsEnginePlugin = null;
  79398. };
  79399. return PhysicsViewer;
  79400. }());
  79401. Debug.SkeletonViewer = /** @class */ (function () {
  79402. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79403. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79404. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79405. this.skeleton = skeleton;
  79406. this.mesh = mesh;
  79407. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79408. this.renderingGroupId = renderingGroupId;
  79409. this.color = BABYLON.Color3.White();
  79410. this._debugLines = new Array();
  79411. this._isEnabled = false;
  79412. this._scene = scene;
  79413. this.update();
  79414. this._renderFunction = this.update.bind(this);
  79415. }
  79416. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79417. get: function () {
  79418. return this._isEnabled;
  79419. },
  79420. set: function (value) {
  79421. if (this._isEnabled === value) {
  79422. return;
  79423. }
  79424. this._isEnabled = value;
  79425. if (value) {
  79426. this._scene.registerBeforeRender(this._renderFunction);
  79427. }
  79428. else {
  79429. this._scene.unregisterBeforeRender(this._renderFunction);
  79430. }
  79431. },
  79432. enumerable: true,
  79433. configurable: true
  79434. });
  79435. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79436. if (x === void 0) { x = 0; }
  79437. if (y === void 0) { y = 0; }
  79438. if (z === void 0) { z = 0; }
  79439. var tmat = BABYLON.Tmp.Matrix[0];
  79440. var parentBone = bone.getParent();
  79441. tmat.copyFrom(bone.getLocalMatrix());
  79442. if (x !== 0 || y !== 0 || z !== 0) {
  79443. var tmat2 = BABYLON.Tmp.Matrix[1];
  79444. BABYLON.Matrix.IdentityToRef(tmat2);
  79445. tmat2.m[12] = x;
  79446. tmat2.m[13] = y;
  79447. tmat2.m[14] = z;
  79448. tmat2.multiplyToRef(tmat, tmat);
  79449. }
  79450. if (parentBone) {
  79451. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79452. }
  79453. tmat.multiplyToRef(meshMat, tmat);
  79454. position.x = tmat.m[12];
  79455. position.y = tmat.m[13];
  79456. position.z = tmat.m[14];
  79457. };
  79458. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79459. var len = bones.length;
  79460. var meshPos = this.mesh.position;
  79461. for (var i = 0; i < len; i++) {
  79462. var bone = bones[i];
  79463. var points = this._debugLines[i];
  79464. if (!points) {
  79465. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79466. this._debugLines[i] = points;
  79467. }
  79468. this._getBonePosition(points[0], bone, meshMat);
  79469. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79470. points[0].subtractInPlace(meshPos);
  79471. points[1].subtractInPlace(meshPos);
  79472. }
  79473. };
  79474. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79475. var len = bones.length;
  79476. var boneNum = 0;
  79477. var meshPos = this.mesh.position;
  79478. for (var i = len - 1; i >= 0; i--) {
  79479. var childBone = bones[i];
  79480. var parentBone = childBone.getParent();
  79481. if (!parentBone) {
  79482. continue;
  79483. }
  79484. var points = this._debugLines[boneNum];
  79485. if (!points) {
  79486. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79487. this._debugLines[boneNum] = points;
  79488. }
  79489. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79490. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79491. points[0].subtractInPlace(meshPos);
  79492. points[1].subtractInPlace(meshPos);
  79493. boneNum++;
  79494. }
  79495. };
  79496. SkeletonViewer.prototype.update = function () {
  79497. if (this.autoUpdateBonesMatrices) {
  79498. this.skeleton.computeAbsoluteTransforms();
  79499. }
  79500. if (this.skeleton.bones[0].length === undefined) {
  79501. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79502. }
  79503. else {
  79504. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79505. }
  79506. if (!this._debugMesh) {
  79507. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79508. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79509. }
  79510. else {
  79511. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79512. }
  79513. this._debugMesh.position.copyFrom(this.mesh.position);
  79514. this._debugMesh.color = this.color;
  79515. };
  79516. SkeletonViewer.prototype.dispose = function () {
  79517. if (this._debugMesh) {
  79518. this.isEnabled = false;
  79519. this._debugMesh.dispose();
  79520. this._debugMesh = null;
  79521. }
  79522. };
  79523. return SkeletonViewer;
  79524. }());
  79525. return Debug;
  79526. }());
  79527. BABYLON.Debug = Debug;
  79528. })(BABYLON || (BABYLON = {}));
  79529. //# sourceMappingURL=babylon.debugModules.js.map
  79530. var BABYLON;
  79531. (function (BABYLON) {
  79532. var RayHelper = /** @class */ (function () {
  79533. function RayHelper(ray) {
  79534. this.ray = ray;
  79535. }
  79536. RayHelper.CreateAndShow = function (ray, scene, color) {
  79537. var helper = new RayHelper(ray);
  79538. helper.show(scene, color);
  79539. return helper;
  79540. };
  79541. RayHelper.prototype.show = function (scene, color) {
  79542. if (!this._renderFunction && this.ray) {
  79543. var ray = this.ray;
  79544. this._renderFunction = this._render.bind(this);
  79545. this._scene = scene;
  79546. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79547. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79548. if (this._renderFunction) {
  79549. this._scene.registerBeforeRender(this._renderFunction);
  79550. }
  79551. }
  79552. if (color && this._renderLine) {
  79553. this._renderLine.color.copyFrom(color);
  79554. }
  79555. };
  79556. RayHelper.prototype.hide = function () {
  79557. if (this._renderFunction && this._scene) {
  79558. this._scene.unregisterBeforeRender(this._renderFunction);
  79559. this._scene = null;
  79560. this._renderFunction = null;
  79561. if (this._renderLine) {
  79562. this._renderLine.dispose();
  79563. this._renderLine = null;
  79564. }
  79565. this._renderPoints = [];
  79566. }
  79567. };
  79568. RayHelper.prototype._render = function () {
  79569. var ray = this.ray;
  79570. if (!ray) {
  79571. return;
  79572. }
  79573. var point = this._renderPoints[1];
  79574. var len = Math.min(ray.length, 1000000);
  79575. point.copyFrom(ray.direction);
  79576. point.scaleInPlace(len);
  79577. point.addInPlace(ray.origin);
  79578. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79579. };
  79580. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79581. this._attachedToMesh = mesh;
  79582. var ray = this.ray;
  79583. if (!ray) {
  79584. return;
  79585. }
  79586. if (!ray.direction) {
  79587. ray.direction = BABYLON.Vector3.Zero();
  79588. }
  79589. if (!ray.origin) {
  79590. ray.origin = BABYLON.Vector3.Zero();
  79591. }
  79592. if (length) {
  79593. ray.length = length;
  79594. }
  79595. if (!meshSpaceOrigin) {
  79596. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79597. }
  79598. if (!meshSpaceDirection) {
  79599. // -1 so that this will work with Mesh.lookAt
  79600. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79601. }
  79602. if (!this._meshSpaceDirection) {
  79603. this._meshSpaceDirection = meshSpaceDirection.clone();
  79604. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79605. }
  79606. else {
  79607. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79608. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79609. }
  79610. if (!this._updateToMeshFunction) {
  79611. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79612. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79613. }
  79614. this._updateToMesh();
  79615. };
  79616. RayHelper.prototype.detachFromMesh = function () {
  79617. if (this._attachedToMesh) {
  79618. if (this._updateToMeshFunction) {
  79619. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79620. }
  79621. this._attachedToMesh = null;
  79622. this._updateToMeshFunction = null;
  79623. }
  79624. };
  79625. RayHelper.prototype._updateToMesh = function () {
  79626. var ray = this.ray;
  79627. if (!this._attachedToMesh || !ray) {
  79628. return;
  79629. }
  79630. if (this._attachedToMesh._isDisposed) {
  79631. this.detachFromMesh();
  79632. return;
  79633. }
  79634. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79635. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79636. };
  79637. RayHelper.prototype.dispose = function () {
  79638. this.hide();
  79639. this.detachFromMesh();
  79640. this.ray = null;
  79641. };
  79642. return RayHelper;
  79643. }());
  79644. BABYLON.RayHelper = RayHelper;
  79645. })(BABYLON || (BABYLON = {}));
  79646. //# sourceMappingURL=babylon.rayHelper.js.map
  79647. var BABYLON;
  79648. (function (BABYLON) {
  79649. // load the inspector using require, if not present in the global namespace.
  79650. var DebugLayer = /** @class */ (function () {
  79651. function DebugLayer(scene) {
  79652. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79653. this._scene = scene;
  79654. // load inspector using require, if it doesn't exist on the global namespace.
  79655. }
  79656. /** Creates the inspector window. */
  79657. DebugLayer.prototype._createInspector = function (config) {
  79658. if (config === void 0) { config = {}; }
  79659. var popup = config.popup || false;
  79660. var initialTab = config.initialTab || 0;
  79661. var parentElement = config.parentElement || null;
  79662. if (!this._inspector) {
  79663. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79664. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79665. } // else nothing to do,; instance is already existing
  79666. };
  79667. DebugLayer.prototype.isVisible = function () {
  79668. if (!this._inspector) {
  79669. return false;
  79670. }
  79671. return true;
  79672. };
  79673. DebugLayer.prototype.hide = function () {
  79674. if (this._inspector) {
  79675. try {
  79676. this._inspector.dispose();
  79677. }
  79678. catch (e) {
  79679. // If the inspector has been removed directly from the inspector tool
  79680. }
  79681. this._inspector = null;
  79682. }
  79683. };
  79684. DebugLayer.prototype.show = function (config) {
  79685. if (config === void 0) { config = {}; }
  79686. if (typeof this.BJSINSPECTOR == 'undefined') {
  79687. // Load inspector and add it to the DOM
  79688. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79689. }
  79690. else {
  79691. // Otherwise creates the inspector
  79692. this._createInspector(config);
  79693. }
  79694. };
  79695. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79696. return DebugLayer;
  79697. }());
  79698. BABYLON.DebugLayer = DebugLayer;
  79699. })(BABYLON || (BABYLON = {}));
  79700. //# sourceMappingURL=babylon.debugLayer.js.map
  79701. var BABYLON;
  79702. (function (BABYLON) {
  79703. var BoundingBoxRenderer = /** @class */ (function () {
  79704. function BoundingBoxRenderer(scene) {
  79705. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79706. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79707. this.showBackLines = true;
  79708. this.renderList = new BABYLON.SmartArray(32);
  79709. this._vertexBuffers = {};
  79710. this._scene = scene;
  79711. }
  79712. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79713. if (this._colorShader) {
  79714. return;
  79715. }
  79716. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79717. attributes: [BABYLON.VertexBuffer.PositionKind],
  79718. uniforms: ["world", "viewProjection", "color"]
  79719. });
  79720. var engine = this._scene.getEngine();
  79721. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79722. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79723. this._createIndexBuffer();
  79724. };
  79725. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79726. var engine = this._scene.getEngine();
  79727. 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]);
  79728. };
  79729. BoundingBoxRenderer.prototype._rebuild = function () {
  79730. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79731. if (vb) {
  79732. vb._rebuild();
  79733. }
  79734. this._createIndexBuffer();
  79735. };
  79736. BoundingBoxRenderer.prototype.reset = function () {
  79737. this.renderList.reset();
  79738. };
  79739. BoundingBoxRenderer.prototype.render = function () {
  79740. if (this.renderList.length === 0) {
  79741. return;
  79742. }
  79743. this._prepareRessources();
  79744. if (!this._colorShader.isReady()) {
  79745. return;
  79746. }
  79747. var engine = this._scene.getEngine();
  79748. engine.setDepthWrite(false);
  79749. this._colorShader._preBind();
  79750. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79751. var boundingBox = this.renderList.data[boundingBoxIndex];
  79752. var min = boundingBox.minimum;
  79753. var max = boundingBox.maximum;
  79754. var diff = max.subtract(min);
  79755. var median = min.add(diff.scale(0.5));
  79756. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79757. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79758. .multiply(boundingBox.getWorldMatrix());
  79759. // VBOs
  79760. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79761. if (this.showBackLines) {
  79762. // Back
  79763. engine.setDepthFunctionToGreaterOrEqual();
  79764. this._scene.resetCachedMaterial();
  79765. this._colorShader.setColor4("color", this.backColor.toColor4());
  79766. this._colorShader.bind(worldMatrix);
  79767. // Draw order
  79768. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79769. }
  79770. // Front
  79771. engine.setDepthFunctionToLess();
  79772. this._scene.resetCachedMaterial();
  79773. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79774. this._colorShader.bind(worldMatrix);
  79775. // Draw order
  79776. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79777. }
  79778. this._colorShader.unbind();
  79779. engine.setDepthFunctionToLessOrEqual();
  79780. engine.setDepthWrite(true);
  79781. };
  79782. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79783. this._prepareRessources();
  79784. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79785. return;
  79786. }
  79787. var engine = this._scene.getEngine();
  79788. engine.setDepthWrite(false);
  79789. engine.setColorWrite(false);
  79790. this._colorShader._preBind();
  79791. var boundingBox = mesh._boundingInfo.boundingBox;
  79792. var min = boundingBox.minimum;
  79793. var max = boundingBox.maximum;
  79794. var diff = max.subtract(min);
  79795. var median = min.add(diff.scale(0.5));
  79796. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79797. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79798. .multiply(boundingBox.getWorldMatrix());
  79799. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79800. engine.setDepthFunctionToLess();
  79801. this._scene.resetCachedMaterial();
  79802. this._colorShader.bind(worldMatrix);
  79803. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79804. this._colorShader.unbind();
  79805. engine.setDepthFunctionToLessOrEqual();
  79806. engine.setDepthWrite(true);
  79807. engine.setColorWrite(true);
  79808. };
  79809. BoundingBoxRenderer.prototype.dispose = function () {
  79810. if (!this._colorShader) {
  79811. return;
  79812. }
  79813. this.renderList.dispose();
  79814. this._colorShader.dispose();
  79815. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79816. if (buffer) {
  79817. buffer.dispose();
  79818. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79819. }
  79820. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79821. };
  79822. return BoundingBoxRenderer;
  79823. }());
  79824. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79825. })(BABYLON || (BABYLON = {}));
  79826. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79827. var BABYLON;
  79828. (function (BABYLON) {
  79829. var MorphTarget = /** @class */ (function () {
  79830. function MorphTarget(name, influence) {
  79831. if (influence === void 0) { influence = 0; }
  79832. this.name = name;
  79833. this.animations = new Array();
  79834. this._positions = null;
  79835. this._normals = null;
  79836. this._tangents = null;
  79837. this.onInfluenceChanged = new BABYLON.Observable();
  79838. this.influence = influence;
  79839. }
  79840. Object.defineProperty(MorphTarget.prototype, "influence", {
  79841. get: function () {
  79842. return this._influence;
  79843. },
  79844. set: function (influence) {
  79845. if (this._influence === influence) {
  79846. return;
  79847. }
  79848. var previous = this._influence;
  79849. this._influence = influence;
  79850. if (this.onInfluenceChanged.hasObservers) {
  79851. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79852. }
  79853. },
  79854. enumerable: true,
  79855. configurable: true
  79856. });
  79857. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79858. get: function () {
  79859. return !!this._positions;
  79860. },
  79861. enumerable: true,
  79862. configurable: true
  79863. });
  79864. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79865. get: function () {
  79866. return !!this._normals;
  79867. },
  79868. enumerable: true,
  79869. configurable: true
  79870. });
  79871. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79872. get: function () {
  79873. return !!this._tangents;
  79874. },
  79875. enumerable: true,
  79876. configurable: true
  79877. });
  79878. MorphTarget.prototype.setPositions = function (data) {
  79879. this._positions = data;
  79880. };
  79881. MorphTarget.prototype.getPositions = function () {
  79882. return this._positions;
  79883. };
  79884. MorphTarget.prototype.setNormals = function (data) {
  79885. this._normals = data;
  79886. };
  79887. MorphTarget.prototype.getNormals = function () {
  79888. return this._normals;
  79889. };
  79890. MorphTarget.prototype.setTangents = function (data) {
  79891. this._tangents = data;
  79892. };
  79893. MorphTarget.prototype.getTangents = function () {
  79894. return this._tangents;
  79895. };
  79896. /**
  79897. * Serializes the current target into a Serialization object.
  79898. * Returns the serialized object.
  79899. */
  79900. MorphTarget.prototype.serialize = function () {
  79901. var serializationObject = {};
  79902. serializationObject.name = this.name;
  79903. serializationObject.influence = this.influence;
  79904. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79905. if (this.hasNormals) {
  79906. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79907. }
  79908. if (this.hasTangents) {
  79909. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79910. }
  79911. // Animations
  79912. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79913. return serializationObject;
  79914. };
  79915. // Statics
  79916. MorphTarget.Parse = function (serializationObject) {
  79917. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79918. result.setPositions(serializationObject.positions);
  79919. if (serializationObject.normals) {
  79920. result.setNormals(serializationObject.normals);
  79921. }
  79922. if (serializationObject.tangents) {
  79923. result.setTangents(serializationObject.tangents);
  79924. }
  79925. // Animations
  79926. if (serializationObject.animations) {
  79927. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79928. var parsedAnimation = serializationObject.animations[animationIndex];
  79929. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79930. }
  79931. }
  79932. return result;
  79933. };
  79934. MorphTarget.FromMesh = function (mesh, name, influence) {
  79935. if (!name) {
  79936. name = mesh.name;
  79937. }
  79938. var result = new MorphTarget(name, influence);
  79939. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79941. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79942. }
  79943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79944. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79945. }
  79946. return result;
  79947. };
  79948. return MorphTarget;
  79949. }());
  79950. BABYLON.MorphTarget = MorphTarget;
  79951. })(BABYLON || (BABYLON = {}));
  79952. //# sourceMappingURL=babylon.morphTarget.js.map
  79953. var BABYLON;
  79954. (function (BABYLON) {
  79955. var MorphTargetManager = /** @class */ (function () {
  79956. function MorphTargetManager(scene) {
  79957. if (scene === void 0) { scene = null; }
  79958. this._targets = new Array();
  79959. this._targetObservable = new Array();
  79960. this._activeTargets = new BABYLON.SmartArray(16);
  79961. this._supportsNormals = false;
  79962. this._supportsTangents = false;
  79963. this._vertexCount = 0;
  79964. this._uniqueId = 0;
  79965. this._tempInfluences = new Array();
  79966. if (!scene) {
  79967. scene = BABYLON.Engine.LastCreatedScene;
  79968. }
  79969. this._scene = scene;
  79970. if (this._scene) {
  79971. this._scene.morphTargetManagers.push(this);
  79972. this._uniqueId = this._scene.getUniqueId();
  79973. }
  79974. }
  79975. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79976. get: function () {
  79977. return this._uniqueId;
  79978. },
  79979. enumerable: true,
  79980. configurable: true
  79981. });
  79982. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79983. get: function () {
  79984. return this._vertexCount;
  79985. },
  79986. enumerable: true,
  79987. configurable: true
  79988. });
  79989. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79990. get: function () {
  79991. return this._supportsNormals;
  79992. },
  79993. enumerable: true,
  79994. configurable: true
  79995. });
  79996. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79997. get: function () {
  79998. return this._supportsTangents;
  79999. },
  80000. enumerable: true,
  80001. configurable: true
  80002. });
  80003. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80004. get: function () {
  80005. return this._targets.length;
  80006. },
  80007. enumerable: true,
  80008. configurable: true
  80009. });
  80010. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80011. get: function () {
  80012. return this._activeTargets.length;
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80018. get: function () {
  80019. return this._influences;
  80020. },
  80021. enumerable: true,
  80022. configurable: true
  80023. });
  80024. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80025. return this._activeTargets.data[index];
  80026. };
  80027. MorphTargetManager.prototype.getTarget = function (index) {
  80028. return this._targets[index];
  80029. };
  80030. MorphTargetManager.prototype.addTarget = function (target) {
  80031. var _this = this;
  80032. this._targets.push(target);
  80033. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80034. _this._syncActiveTargets(needUpdate);
  80035. }));
  80036. this._syncActiveTargets(true);
  80037. };
  80038. MorphTargetManager.prototype.removeTarget = function (target) {
  80039. var index = this._targets.indexOf(target);
  80040. if (index >= 0) {
  80041. this._targets.splice(index, 1);
  80042. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80043. this._syncActiveTargets(true);
  80044. }
  80045. };
  80046. /**
  80047. * Serializes the current manager into a Serialization object.
  80048. * Returns the serialized object.
  80049. */
  80050. MorphTargetManager.prototype.serialize = function () {
  80051. var serializationObject = {};
  80052. serializationObject.id = this.uniqueId;
  80053. serializationObject.targets = [];
  80054. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80055. var target = _a[_i];
  80056. serializationObject.targets.push(target.serialize());
  80057. }
  80058. return serializationObject;
  80059. };
  80060. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80061. var influenceCount = 0;
  80062. this._activeTargets.reset();
  80063. this._supportsNormals = true;
  80064. this._supportsTangents = true;
  80065. this._vertexCount = 0;
  80066. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80067. var target = _a[_i];
  80068. this._activeTargets.push(target);
  80069. this._tempInfluences[influenceCount++] = target.influence;
  80070. var positions = target.getPositions();
  80071. if (positions) {
  80072. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80073. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80074. var vertexCount = positions.length / 3;
  80075. if (this._vertexCount === 0) {
  80076. this._vertexCount = vertexCount;
  80077. }
  80078. else if (this._vertexCount !== vertexCount) {
  80079. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80080. return;
  80081. }
  80082. }
  80083. }
  80084. if (!this._influences || this._influences.length !== influenceCount) {
  80085. this._influences = new Float32Array(influenceCount);
  80086. }
  80087. for (var index = 0; index < influenceCount; index++) {
  80088. this._influences[index] = this._tempInfluences[index];
  80089. }
  80090. if (needUpdate && this._scene) {
  80091. // Flag meshes as dirty to resync with the active targets
  80092. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80093. var mesh = _c[_b];
  80094. if (mesh.morphTargetManager === this) {
  80095. mesh._syncGeometryWithMorphTargetManager();
  80096. }
  80097. }
  80098. }
  80099. };
  80100. // Statics
  80101. MorphTargetManager.Parse = function (serializationObject, scene) {
  80102. var result = new MorphTargetManager(scene);
  80103. result._uniqueId = serializationObject.id;
  80104. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80105. var targetData = _a[_i];
  80106. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80107. }
  80108. return result;
  80109. };
  80110. return MorphTargetManager;
  80111. }());
  80112. BABYLON.MorphTargetManager = MorphTargetManager;
  80113. })(BABYLON || (BABYLON = {}));
  80114. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80115. var BABYLON;
  80116. (function (BABYLON) {
  80117. var Octree = /** @class */ (function () {
  80118. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80119. if (maxDepth === void 0) { maxDepth = 2; }
  80120. this.maxDepth = maxDepth;
  80121. this.dynamicContent = new Array();
  80122. this._maxBlockCapacity = maxBlockCapacity || 64;
  80123. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80124. this._creationFunc = creationFunc;
  80125. }
  80126. // Methods
  80127. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80128. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80129. };
  80130. Octree.prototype.addMesh = function (entry) {
  80131. for (var index = 0; index < this.blocks.length; index++) {
  80132. var block = this.blocks[index];
  80133. block.addEntry(entry);
  80134. }
  80135. };
  80136. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80137. this._selectionContent.reset();
  80138. for (var index = 0; index < this.blocks.length; index++) {
  80139. var block = this.blocks[index];
  80140. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80141. }
  80142. if (allowDuplicate) {
  80143. this._selectionContent.concat(this.dynamicContent);
  80144. }
  80145. else {
  80146. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80147. }
  80148. return this._selectionContent;
  80149. };
  80150. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80151. this._selectionContent.reset();
  80152. for (var index = 0; index < this.blocks.length; index++) {
  80153. var block = this.blocks[index];
  80154. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80155. }
  80156. if (allowDuplicate) {
  80157. this._selectionContent.concat(this.dynamicContent);
  80158. }
  80159. else {
  80160. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80161. }
  80162. return this._selectionContent;
  80163. };
  80164. Octree.prototype.intersectsRay = function (ray) {
  80165. this._selectionContent.reset();
  80166. for (var index = 0; index < this.blocks.length; index++) {
  80167. var block = this.blocks[index];
  80168. block.intersectsRay(ray, this._selectionContent);
  80169. }
  80170. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80171. return this._selectionContent;
  80172. };
  80173. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80174. target.blocks = new Array();
  80175. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80176. // Segmenting space
  80177. for (var x = 0; x < 2; x++) {
  80178. for (var y = 0; y < 2; y++) {
  80179. for (var z = 0; z < 2; z++) {
  80180. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80181. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80182. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80183. block.addEntries(entries);
  80184. target.blocks.push(block);
  80185. }
  80186. }
  80187. }
  80188. };
  80189. Octree.CreationFuncForMeshes = function (entry, block) {
  80190. var boundingInfo = entry.getBoundingInfo();
  80191. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80192. block.entries.push(entry);
  80193. }
  80194. };
  80195. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80196. var boundingInfo = entry.getBoundingInfo();
  80197. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80198. block.entries.push(entry);
  80199. }
  80200. };
  80201. return Octree;
  80202. }());
  80203. BABYLON.Octree = Octree;
  80204. })(BABYLON || (BABYLON = {}));
  80205. //# sourceMappingURL=babylon.octree.js.map
  80206. var BABYLON;
  80207. (function (BABYLON) {
  80208. var OctreeBlock = /** @class */ (function () {
  80209. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80210. this.entries = new Array();
  80211. this._boundingVectors = new Array();
  80212. this._capacity = capacity;
  80213. this._depth = depth;
  80214. this._maxDepth = maxDepth;
  80215. this._creationFunc = creationFunc;
  80216. this._minPoint = minPoint;
  80217. this._maxPoint = maxPoint;
  80218. this._boundingVectors.push(minPoint.clone());
  80219. this._boundingVectors.push(maxPoint.clone());
  80220. this._boundingVectors.push(minPoint.clone());
  80221. this._boundingVectors[2].x = maxPoint.x;
  80222. this._boundingVectors.push(minPoint.clone());
  80223. this._boundingVectors[3].y = maxPoint.y;
  80224. this._boundingVectors.push(minPoint.clone());
  80225. this._boundingVectors[4].z = maxPoint.z;
  80226. this._boundingVectors.push(maxPoint.clone());
  80227. this._boundingVectors[5].z = minPoint.z;
  80228. this._boundingVectors.push(maxPoint.clone());
  80229. this._boundingVectors[6].x = minPoint.x;
  80230. this._boundingVectors.push(maxPoint.clone());
  80231. this._boundingVectors[7].y = minPoint.y;
  80232. }
  80233. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80234. // Property
  80235. get: function () {
  80236. return this._capacity;
  80237. },
  80238. enumerable: true,
  80239. configurable: true
  80240. });
  80241. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80242. get: function () {
  80243. return this._minPoint;
  80244. },
  80245. enumerable: true,
  80246. configurable: true
  80247. });
  80248. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80249. get: function () {
  80250. return this._maxPoint;
  80251. },
  80252. enumerable: true,
  80253. configurable: true
  80254. });
  80255. // Methods
  80256. OctreeBlock.prototype.addEntry = function (entry) {
  80257. if (this.blocks) {
  80258. for (var index = 0; index < this.blocks.length; index++) {
  80259. var block = this.blocks[index];
  80260. block.addEntry(entry);
  80261. }
  80262. return;
  80263. }
  80264. this._creationFunc(entry, this);
  80265. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80266. this.createInnerBlocks();
  80267. }
  80268. };
  80269. OctreeBlock.prototype.addEntries = function (entries) {
  80270. for (var index = 0; index < entries.length; index++) {
  80271. var mesh = entries[index];
  80272. this.addEntry(mesh);
  80273. }
  80274. };
  80275. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80276. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80277. if (this.blocks) {
  80278. for (var index = 0; index < this.blocks.length; index++) {
  80279. var block = this.blocks[index];
  80280. block.select(frustumPlanes, selection, allowDuplicate);
  80281. }
  80282. return;
  80283. }
  80284. if (allowDuplicate) {
  80285. selection.concat(this.entries);
  80286. }
  80287. else {
  80288. selection.concatWithNoDuplicate(this.entries);
  80289. }
  80290. }
  80291. };
  80292. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80293. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80294. if (this.blocks) {
  80295. for (var index = 0; index < this.blocks.length; index++) {
  80296. var block = this.blocks[index];
  80297. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80298. }
  80299. return;
  80300. }
  80301. if (allowDuplicate) {
  80302. selection.concat(this.entries);
  80303. }
  80304. else {
  80305. selection.concatWithNoDuplicate(this.entries);
  80306. }
  80307. }
  80308. };
  80309. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80310. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80311. if (this.blocks) {
  80312. for (var index = 0; index < this.blocks.length; index++) {
  80313. var block = this.blocks[index];
  80314. block.intersectsRay(ray, selection);
  80315. }
  80316. return;
  80317. }
  80318. selection.concatWithNoDuplicate(this.entries);
  80319. }
  80320. };
  80321. OctreeBlock.prototype.createInnerBlocks = function () {
  80322. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80323. };
  80324. return OctreeBlock;
  80325. }());
  80326. BABYLON.OctreeBlock = OctreeBlock;
  80327. })(BABYLON || (BABYLON = {}));
  80328. //# sourceMappingURL=babylon.octreeBlock.js.map
  80329. var BABYLON;
  80330. (function (BABYLON) {
  80331. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80332. __extends(VRDistortionCorrectionPostProcess, _super);
  80333. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80334. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80335. 'LensCenter',
  80336. 'Scale',
  80337. 'ScaleIn',
  80338. 'HmdWarpParam'
  80339. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80340. _this._isRightEye = isRightEye;
  80341. _this._distortionFactors = vrMetrics.distortionK;
  80342. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80343. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80344. _this.adaptScaleToCurrentViewport = true;
  80345. _this.onSizeChangedObservable.add(function () {
  80346. _this.aspectRatio = _this.width * .5 / _this.height;
  80347. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80348. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80349. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80350. });
  80351. _this.onApplyObservable.add(function (effect) {
  80352. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80353. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80354. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80355. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80356. });
  80357. return _this;
  80358. }
  80359. return VRDistortionCorrectionPostProcess;
  80360. }(BABYLON.PostProcess));
  80361. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80362. })(BABYLON || (BABYLON = {}));
  80363. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80364. var BABYLON;
  80365. (function (BABYLON) {
  80366. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80367. __extends(AnaglyphPostProcess, _super);
  80368. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80369. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80370. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80371. _this.onApplyObservable.add(function (effect) {
  80372. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80373. });
  80374. return _this;
  80375. }
  80376. return AnaglyphPostProcess;
  80377. }(BABYLON.PostProcess));
  80378. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80379. })(BABYLON || (BABYLON = {}));
  80380. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80381. var BABYLON;
  80382. (function (BABYLON) {
  80383. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80384. __extends(StereoscopicInterlacePostProcess, _super);
  80385. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80386. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80387. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80388. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80389. _this.onSizeChangedObservable.add(function () {
  80390. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80391. });
  80392. _this.onApplyObservable.add(function (effect) {
  80393. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80394. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80395. });
  80396. return _this;
  80397. }
  80398. return StereoscopicInterlacePostProcess;
  80399. }(BABYLON.PostProcess));
  80400. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80401. })(BABYLON || (BABYLON = {}));
  80402. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80403. var BABYLON;
  80404. (function (BABYLON) {
  80405. /**
  80406. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80407. * Screen rotation is taken into account.
  80408. */
  80409. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80410. function FreeCameraDeviceOrientationInput() {
  80411. var _this = this;
  80412. this._screenOrientationAngle = 0;
  80413. this._screenQuaternion = new BABYLON.Quaternion();
  80414. this._alpha = 0;
  80415. this._beta = 0;
  80416. this._gamma = 0;
  80417. this._orientationChanged = function () {
  80418. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80419. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80420. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80421. };
  80422. this._deviceOrientation = function (evt) {
  80423. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80424. _this._beta = evt.beta !== null ? evt.beta : 0;
  80425. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80426. };
  80427. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80428. this._orientationChanged();
  80429. }
  80430. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80431. get: function () {
  80432. return this._camera;
  80433. },
  80434. set: function (camera) {
  80435. this._camera = camera;
  80436. if (this._camera != null && !this._camera.rotationQuaternion) {
  80437. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80438. }
  80439. },
  80440. enumerable: true,
  80441. configurable: true
  80442. });
  80443. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80444. window.addEventListener("orientationchange", this._orientationChanged);
  80445. window.addEventListener("deviceorientation", this._deviceOrientation);
  80446. //In certain cases, the attach control is called AFTER orientation was changed,
  80447. //So this is needed.
  80448. this._orientationChanged();
  80449. };
  80450. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80451. window.removeEventListener("orientationchange", this._orientationChanged);
  80452. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80453. };
  80454. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80455. //if no device orientation provided, don't update the rotation.
  80456. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80457. if (!this._alpha)
  80458. return;
  80459. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80460. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80461. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80462. //Mirror on XY Plane
  80463. this._camera.rotationQuaternion.z *= -1;
  80464. this._camera.rotationQuaternion.w *= -1;
  80465. };
  80466. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80467. return "FreeCameraDeviceOrientationInput";
  80468. };
  80469. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80470. return "deviceOrientation";
  80471. };
  80472. return FreeCameraDeviceOrientationInput;
  80473. }());
  80474. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80475. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80476. })(BABYLON || (BABYLON = {}));
  80477. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80478. var BABYLON;
  80479. (function (BABYLON) {
  80480. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80481. function ArcRotateCameraVRDeviceOrientationInput() {
  80482. this.alphaCorrection = 1;
  80483. this.betaCorrection = 1;
  80484. this.gammaCorrection = 1;
  80485. this._alpha = 0;
  80486. this._gamma = 0;
  80487. this._dirty = false;
  80488. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80489. }
  80490. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80491. this.camera.attachControl(element, noPreventDefault);
  80492. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80493. };
  80494. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80495. if (evt.alpha !== null) {
  80496. this._alpha = +evt.alpha | 0;
  80497. }
  80498. if (evt.gamma !== null) {
  80499. this._gamma = +evt.gamma | 0;
  80500. }
  80501. this._dirty = true;
  80502. };
  80503. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80504. if (this._dirty) {
  80505. this._dirty = false;
  80506. if (this._gamma < 0) {
  80507. this._gamma = 180 + this._gamma;
  80508. }
  80509. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80510. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80511. }
  80512. };
  80513. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80514. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80515. };
  80516. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80517. return "ArcRotateCameraVRDeviceOrientationInput";
  80518. };
  80519. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80520. return "VRDeviceOrientation";
  80521. };
  80522. return ArcRotateCameraVRDeviceOrientationInput;
  80523. }());
  80524. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80525. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80526. })(BABYLON || (BABYLON = {}));
  80527. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80528. var BABYLON;
  80529. (function (BABYLON) {
  80530. var VRCameraMetrics = /** @class */ (function () {
  80531. function VRCameraMetrics() {
  80532. this.compensateDistortion = true;
  80533. }
  80534. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80535. get: function () {
  80536. return this.hResolution / (2 * this.vResolution);
  80537. },
  80538. enumerable: true,
  80539. configurable: true
  80540. });
  80541. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80542. get: function () {
  80543. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80544. },
  80545. enumerable: true,
  80546. configurable: true
  80547. });
  80548. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80549. get: function () {
  80550. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80551. var h = (4 * meters) / this.hScreenSize;
  80552. return BABYLON.Matrix.Translation(h, 0, 0);
  80553. },
  80554. enumerable: true,
  80555. configurable: true
  80556. });
  80557. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80558. get: function () {
  80559. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80560. var h = (4 * meters) / this.hScreenSize;
  80561. return BABYLON.Matrix.Translation(-h, 0, 0);
  80562. },
  80563. enumerable: true,
  80564. configurable: true
  80565. });
  80566. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80567. get: function () {
  80568. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80569. },
  80570. enumerable: true,
  80571. configurable: true
  80572. });
  80573. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80574. get: function () {
  80575. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80576. },
  80577. enumerable: true,
  80578. configurable: true
  80579. });
  80580. VRCameraMetrics.GetDefault = function () {
  80581. var result = new VRCameraMetrics();
  80582. result.hResolution = 1280;
  80583. result.vResolution = 800;
  80584. result.hScreenSize = 0.149759993;
  80585. result.vScreenSize = 0.0935999975;
  80586. result.vScreenCenter = 0.0467999987;
  80587. result.eyeToScreenDistance = 0.0410000011;
  80588. result.lensSeparationDistance = 0.0635000020;
  80589. result.interpupillaryDistance = 0.0640000030;
  80590. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80591. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80592. result.postProcessScaleFactor = 1.714605507808412;
  80593. result.lensCenterOffset = 0.151976421;
  80594. return result;
  80595. };
  80596. return VRCameraMetrics;
  80597. }());
  80598. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80599. })(BABYLON || (BABYLON = {}));
  80600. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80601. var BABYLON;
  80602. (function (BABYLON) {
  80603. /**
  80604. * This represents a WebVR camera.
  80605. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80606. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80607. */
  80608. var WebVRFreeCamera = /** @class */ (function (_super) {
  80609. __extends(WebVRFreeCamera, _super);
  80610. /**
  80611. * Instantiates a WebVRFreeCamera.
  80612. * @param name The name of the WebVRFreeCamera
  80613. * @param position The starting anchor position for the camera
  80614. * @param scene The scene the camera belongs to
  80615. * @param webVROptions a set of customizable options for the webVRCamera
  80616. */
  80617. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80618. if (webVROptions === void 0) { webVROptions = {}; }
  80619. var _this = _super.call(this, name, position, scene) || this;
  80620. _this.webVROptions = webVROptions;
  80621. /**
  80622. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80623. */
  80624. _this._vrDevice = null;
  80625. /**
  80626. * The rawPose of the vrDevice.
  80627. */
  80628. _this.rawPose = null;
  80629. _this._specsVersion = "1.1";
  80630. _this._attached = false;
  80631. _this._descendants = [];
  80632. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80633. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80634. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80635. _this._standingMatrix = null;
  80636. /**
  80637. * Represents device position in babylon space.
  80638. */
  80639. _this.devicePosition = BABYLON.Vector3.Zero();
  80640. /**
  80641. * Represents device rotation in babylon space.
  80642. */
  80643. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80644. /**
  80645. * The scale of the device to be used when translating from device space to babylon space.
  80646. */
  80647. _this.deviceScaleFactor = 1;
  80648. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80649. _this._worldToDevice = BABYLON.Matrix.Identity();
  80650. /**
  80651. * References to the webVR controllers for the vrDevice.
  80652. */
  80653. _this.controllers = [];
  80654. /**
  80655. * Emits an event when a controller is attached.
  80656. */
  80657. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80658. /**
  80659. * Emits an event when a controller's mesh has been loaded;
  80660. */
  80661. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80662. /**
  80663. * If the rig cameras be used as parent instead of this camera.
  80664. */
  80665. _this.rigParenting = true;
  80666. _this._defaultHeight = undefined;
  80667. _this._workingVector = BABYLON.Vector3.Zero();
  80668. _this._oneVector = BABYLON.Vector3.One();
  80669. _this._workingMatrix = BABYLON.Matrix.Identity();
  80670. _this._cache.position = BABYLON.Vector3.Zero();
  80671. if (webVROptions.defaultHeight) {
  80672. _this._defaultHeight = webVROptions.defaultHeight;
  80673. _this.position.y = _this._defaultHeight;
  80674. }
  80675. _this.minZ = 0.1;
  80676. //legacy support - the compensation boolean was removed.
  80677. if (arguments.length === 5) {
  80678. _this.webVROptions = arguments[4];
  80679. }
  80680. // default webVR options
  80681. if (_this.webVROptions.trackPosition == undefined) {
  80682. _this.webVROptions.trackPosition = true;
  80683. }
  80684. if (_this.webVROptions.controllerMeshes == undefined) {
  80685. _this.webVROptions.controllerMeshes = true;
  80686. }
  80687. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80688. _this.webVROptions.defaultLightingOnControllers = true;
  80689. }
  80690. _this.rotationQuaternion = new BABYLON.Quaternion();
  80691. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80692. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80693. }
  80694. //enable VR
  80695. var engine = _this.getEngine();
  80696. _this._onVREnabled = function (success) { if (success) {
  80697. _this.initControllers();
  80698. } };
  80699. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80700. engine.initWebVR().add(function (event) {
  80701. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80702. return;
  80703. }
  80704. _this._vrDevice = event.vrDisplay;
  80705. //reset the rig parameters.
  80706. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80707. if (_this._attached) {
  80708. _this.getEngine().enableVR();
  80709. }
  80710. });
  80711. if (typeof (VRFrameData) !== "undefined")
  80712. _this._frameData = new VRFrameData();
  80713. /**
  80714. * The idea behind the following lines:
  80715. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80716. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80717. * the second will not show it correctly.
  80718. *
  80719. * To solve this - each object that has the camera as parent will be added to a protected array.
  80720. * When the rig camera renders, it will take this array and set all of those to be its children.
  80721. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80722. * Amazing!
  80723. */
  80724. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80725. if (camera.parent === _this && _this.rigParenting) {
  80726. _this._descendants = _this.getDescendants(true, function (n) {
  80727. // don't take the cameras or the controllers!
  80728. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80729. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80730. return !isController && !isRigCamera;
  80731. });
  80732. _this._descendants.forEach(function (node) {
  80733. node.parent = camera;
  80734. });
  80735. }
  80736. });
  80737. scene.onAfterCameraRenderObservable.add(function (camera) {
  80738. if (camera.parent === _this && _this.rigParenting) {
  80739. _this._descendants.forEach(function (node) {
  80740. node.parent = _this;
  80741. });
  80742. }
  80743. });
  80744. return _this;
  80745. }
  80746. /**
  80747. * Gets the device distance from the ground in meters.
  80748. * @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.
  80749. */
  80750. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80751. if (this._standingMatrix) {
  80752. // Add standing matrix offset to get real offset from ground in room
  80753. this._standingMatrix.getTranslationToRef(this._workingVector);
  80754. return this._deviceRoomPosition.y + this._workingVector.y;
  80755. }
  80756. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80757. return this._defaultHeight || 0;
  80758. };
  80759. /**
  80760. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80761. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80762. */
  80763. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80764. var _this = this;
  80765. if (callback === void 0) { callback = function (bool) { }; }
  80766. // Use standing matrix if available
  80767. this.getEngine().initWebVRAsync().then(function (result) {
  80768. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80769. callback(false);
  80770. }
  80771. else {
  80772. _this._standingMatrix = new BABYLON.Matrix();
  80773. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80774. if (!_this.getScene().useRightHandedSystem) {
  80775. [2, 6, 8, 9, 14].forEach(function (num) {
  80776. if (_this._standingMatrix) {
  80777. _this._standingMatrix.m[num] *= -1;
  80778. }
  80779. });
  80780. }
  80781. callback(true);
  80782. }
  80783. });
  80784. };
  80785. /**
  80786. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80787. * @returns A promise with a boolean set to if the standing matrix is supported.
  80788. */
  80789. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80790. var _this = this;
  80791. return new Promise(function (res, rej) {
  80792. _this.useStandingMatrix(function (supported) {
  80793. res(supported);
  80794. });
  80795. });
  80796. };
  80797. /**
  80798. * Disposes the camera
  80799. */
  80800. WebVRFreeCamera.prototype.dispose = function () {
  80801. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80802. _super.prototype.dispose.call(this);
  80803. };
  80804. /**
  80805. * Gets a vrController by name.
  80806. * @param name The name of the controller to retreive
  80807. * @returns the controller matching the name specified or null if not found
  80808. */
  80809. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80810. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80811. var gp = _a[_i];
  80812. if (gp.hand === name) {
  80813. return gp;
  80814. }
  80815. }
  80816. return null;
  80817. };
  80818. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80819. /**
  80820. * The controller corrisponding to the users left hand.
  80821. */
  80822. get: function () {
  80823. if (!this._leftController) {
  80824. this._leftController = this.getControllerByName("left");
  80825. }
  80826. return this._leftController;
  80827. },
  80828. enumerable: true,
  80829. configurable: true
  80830. });
  80831. ;
  80832. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80833. /**
  80834. * The controller corrisponding to the users right hand.
  80835. */
  80836. get: function () {
  80837. if (!this._rightController) {
  80838. this._rightController = this.getControllerByName("right");
  80839. }
  80840. return this._rightController;
  80841. },
  80842. enumerable: true,
  80843. configurable: true
  80844. });
  80845. ;
  80846. /**
  80847. * Casts a ray forward from the vrCamera's gaze.
  80848. * @param length Length of the ray (default: 100)
  80849. * @returns the ray corrisponding to the gaze
  80850. */
  80851. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80852. if (length === void 0) { length = 100; }
  80853. if (this.leftCamera) {
  80854. // Use left eye to avoid computation to compute center on every call
  80855. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80856. }
  80857. else {
  80858. return _super.prototype.getForwardRay.call(this, length);
  80859. }
  80860. };
  80861. /**
  80862. * Updates the camera based on device's frame data
  80863. */
  80864. WebVRFreeCamera.prototype._checkInputs = function () {
  80865. if (this._vrDevice && this._vrDevice.isPresenting) {
  80866. this._vrDevice.getFrameData(this._frameData);
  80867. this.updateFromDevice(this._frameData.pose);
  80868. }
  80869. _super.prototype._checkInputs.call(this);
  80870. };
  80871. /**
  80872. * Updates the poseControlled values based on the input device pose.
  80873. * @param poseData Pose coming from the device
  80874. */
  80875. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80876. if (poseData && poseData.orientation) {
  80877. this.rawPose = poseData;
  80878. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80879. if (this.getScene().useRightHandedSystem) {
  80880. this._deviceRoomRotationQuaternion.z *= -1;
  80881. this._deviceRoomRotationQuaternion.w *= -1;
  80882. }
  80883. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80884. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80885. if (this.getScene().useRightHandedSystem) {
  80886. this._deviceRoomPosition.z *= -1;
  80887. }
  80888. }
  80889. }
  80890. };
  80891. /**
  80892. * WebVR's attach control will start broadcasting frames to the device.
  80893. * Note that in certain browsers (chrome for example) this function must be called
  80894. * within a user-interaction callback. Example:
  80895. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80896. *
  80897. * @param element html element to attach the vrDevice to
  80898. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80899. */
  80900. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80901. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80902. this._attached = true;
  80903. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80904. if (this._vrDevice) {
  80905. this.getEngine().enableVR();
  80906. }
  80907. };
  80908. /**
  80909. * Detaches the camera from the html element and disables VR
  80910. *
  80911. * @param element html element to detach from
  80912. */
  80913. WebVRFreeCamera.prototype.detachControl = function (element) {
  80914. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80915. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80916. _super.prototype.detachControl.call(this, element);
  80917. this._attached = false;
  80918. this.getEngine().disableVR();
  80919. };
  80920. /**
  80921. * @returns the name of this class
  80922. */
  80923. WebVRFreeCamera.prototype.getClassName = function () {
  80924. return "WebVRFreeCamera";
  80925. };
  80926. /**
  80927. * Calls resetPose on the vrDisplay
  80928. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80929. */
  80930. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80931. //uses the vrDisplay's "resetPose()".
  80932. //pitch and roll won't be affected.
  80933. this._vrDevice.resetPose();
  80934. };
  80935. /**
  80936. * Updates the rig cameras (left and right eye)
  80937. */
  80938. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80939. var camLeft = this._rigCameras[0];
  80940. var camRight = this._rigCameras[1];
  80941. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80942. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80943. camLeft.position.copyFrom(this._deviceRoomPosition);
  80944. camRight.position.copyFrom(this._deviceRoomPosition);
  80945. };
  80946. /**
  80947. * Updates the cached values of the camera
  80948. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80949. */
  80950. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80951. var _this = this;
  80952. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80953. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80954. if (!this.updateCacheCalled) {
  80955. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80956. this.updateCacheCalled = true;
  80957. this.update();
  80958. }
  80959. // Set working vector to the device position in room space rotated by the new rotation
  80960. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80961. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80962. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80963. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80964. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80965. // Add translation from anchor position
  80966. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80967. this._workingVector.addInPlace(this.position);
  80968. this._workingVector.subtractInPlace(this._cache.position);
  80969. this._deviceToWorld.setTranslation(this._workingVector);
  80970. // Set an inverted matrix to be used when updating the camera
  80971. this._deviceToWorld.invertToRef(this._worldToDevice);
  80972. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80973. this.controllers.forEach(function (controller) {
  80974. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80975. controller.update();
  80976. });
  80977. }
  80978. if (!ignoreParentClass) {
  80979. _super.prototype._updateCache.call(this);
  80980. }
  80981. this.updateCacheCalled = false;
  80982. };
  80983. /**
  80984. * Updates the current device position and rotation in the babylon world
  80985. */
  80986. WebVRFreeCamera.prototype.update = function () {
  80987. // Get current device position in babylon world
  80988. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80989. // Get current device rotation in babylon world
  80990. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80991. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80992. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80993. _super.prototype.update.call(this);
  80994. };
  80995. /**
  80996. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80997. * @returns an identity matrix
  80998. */
  80999. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81000. return BABYLON.Matrix.Identity();
  81001. };
  81002. /**
  81003. * This function is called by the two RIG cameras.
  81004. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81005. */
  81006. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81007. var _this = this;
  81008. // Update the parent camera prior to using a child camera to avoid desynchronization
  81009. var parentCamera = this._cameraRigParams["parentCamera"];
  81010. parentCamera._updateCache();
  81011. //WebVR 1.1
  81012. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81013. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81014. if (!this.getScene().useRightHandedSystem) {
  81015. [2, 6, 8, 9, 14].forEach(function (num) {
  81016. _this._webvrViewMatrix.m[num] *= -1;
  81017. });
  81018. }
  81019. // update the camera rotation matrix
  81020. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81021. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81022. // Computing target and final matrix
  81023. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81024. // should the view matrix be updated with scale and position offset?
  81025. if (parentCamera.deviceScaleFactor !== 1) {
  81026. this._webvrViewMatrix.invert();
  81027. // scale the position, if set
  81028. if (parentCamera.deviceScaleFactor) {
  81029. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81030. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81031. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81032. }
  81033. this._webvrViewMatrix.invert();
  81034. }
  81035. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81036. return this._webvrViewMatrix;
  81037. };
  81038. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81039. var _this = this;
  81040. var parentCamera = this.parent;
  81041. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81042. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81043. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81044. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81045. //babylon compatible matrix
  81046. if (!this.getScene().useRightHandedSystem) {
  81047. [8, 9, 10, 11].forEach(function (num) {
  81048. _this._projectionMatrix.m[num] *= -1;
  81049. });
  81050. }
  81051. return this._projectionMatrix;
  81052. };
  81053. /**
  81054. * Initializes the controllers and their meshes
  81055. */
  81056. WebVRFreeCamera.prototype.initControllers = function () {
  81057. var _this = this;
  81058. this.controllers = [];
  81059. var manager = this.getScene().gamepadManager;
  81060. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81061. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81062. var webVrController = gamepad;
  81063. if (webVrController.defaultModel) {
  81064. webVrController.defaultModel.setEnabled(false);
  81065. }
  81066. if (webVrController.hand === "right") {
  81067. _this._rightController = null;
  81068. }
  81069. if (webVrController.hand === "left") {
  81070. _this._leftController = null;
  81071. }
  81072. var controllerIndex = _this.controllers.indexOf(webVrController);
  81073. if (controllerIndex !== -1) {
  81074. _this.controllers.splice(controllerIndex, 1);
  81075. }
  81076. }
  81077. });
  81078. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81079. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81080. var webVrController_1 = gamepad;
  81081. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81082. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81083. if (_this.webVROptions.controllerMeshes) {
  81084. if (webVrController_1.defaultModel) {
  81085. webVrController_1.defaultModel.setEnabled(true);
  81086. }
  81087. else {
  81088. // Load the meshes
  81089. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81090. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81091. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81092. if (_this.webVROptions.defaultLightingOnControllers) {
  81093. if (!_this._lightOnControllers) {
  81094. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81095. }
  81096. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81097. var children = mesh.getChildren();
  81098. if (children.length !== 0) {
  81099. children.forEach(function (mesh) {
  81100. light.includedOnlyMeshes.push(mesh);
  81101. activateLightOnSubMeshes_1(mesh, light);
  81102. });
  81103. }
  81104. };
  81105. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81106. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81107. }
  81108. });
  81109. }
  81110. }
  81111. webVrController_1.attachToPoseControlledCamera(_this);
  81112. // since this is async - sanity check. Is the controller already stored?
  81113. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81114. //add to the controllers array
  81115. _this.controllers.push(webVrController_1);
  81116. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81117. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81118. // So we're overriding setting left & right manually to be sure
  81119. var firstViveWandDetected = false;
  81120. for (var i = 0; i < _this.controllers.length; i++) {
  81121. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81122. if (!firstViveWandDetected) {
  81123. firstViveWandDetected = true;
  81124. _this.controllers[i].hand = "left";
  81125. }
  81126. else {
  81127. _this.controllers[i].hand = "right";
  81128. }
  81129. }
  81130. }
  81131. //did we find enough controllers? Great! let the developer know.
  81132. if (_this.controllers.length >= 2) {
  81133. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81134. }
  81135. }
  81136. }
  81137. });
  81138. };
  81139. return WebVRFreeCamera;
  81140. }(BABYLON.FreeCamera));
  81141. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81142. })(BABYLON || (BABYLON = {}));
  81143. //# sourceMappingURL=babylon.webVRCamera.js.map
  81144. var BABYLON;
  81145. (function (BABYLON) {
  81146. // We're mainly based on the logic defined into the FreeCamera code
  81147. /**
  81148. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81149. * being tilted forward or back and left or right.
  81150. */
  81151. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81152. __extends(DeviceOrientationCamera, _super);
  81153. /**
  81154. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81155. * @param name The name of the camera
  81156. * @param position The start position camera
  81157. * @param scene The scene the camera belongs to
  81158. */
  81159. function DeviceOrientationCamera(name, position, scene) {
  81160. var _this = _super.call(this, name, position, scene) || this;
  81161. _this._quaternionCache = new BABYLON.Quaternion();
  81162. _this.inputs.addDeviceOrientation();
  81163. return _this;
  81164. }
  81165. /**
  81166. * Gets the current instance class name ("DeviceOrientationCamera").
  81167. * This helps avoiding instanceof at run time.
  81168. * @returns the class name
  81169. */
  81170. DeviceOrientationCamera.prototype.getClassName = function () {
  81171. return "DeviceOrientationCamera";
  81172. };
  81173. /**
  81174. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81175. */
  81176. DeviceOrientationCamera.prototype._checkInputs = function () {
  81177. _super.prototype._checkInputs.call(this);
  81178. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81179. if (this._initialQuaternion) {
  81180. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81181. }
  81182. };
  81183. /**
  81184. * Reset the camera to its default orientation on the specified axis only.
  81185. * @param axis The axis to reset
  81186. */
  81187. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81188. var _this = this;
  81189. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81190. //can only work if this camera has a rotation quaternion already.
  81191. if (!this.rotationQuaternion)
  81192. return;
  81193. if (!this._initialQuaternion) {
  81194. this._initialQuaternion = new BABYLON.Quaternion();
  81195. }
  81196. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81197. ['x', 'y', 'z'].forEach(function (axisName) {
  81198. if (!axis[axisName]) {
  81199. _this._initialQuaternion[axisName] = 0;
  81200. }
  81201. else {
  81202. _this._initialQuaternion[axisName] *= -1;
  81203. }
  81204. });
  81205. this._initialQuaternion.normalize();
  81206. //force rotation update
  81207. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81208. };
  81209. return DeviceOrientationCamera;
  81210. }(BABYLON.FreeCamera));
  81211. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81212. })(BABYLON || (BABYLON = {}));
  81213. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81214. var BABYLON;
  81215. (function (BABYLON) {
  81216. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81217. __extends(VRDeviceOrientationFreeCamera, _super);
  81218. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81219. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81220. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81221. var _this = _super.call(this, name, position, scene) || this;
  81222. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81223. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81224. return _this;
  81225. }
  81226. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81227. return "VRDeviceOrientationFreeCamera";
  81228. };
  81229. return VRDeviceOrientationFreeCamera;
  81230. }(BABYLON.DeviceOrientationCamera));
  81231. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81232. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81233. __extends(VRDeviceOrientationGamepadCamera, _super);
  81234. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81235. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81236. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81237. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81238. _this.inputs.addGamepad();
  81239. return _this;
  81240. }
  81241. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81242. return "VRDeviceOrientationGamepadCamera";
  81243. };
  81244. return VRDeviceOrientationGamepadCamera;
  81245. }(VRDeviceOrientationFreeCamera));
  81246. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81247. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81248. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81249. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81250. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81251. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81252. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81253. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81254. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81255. _this.inputs.addVRDeviceOrientation();
  81256. return _this;
  81257. }
  81258. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81259. return "VRDeviceOrientationArcRotateCamera";
  81260. };
  81261. return VRDeviceOrientationArcRotateCamera;
  81262. }(BABYLON.ArcRotateCamera));
  81263. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81264. })(BABYLON || (BABYLON = {}));
  81265. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81266. var BABYLON;
  81267. (function (BABYLON) {
  81268. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81269. __extends(AnaglyphFreeCamera, _super);
  81270. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81271. var _this = _super.call(this, name, position, scene) || this;
  81272. _this.interaxialDistance = interaxialDistance;
  81273. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81274. return _this;
  81275. }
  81276. AnaglyphFreeCamera.prototype.getClassName = function () {
  81277. return "AnaglyphFreeCamera";
  81278. };
  81279. return AnaglyphFreeCamera;
  81280. }(BABYLON.FreeCamera));
  81281. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81282. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81283. __extends(AnaglyphArcRotateCamera, _super);
  81284. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81285. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81286. _this.interaxialDistance = interaxialDistance;
  81287. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81288. return _this;
  81289. }
  81290. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81291. return "AnaglyphArcRotateCamera";
  81292. };
  81293. return AnaglyphArcRotateCamera;
  81294. }(BABYLON.ArcRotateCamera));
  81295. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81296. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81297. __extends(AnaglyphGamepadCamera, _super);
  81298. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81299. var _this = _super.call(this, name, position, scene) || this;
  81300. _this.interaxialDistance = interaxialDistance;
  81301. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81302. return _this;
  81303. }
  81304. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81305. return "AnaglyphGamepadCamera";
  81306. };
  81307. return AnaglyphGamepadCamera;
  81308. }(BABYLON.GamepadCamera));
  81309. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81310. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81311. __extends(AnaglyphUniversalCamera, _super);
  81312. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81313. var _this = _super.call(this, name, position, scene) || this;
  81314. _this.interaxialDistance = interaxialDistance;
  81315. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81316. return _this;
  81317. }
  81318. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81319. return "AnaglyphUniversalCamera";
  81320. };
  81321. return AnaglyphUniversalCamera;
  81322. }(BABYLON.UniversalCamera));
  81323. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81324. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81325. __extends(StereoscopicFreeCamera, _super);
  81326. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81327. var _this = _super.call(this, name, position, scene) || this;
  81328. _this.interaxialDistance = interaxialDistance;
  81329. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81330. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81331. return _this;
  81332. }
  81333. StereoscopicFreeCamera.prototype.getClassName = function () {
  81334. return "StereoscopicFreeCamera";
  81335. };
  81336. return StereoscopicFreeCamera;
  81337. }(BABYLON.FreeCamera));
  81338. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81339. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81340. __extends(StereoscopicArcRotateCamera, _super);
  81341. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81342. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81343. _this.interaxialDistance = interaxialDistance;
  81344. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81345. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81346. return _this;
  81347. }
  81348. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81349. return "StereoscopicArcRotateCamera";
  81350. };
  81351. return StereoscopicArcRotateCamera;
  81352. }(BABYLON.ArcRotateCamera));
  81353. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81354. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81355. __extends(StereoscopicGamepadCamera, _super);
  81356. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81357. var _this = _super.call(this, name, position, scene) || this;
  81358. _this.interaxialDistance = interaxialDistance;
  81359. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81360. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81361. return _this;
  81362. }
  81363. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81364. return "StereoscopicGamepadCamera";
  81365. };
  81366. return StereoscopicGamepadCamera;
  81367. }(BABYLON.GamepadCamera));
  81368. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81369. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81370. __extends(StereoscopicUniversalCamera, _super);
  81371. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81372. var _this = _super.call(this, name, position, scene) || this;
  81373. _this.interaxialDistance = interaxialDistance;
  81374. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81375. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81376. return _this;
  81377. }
  81378. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81379. return "StereoscopicUniversalCamera";
  81380. };
  81381. return StereoscopicUniversalCamera;
  81382. }(BABYLON.UniversalCamera));
  81383. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81384. })(BABYLON || (BABYLON = {}));
  81385. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81386. var BABYLON;
  81387. (function (BABYLON) {
  81388. var VRExperienceHelperGazer = /** @class */ (function () {
  81389. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81390. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81391. this.scene = scene;
  81392. this._pointerDownOnMeshAsked = false;
  81393. this._isActionableMesh = false;
  81394. this._teleportationRequestInitiated = false;
  81395. this._teleportationBackRequestInitiated = false;
  81396. this._dpadPressed = true;
  81397. this._activePointer = false;
  81398. this._id = VRExperienceHelperGazer._idCounter++;
  81399. // Gaze tracker
  81400. if (!gazeTrackerToClone) {
  81401. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81402. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81403. this._gazeTracker.isPickable = false;
  81404. this._gazeTracker.isVisible = false;
  81405. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81406. targetMat.specularColor = BABYLON.Color3.Black();
  81407. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81408. targetMat.backFaceCulling = false;
  81409. this._gazeTracker.material = targetMat;
  81410. }
  81411. else {
  81412. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81413. }
  81414. }
  81415. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81416. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81417. };
  81418. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81419. this._pointerDownOnMeshAsked = true;
  81420. if (this._currentMeshSelected && this._currentHit) {
  81421. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81422. }
  81423. };
  81424. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81425. if (this._currentMeshSelected && this._currentHit) {
  81426. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81427. }
  81428. this._pointerDownOnMeshAsked = false;
  81429. };
  81430. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81431. this._activePointer = true;
  81432. };
  81433. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81434. this._activePointer = false;
  81435. };
  81436. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81437. };
  81438. VRExperienceHelperGazer.prototype.dispose = function () {
  81439. this._interactionsEnabled = false;
  81440. this._teleportationEnabled = false;
  81441. };
  81442. VRExperienceHelperGazer._idCounter = 0;
  81443. return VRExperienceHelperGazer;
  81444. }());
  81445. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81446. __extends(VRExperienceHelperControllerGazer, _super);
  81447. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81448. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81449. _this.webVRController = webVRController;
  81450. // Laser pointer
  81451. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81452. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81453. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81454. laserPointerMaterial.alpha = 0.6;
  81455. _this._laserPointer.material = laserPointerMaterial;
  81456. _this._laserPointer.rotation.x = Math.PI / 2;
  81457. _this._laserPointer.position.z = -0.5;
  81458. _this._laserPointer.isVisible = false;
  81459. if (!webVRController.mesh) {
  81460. // Create an empty mesh that is used prior to loading the high quality model
  81461. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81462. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81463. preloadPointerPose.rotation.x = -0.7;
  81464. preloadMesh.addChild(preloadPointerPose);
  81465. webVRController.attachToMesh(preloadMesh);
  81466. }
  81467. _this._setLaserPointerParent(webVRController.mesh);
  81468. return _this;
  81469. }
  81470. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81471. return this.webVRController.getForwardRay(length);
  81472. };
  81473. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81474. _super.prototype._activatePointer.call(this);
  81475. this._laserPointer.isVisible = true;
  81476. };
  81477. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81478. _super.prototype._deactivatePointer.call(this);
  81479. this._laserPointer.isVisible = false;
  81480. };
  81481. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81482. this._laserPointer.material.emissiveColor = color;
  81483. };
  81484. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81485. var makeNotPick = function (root) {
  81486. root.name += " laserPointer";
  81487. root.getChildMeshes().forEach(function (c) {
  81488. makeNotPick(c);
  81489. });
  81490. };
  81491. makeNotPick(mesh);
  81492. var childMeshes = mesh.getChildMeshes();
  81493. this.webVRController._pointingPoseNode = null;
  81494. for (var i = 0; i < childMeshes.length; i++) {
  81495. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81496. mesh = childMeshes[i];
  81497. this.webVRController._pointingPoseNode = mesh;
  81498. break;
  81499. }
  81500. }
  81501. this._laserPointer.parent = mesh;
  81502. };
  81503. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81504. this._laserPointer.scaling.y = distance;
  81505. this._laserPointer.position.z = -distance / 2;
  81506. };
  81507. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81508. _super.prototype.dispose.call(this);
  81509. this._laserPointer.dispose();
  81510. };
  81511. return VRExperienceHelperControllerGazer;
  81512. }(VRExperienceHelperGazer));
  81513. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81514. __extends(VRExperienceHelperCameraGazer, _super);
  81515. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81516. var _this = _super.call(this, scene) || this;
  81517. _this.getCamera = getCamera;
  81518. return _this;
  81519. }
  81520. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81521. var camera = this.getCamera();
  81522. if (camera) {
  81523. return camera.getForwardRay(length);
  81524. }
  81525. else {
  81526. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81527. }
  81528. };
  81529. return VRExperienceHelperCameraGazer;
  81530. }(VRExperienceHelperGazer));
  81531. /**
  81532. * Helps to quickly add VR support to an existing scene.
  81533. * See http://doc.babylonjs.com/how_to/webvr_helper
  81534. */
  81535. var VRExperienceHelper = /** @class */ (function () {
  81536. /**
  81537. * Instantiates a VRExperienceHelper.
  81538. * Helps to quickly add VR support to an existing scene.
  81539. * @param scene The scene the VRExperienceHelper belongs to.
  81540. * @param webVROptions Options to modify the vr experience helper's behavior.
  81541. */
  81542. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81543. if (webVROptions === void 0) { webVROptions = {}; }
  81544. var _this = this;
  81545. this.webVROptions = webVROptions;
  81546. // Can the system support WebVR, even if a headset isn't plugged in?
  81547. this._webVRsupported = false;
  81548. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81549. this._webVRready = false;
  81550. // Are we waiting for the requestPresent callback to complete?
  81551. this._webVRrequesting = false;
  81552. // Are we presenting to the headset right now?
  81553. this._webVRpresenting = false;
  81554. // Are we presenting in the fullscreen fallback?
  81555. this._fullscreenVRpresenting = false;
  81556. /**
  81557. * Observable raised when entering VR.
  81558. */
  81559. this.onEnteringVRObservable = new BABYLON.Observable();
  81560. /**
  81561. * Observable raised when exiting VR.
  81562. */
  81563. this.onExitingVRObservable = new BABYLON.Observable();
  81564. /**
  81565. * Observable raised when controller mesh is loaded.
  81566. */
  81567. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81568. this._useCustomVRButton = false;
  81569. this._teleportationRequested = false;
  81570. this._teleportActive = false;
  81571. this._floorMeshesCollection = [];
  81572. this._rotationAllowed = true;
  81573. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81574. this._rotationRightAsked = false;
  81575. this._rotationLeftAsked = false;
  81576. this._isDefaultTeleportationTarget = true;
  81577. this._teleportationFillColor = "#444444";
  81578. this._teleportationBorderColor = "#FFFFFF";
  81579. this._rotationAngle = 0;
  81580. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81581. this._padSensibilityUp = 0.65;
  81582. this._padSensibilityDown = 0.35;
  81583. this.leftController = null;
  81584. this.rightController = null;
  81585. /**
  81586. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81587. */
  81588. this.onNewMeshSelected = new BABYLON.Observable();
  81589. /**
  81590. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81591. */
  81592. this.onNewMeshPicked = new BABYLON.Observable();
  81593. /**
  81594. * Observable raised before camera teleportation
  81595. */
  81596. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81597. /**
  81598. * Observable raised after camera teleportation
  81599. */
  81600. this.onAfterCameraTeleport = new BABYLON.Observable();
  81601. /**
  81602. * Observable raised when current selected mesh gets unselected
  81603. */
  81604. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81605. /**
  81606. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81607. */
  81608. this.teleportationEnabled = true;
  81609. this._teleportationInitialized = false;
  81610. this._interactionsEnabled = false;
  81611. this._interactionsRequested = false;
  81612. this._displayGaze = true;
  81613. this._displayLaserPointer = true;
  81614. this._onResize = function () {
  81615. _this.moveButtonToBottomRight();
  81616. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81617. _this.exitVR();
  81618. }
  81619. };
  81620. this._onFullscreenChange = function () {
  81621. if (document.fullscreen !== undefined) {
  81622. _this._fullscreenVRpresenting = document.fullscreen;
  81623. }
  81624. else if (document.mozFullScreen !== undefined) {
  81625. _this._fullscreenVRpresenting = document.mozFullScreen;
  81626. }
  81627. else if (document.webkitIsFullScreen !== undefined) {
  81628. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81629. }
  81630. else if (document.msIsFullScreen !== undefined) {
  81631. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81632. }
  81633. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81634. _this.exitVR();
  81635. if (!_this._useCustomVRButton) {
  81636. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81637. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81638. }
  81639. }
  81640. };
  81641. this.beforeRender = function () {
  81642. if (_this.leftController && _this.leftController._activePointer) {
  81643. _this._castRayAndSelectObject(_this.leftController);
  81644. }
  81645. if (_this.rightController && _this.rightController._activePointer) {
  81646. _this._castRayAndSelectObject(_this.rightController);
  81647. }
  81648. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81649. _this._castRayAndSelectObject(_this._cameraGazer);
  81650. }
  81651. else {
  81652. _this._cameraGazer._gazeTracker.isVisible = false;
  81653. }
  81654. };
  81655. this._onNewGamepadConnected = function (gamepad) {
  81656. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81657. if (gamepad.leftStick) {
  81658. gamepad.onleftstickchanged(function (stickValues) {
  81659. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81660. // Listening to classic/xbox gamepad only if no VR controller is active
  81661. if ((!_this.leftController && !_this.rightController) ||
  81662. ((_this.leftController && !_this.leftController._activePointer) &&
  81663. (_this.rightController && !_this.rightController._activePointer))) {
  81664. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81665. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81666. }
  81667. }
  81668. });
  81669. }
  81670. if (gamepad.rightStick) {
  81671. gamepad.onrightstickchanged(function (stickValues) {
  81672. if (_this._teleportationInitialized) {
  81673. _this._checkRotate(stickValues, _this._cameraGazer);
  81674. }
  81675. });
  81676. }
  81677. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81678. gamepad.onbuttondown(function (buttonPressed) {
  81679. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81680. _this._cameraGazer._selectionPointerDown();
  81681. }
  81682. });
  81683. gamepad.onbuttonup(function (buttonPressed) {
  81684. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81685. _this._cameraGazer._selectionPointerUp();
  81686. }
  81687. });
  81688. }
  81689. }
  81690. else {
  81691. var webVRController = gamepad;
  81692. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81693. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81694. _this.rightController = controller;
  81695. }
  81696. else {
  81697. _this.leftController = controller;
  81698. }
  81699. _this._tryEnableInteractionOnController(controller);
  81700. }
  81701. };
  81702. // 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
  81703. this._tryEnableInteractionOnController = function (controller) {
  81704. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81705. _this._enableInteractionOnController(controller);
  81706. }
  81707. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81708. _this._enableTeleportationOnController(controller);
  81709. }
  81710. };
  81711. this._onNewGamepadDisconnected = function (gamepad) {
  81712. if (gamepad instanceof BABYLON.WebVRController) {
  81713. if (gamepad.hand === "left" && _this.leftController != null) {
  81714. _this.leftController.dispose();
  81715. _this.leftController = null;
  81716. }
  81717. if (gamepad.hand === "right" && _this.rightController != null) {
  81718. _this.rightController.dispose();
  81719. _this.rightController = null;
  81720. }
  81721. }
  81722. };
  81723. this._workingVector = BABYLON.Vector3.Zero();
  81724. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81725. this._workingMatrix = BABYLON.Matrix.Identity();
  81726. this._scene = scene;
  81727. this._canvas = scene.getEngine().getRenderingCanvas();
  81728. // Parse options
  81729. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81730. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81731. }
  81732. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81733. webVROptions.createDeviceOrientationCamera = true;
  81734. }
  81735. if (webVROptions.defaultHeight === undefined) {
  81736. webVROptions.defaultHeight = 1.7;
  81737. }
  81738. if (webVROptions.useCustomVRButton) {
  81739. this._useCustomVRButton = true;
  81740. if (webVROptions.customVRButton) {
  81741. this._btnVR = webVROptions.customVRButton;
  81742. }
  81743. }
  81744. if (webVROptions.rayLength) {
  81745. this._rayLength = webVROptions.rayLength;
  81746. }
  81747. this._defaultHeight = webVROptions.defaultHeight;
  81748. if (webVROptions.positionScale) {
  81749. this._rayLength *= webVROptions.positionScale;
  81750. this._defaultHeight *= webVROptions.positionScale;
  81751. }
  81752. // Set position
  81753. if (this._scene.activeCamera) {
  81754. this._position = this._scene.activeCamera.position.clone();
  81755. }
  81756. else {
  81757. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81758. }
  81759. // Set non-vr camera
  81760. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81761. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81762. // Copy data from existing camera
  81763. if (this._scene.activeCamera) {
  81764. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81765. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81766. // Set rotation from previous camera
  81767. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81768. var targetCamera = this._scene.activeCamera;
  81769. if (targetCamera.rotationQuaternion) {
  81770. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81771. }
  81772. else {
  81773. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81774. }
  81775. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81776. }
  81777. }
  81778. this._scene.activeCamera = this._deviceOrientationCamera;
  81779. if (this._canvas) {
  81780. this._scene.activeCamera.attachControl(this._canvas);
  81781. }
  81782. }
  81783. else {
  81784. this._existingCamera = this._scene.activeCamera;
  81785. }
  81786. // Create VR cameras
  81787. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81788. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81789. }
  81790. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81791. this._webVRCamera.useStandingMatrix();
  81792. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81793. // Create default button
  81794. if (!this._useCustomVRButton) {
  81795. this._btnVR = document.createElement("BUTTON");
  81796. this._btnVR.className = "babylonVRicon";
  81797. this._btnVR.id = "babylonVRiconbtn";
  81798. this._btnVR.title = "Click to switch to VR";
  81799. 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) }";
  81800. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81801. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81802. // css += ".babylonVRicon.vrdisplaysupported { }";
  81803. // css += ".babylonVRicon.vrdisplayready { }";
  81804. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81805. var style = document.createElement('style');
  81806. style.appendChild(document.createTextNode(css));
  81807. document.getElementsByTagName('head')[0].appendChild(style);
  81808. this.moveButtonToBottomRight();
  81809. }
  81810. // VR button click event
  81811. if (this._btnVR) {
  81812. this._btnVR.addEventListener("click", function () {
  81813. if (!_this.isInVRMode) {
  81814. _this.enterVR();
  81815. }
  81816. else {
  81817. _this.exitVR();
  81818. }
  81819. });
  81820. }
  81821. // Window events
  81822. window.addEventListener("resize", this._onResize);
  81823. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81824. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81825. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81826. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81827. // Display vr button when headset is connected
  81828. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81829. this.displayVRButton();
  81830. }
  81831. else {
  81832. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81833. if (e.vrDisplay) {
  81834. _this.displayVRButton();
  81835. }
  81836. });
  81837. }
  81838. // Exiting VR mode using 'ESC' key on desktop
  81839. this._onKeyDown = function (event) {
  81840. if (event.keyCode === 27 && _this.isInVRMode) {
  81841. _this.exitVR();
  81842. }
  81843. };
  81844. document.addEventListener("keydown", this._onKeyDown);
  81845. // Exiting VR mode double tapping the touch screen
  81846. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81847. if (_this.isInVRMode) {
  81848. _this.exitVR();
  81849. if (_this._fullscreenVRpresenting) {
  81850. _this._scene.getEngine().switchFullscreen(true);
  81851. }
  81852. }
  81853. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81854. // Listen for WebVR display changes
  81855. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81856. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81857. this._onVRRequestPresentStart = function () {
  81858. _this._webVRrequesting = true;
  81859. _this.updateButtonVisibility();
  81860. };
  81861. this._onVRRequestPresentComplete = function (success) {
  81862. _this._webVRrequesting = false;
  81863. _this.updateButtonVisibility();
  81864. };
  81865. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81866. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81867. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81868. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81869. scene.onDisposeObservable.add(function () {
  81870. _this.dispose();
  81871. });
  81872. // Gamepad connection events
  81873. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81874. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81875. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81876. this.updateButtonVisibility();
  81877. //create easing functions
  81878. this._circleEase = new BABYLON.CircleEase();
  81879. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81880. }
  81881. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81882. /** Return this.onEnteringVRObservable
  81883. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81884. */
  81885. get: function () {
  81886. return this.onEnteringVRObservable;
  81887. },
  81888. enumerable: true,
  81889. configurable: true
  81890. });
  81891. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81892. /** Return this.onExitingVRObservable
  81893. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81894. */
  81895. get: function () {
  81896. return this.onExitingVRObservable;
  81897. },
  81898. enumerable: true,
  81899. configurable: true
  81900. });
  81901. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81902. /** Return this.onControllerMeshLoadedObservable
  81903. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81904. */
  81905. get: function () {
  81906. return this.onControllerMeshLoadedObservable;
  81907. },
  81908. enumerable: true,
  81909. configurable: true
  81910. });
  81911. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81912. /**
  81913. * The mesh used to display where the user is going to teleport.
  81914. */
  81915. get: function () {
  81916. return this._teleportationTarget;
  81917. },
  81918. /**
  81919. * Sets the mesh to be used to display where the user is going to teleport.
  81920. */
  81921. set: function (value) {
  81922. if (value) {
  81923. value.name = "teleportationTarget";
  81924. this._isDefaultTeleportationTarget = false;
  81925. this._teleportationTarget = value;
  81926. }
  81927. },
  81928. enumerable: true,
  81929. configurable: true
  81930. });
  81931. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81932. /**
  81933. * The mesh used to display where the user is selecting,
  81934. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81935. * See http://doc.babylonjs.com/resources/baking_transformations
  81936. */
  81937. get: function () {
  81938. return this._cameraGazer._gazeTracker;
  81939. },
  81940. set: function (value) {
  81941. if (value) {
  81942. this._cameraGazer._gazeTracker = value;
  81943. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81944. this._cameraGazer._gazeTracker.isPickable = false;
  81945. this._cameraGazer._gazeTracker.isVisible = false;
  81946. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81947. if (this.leftController) {
  81948. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81949. }
  81950. if (this.rightController) {
  81951. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81952. }
  81953. }
  81954. },
  81955. enumerable: true,
  81956. configurable: true
  81957. });
  81958. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81959. /**
  81960. * If the ray of the gaze should be displayed.
  81961. */
  81962. get: function () {
  81963. return this._displayGaze;
  81964. },
  81965. /**
  81966. * Sets if the ray of the gaze should be displayed.
  81967. */
  81968. set: function (value) {
  81969. this._displayGaze = value;
  81970. if (!value) {
  81971. this._cameraGazer._gazeTracker.isVisible = false;
  81972. if (this.leftController) {
  81973. this.leftController._gazeTracker.isVisible = false;
  81974. }
  81975. if (this.rightController) {
  81976. this.rightController._gazeTracker.isVisible = false;
  81977. }
  81978. }
  81979. },
  81980. enumerable: true,
  81981. configurable: true
  81982. });
  81983. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81984. /**
  81985. * If the ray of the LaserPointer should be displayed.
  81986. */
  81987. get: function () {
  81988. return this._displayLaserPointer;
  81989. },
  81990. /**
  81991. * Sets if the ray of the LaserPointer should be displayed.
  81992. */
  81993. set: function (value) {
  81994. this._displayLaserPointer = value;
  81995. if (!value) {
  81996. if (this.rightController) {
  81997. this.rightController._deactivatePointer();
  81998. this.rightController._gazeTracker.isVisible = false;
  81999. }
  82000. if (this.leftController) {
  82001. this.leftController._deactivatePointer();
  82002. this.leftController._gazeTracker.isVisible = false;
  82003. }
  82004. }
  82005. else {
  82006. if (this.rightController) {
  82007. this.rightController._activatePointer();
  82008. }
  82009. else if (this.leftController) {
  82010. this.leftController._activatePointer();
  82011. }
  82012. }
  82013. },
  82014. enumerable: true,
  82015. configurable: true
  82016. });
  82017. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82018. /**
  82019. * The deviceOrientationCamera used as the camera when not in VR.
  82020. */
  82021. get: function () {
  82022. return this._deviceOrientationCamera;
  82023. },
  82024. enumerable: true,
  82025. configurable: true
  82026. });
  82027. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82028. /**
  82029. * Based on the current WebVR support, returns the current VR camera used.
  82030. */
  82031. get: function () {
  82032. if (this._webVRready) {
  82033. return this._webVRCamera;
  82034. }
  82035. else {
  82036. return this._scene.activeCamera;
  82037. }
  82038. },
  82039. enumerable: true,
  82040. configurable: true
  82041. });
  82042. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82043. /**
  82044. * The webVRCamera which is used when in VR.
  82045. */
  82046. get: function () {
  82047. return this._webVRCamera;
  82048. },
  82049. enumerable: true,
  82050. configurable: true
  82051. });
  82052. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82053. /**
  82054. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82055. */
  82056. get: function () {
  82057. return this._vrDeviceOrientationCamera;
  82058. },
  82059. enumerable: true,
  82060. configurable: true
  82061. });
  82062. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82063. get: function () {
  82064. var result = this._cameraGazer._teleportationRequestInitiated
  82065. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82066. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82067. return result;
  82068. },
  82069. enumerable: true,
  82070. configurable: true
  82071. });
  82072. // Raised when one of the controller has loaded successfully its associated default mesh
  82073. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82074. if (this.leftController && this.leftController.webVRController == webVRController) {
  82075. if (webVRController.mesh) {
  82076. this.leftController._setLaserPointerParent(webVRController.mesh);
  82077. }
  82078. }
  82079. if (this.rightController && this.rightController.webVRController == webVRController) {
  82080. if (webVRController.mesh) {
  82081. this.rightController._setLaserPointerParent(webVRController.mesh);
  82082. }
  82083. }
  82084. try {
  82085. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82086. }
  82087. catch (err) {
  82088. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82089. }
  82090. };
  82091. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82092. /**
  82093. * Gets a value indicating if we are currently in VR mode.
  82094. */
  82095. get: function () {
  82096. return this._webVRpresenting || this._fullscreenVRpresenting;
  82097. },
  82098. enumerable: true,
  82099. configurable: true
  82100. });
  82101. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82102. var vrDisplay = this._scene.getEngine().getVRDevice();
  82103. if (vrDisplay) {
  82104. var wasPresenting = this._webVRpresenting;
  82105. // A VR display is connected
  82106. this._webVRpresenting = vrDisplay.isPresenting;
  82107. if (wasPresenting && !this._webVRpresenting)
  82108. this.exitVR();
  82109. }
  82110. else {
  82111. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82112. }
  82113. this.updateButtonVisibility();
  82114. };
  82115. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82116. this._webVRsupported = eventArgs.vrSupported;
  82117. this._webVRready = !!eventArgs.vrDisplay;
  82118. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82119. this.updateButtonVisibility();
  82120. };
  82121. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82122. if (this._canvas && !this._useCustomVRButton) {
  82123. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82124. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82125. }
  82126. };
  82127. VRExperienceHelper.prototype.displayVRButton = function () {
  82128. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82129. document.body.appendChild(this._btnVR);
  82130. this._btnVRDisplayed = true;
  82131. }
  82132. };
  82133. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82134. if (!this._btnVR || this._useCustomVRButton) {
  82135. return;
  82136. }
  82137. this._btnVR.className = "babylonVRicon";
  82138. if (this.isInVRMode) {
  82139. this._btnVR.className += " vrdisplaypresenting";
  82140. }
  82141. else {
  82142. if (this._webVRready)
  82143. this._btnVR.className += " vrdisplayready";
  82144. if (this._webVRsupported)
  82145. this._btnVR.className += " vrdisplaysupported";
  82146. if (this._webVRrequesting)
  82147. this._btnVR.className += " vrdisplayrequesting";
  82148. }
  82149. };
  82150. /**
  82151. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82152. * Otherwise, will use the fullscreen API.
  82153. */
  82154. VRExperienceHelper.prototype.enterVR = function () {
  82155. if (this.onEnteringVRObservable) {
  82156. try {
  82157. this.onEnteringVRObservable.notifyObservers(this);
  82158. }
  82159. catch (err) {
  82160. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82161. }
  82162. }
  82163. if (this._scene.activeCamera) {
  82164. this._position = this._scene.activeCamera.position.clone();
  82165. // make sure that we return to the last active camera
  82166. this._existingCamera = this._scene.activeCamera;
  82167. }
  82168. if (this._webVRrequesting)
  82169. return;
  82170. // If WebVR is supported and a headset is connected
  82171. if (this._webVRready) {
  82172. if (!this._webVRpresenting) {
  82173. this._webVRCamera.position = this._position;
  82174. this._scene.activeCamera = this._webVRCamera;
  82175. }
  82176. }
  82177. else if (this._vrDeviceOrientationCamera) {
  82178. this._vrDeviceOrientationCamera.position = this._position;
  82179. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82180. this._scene.getEngine().switchFullscreen(true);
  82181. this.updateButtonVisibility();
  82182. }
  82183. if (this._scene.activeCamera && this._canvas) {
  82184. this._scene.activeCamera.attachControl(this._canvas);
  82185. }
  82186. if (this._interactionsEnabled) {
  82187. this._scene.registerBeforeRender(this.beforeRender);
  82188. }
  82189. };
  82190. /**
  82191. * Attempt to exit VR, or fullscreen.
  82192. */
  82193. VRExperienceHelper.prototype.exitVR = function () {
  82194. if (this.onExitingVRObservable) {
  82195. try {
  82196. this.onExitingVRObservable.notifyObservers(this);
  82197. }
  82198. catch (err) {
  82199. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82200. }
  82201. }
  82202. if (this._webVRpresenting) {
  82203. this._scene.getEngine().disableVR();
  82204. }
  82205. if (this._scene.activeCamera) {
  82206. this._position = this._scene.activeCamera.position.clone();
  82207. }
  82208. if (this._deviceOrientationCamera) {
  82209. this._deviceOrientationCamera.position = this._position;
  82210. this._scene.activeCamera = this._deviceOrientationCamera;
  82211. if (this._canvas) {
  82212. this._scene.activeCamera.attachControl(this._canvas);
  82213. }
  82214. }
  82215. else if (this._existingCamera) {
  82216. this._existingCamera.position = this._position;
  82217. this._scene.activeCamera = this._existingCamera;
  82218. }
  82219. this.updateButtonVisibility();
  82220. if (this._interactionsEnabled) {
  82221. this._scene.unregisterBeforeRender(this.beforeRender);
  82222. }
  82223. };
  82224. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82225. /**
  82226. * The position of the vr experience helper.
  82227. */
  82228. get: function () {
  82229. return this._position;
  82230. },
  82231. /**
  82232. * Sets the position of the vr experience helper.
  82233. */
  82234. set: function (value) {
  82235. this._position = value;
  82236. if (this._scene.activeCamera) {
  82237. this._scene.activeCamera.position = value;
  82238. }
  82239. },
  82240. enumerable: true,
  82241. configurable: true
  82242. });
  82243. /**
  82244. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82245. */
  82246. VRExperienceHelper.prototype.enableInteractions = function () {
  82247. var _this = this;
  82248. if (!this._interactionsEnabled) {
  82249. this._interactionsRequested = true;
  82250. if (this.leftController) {
  82251. this._enableInteractionOnController(this.leftController);
  82252. }
  82253. if (this.rightController) {
  82254. this._enableInteractionOnController(this.rightController);
  82255. }
  82256. this.raySelectionPredicate = function (mesh) {
  82257. return mesh.isVisible;
  82258. };
  82259. this.meshSelectionPredicate = function (mesh) {
  82260. return true;
  82261. };
  82262. this._raySelectionPredicate = function (mesh) {
  82263. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82264. && mesh.name.indexOf("teleportationTarget") === -1
  82265. && mesh.name.indexOf("torusTeleportation") === -1
  82266. && mesh.name.indexOf("laserPointer") === -1)) {
  82267. return _this.raySelectionPredicate(mesh);
  82268. }
  82269. return false;
  82270. };
  82271. this._interactionsEnabled = true;
  82272. }
  82273. };
  82274. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82275. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82276. if (this._floorMeshesCollection[i].id === mesh.id) {
  82277. return true;
  82278. }
  82279. }
  82280. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82281. return true;
  82282. }
  82283. return false;
  82284. };
  82285. /**
  82286. * Adds a floor mesh to be used for teleportation.
  82287. * @param floorMesh the mesh to be used for teleportation.
  82288. */
  82289. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82290. if (!this._floorMeshesCollection) {
  82291. return;
  82292. }
  82293. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82294. return;
  82295. }
  82296. this._floorMeshesCollection.push(floorMesh);
  82297. };
  82298. /**
  82299. * Removes a floor mesh from being used for teleportation.
  82300. * @param floorMesh the mesh to be removed.
  82301. */
  82302. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82303. if (!this._floorMeshesCollection) {
  82304. return;
  82305. }
  82306. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82307. if (meshIndex !== -1) {
  82308. this._floorMeshesCollection.splice(meshIndex, 1);
  82309. }
  82310. };
  82311. /**
  82312. * Enables interactions and teleportation using the VR controllers and gaze.
  82313. * @param vrTeleportationOptions options to modify teleportation behavior.
  82314. */
  82315. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82316. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82317. if (!this._teleportationInitialized) {
  82318. this._teleportationRequested = true;
  82319. this.enableInteractions();
  82320. if (vrTeleportationOptions.floorMeshName) {
  82321. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82322. }
  82323. if (vrTeleportationOptions.floorMeshes) {
  82324. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82325. }
  82326. if (this.leftController != null) {
  82327. this._enableTeleportationOnController(this.leftController);
  82328. }
  82329. if (this.rightController != null) {
  82330. this._enableTeleportationOnController(this.rightController);
  82331. }
  82332. // Creates an image processing post process for the vignette not relying
  82333. // on the main scene configuration for image processing to reduce setup and spaces
  82334. // (gamma/linear) conflicts.
  82335. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82336. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82337. imageProcessingConfiguration.vignetteEnabled = true;
  82338. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82339. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82340. this._teleportationInitialized = true;
  82341. if (this._isDefaultTeleportationTarget) {
  82342. this._createTeleportationCircles();
  82343. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82344. }
  82345. }
  82346. };
  82347. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82348. var _this = this;
  82349. var controllerMesh = controller.webVRController.mesh;
  82350. if (controllerMesh) {
  82351. controller._interactionsEnabled = true;
  82352. controller._activatePointer();
  82353. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82354. // Enabling / disabling laserPointer
  82355. if (_this._displayLaserPointer && stateObject.value === 1) {
  82356. if (controller._activePointer) {
  82357. controller._deactivatePointer();
  82358. }
  82359. else {
  82360. controller._activatePointer();
  82361. }
  82362. if (_this.displayGaze) {
  82363. controller._gazeTracker.isVisible = controller._activePointer;
  82364. }
  82365. }
  82366. });
  82367. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82368. if (!controller._pointerDownOnMeshAsked) {
  82369. if (stateObject.value > _this._padSensibilityUp) {
  82370. controller._selectionPointerDown();
  82371. }
  82372. }
  82373. else if (stateObject.value < _this._padSensibilityDown) {
  82374. controller._selectionPointerUp();
  82375. }
  82376. });
  82377. }
  82378. };
  82379. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82380. // Dont teleport if another gaze already requested teleportation
  82381. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82382. return;
  82383. }
  82384. if (!gazer._teleportationRequestInitiated) {
  82385. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82386. gazer._activatePointer();
  82387. gazer._teleportationRequestInitiated = true;
  82388. }
  82389. }
  82390. else {
  82391. // Listening to the proper controller values changes to confirm teleportation
  82392. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82393. if (this._teleportActive) {
  82394. this._teleportCamera(this._haloCenter);
  82395. }
  82396. gazer._teleportationRequestInitiated = false;
  82397. }
  82398. }
  82399. };
  82400. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82401. // Only rotate when user is not currently selecting a teleportation location
  82402. if (gazer._teleportationRequestInitiated) {
  82403. return;
  82404. }
  82405. if (!this._rotationLeftAsked) {
  82406. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82407. this._rotationLeftAsked = true;
  82408. if (this._rotationAllowed) {
  82409. this._rotateCamera(false);
  82410. }
  82411. }
  82412. }
  82413. else {
  82414. if (stateObject.x > -this._padSensibilityDown) {
  82415. this._rotationLeftAsked = false;
  82416. }
  82417. }
  82418. if (!this._rotationRightAsked) {
  82419. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82420. this._rotationRightAsked = true;
  82421. if (this._rotationAllowed) {
  82422. this._rotateCamera(true);
  82423. }
  82424. }
  82425. }
  82426. else {
  82427. if (stateObject.x < this._padSensibilityDown) {
  82428. this._rotationRightAsked = false;
  82429. }
  82430. }
  82431. };
  82432. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82433. // Only teleport backwards when user is not currently selecting a teleportation location
  82434. if (gazer._teleportationRequestInitiated) {
  82435. return;
  82436. }
  82437. // Teleport backwards
  82438. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82439. if (!gazer._teleportationBackRequestInitiated) {
  82440. if (!this.currentVRCamera) {
  82441. return;
  82442. }
  82443. // Get rotation and position of the current camera
  82444. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82445. var position = this.currentVRCamera.position;
  82446. // If the camera has device position, use that instead
  82447. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82448. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82449. position = this.currentVRCamera.devicePosition;
  82450. }
  82451. // Get matrix with only the y rotation of the device rotation
  82452. rotation.toEulerAnglesToRef(this._workingVector);
  82453. this._workingVector.z = 0;
  82454. this._workingVector.x = 0;
  82455. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82456. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82457. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82458. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82459. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82460. var ray = new BABYLON.Ray(position, this._workingVector);
  82461. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82462. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82463. this._teleportCamera(hit.pickedPoint);
  82464. }
  82465. gazer._teleportationBackRequestInitiated = true;
  82466. }
  82467. }
  82468. else {
  82469. gazer._teleportationBackRequestInitiated = false;
  82470. }
  82471. };
  82472. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82473. var _this = this;
  82474. var controllerMesh = controller.webVRController.mesh;
  82475. if (controllerMesh) {
  82476. if (!controller._interactionsEnabled) {
  82477. this._enableInteractionOnController(controller);
  82478. }
  82479. controller._interactionsEnabled = true;
  82480. controller._teleportationEnabled = true;
  82481. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82482. controller._dpadPressed = false;
  82483. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82484. controller._dpadPressed = stateObject.pressed;
  82485. if (!controller._dpadPressed) {
  82486. _this._rotationLeftAsked = false;
  82487. _this._rotationRightAsked = false;
  82488. controller._teleportationBackRequestInitiated = false;
  82489. }
  82490. });
  82491. }
  82492. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82493. if (_this.teleportationEnabled) {
  82494. _this._checkTeleportBackwards(stateObject, controller);
  82495. _this._checkTeleportWithRay(stateObject, controller);
  82496. }
  82497. _this._checkRotate(stateObject, controller);
  82498. });
  82499. }
  82500. };
  82501. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82502. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82503. this._teleportationTarget.isPickable = false;
  82504. var length = 512;
  82505. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82506. dynamicTexture.hasAlpha = true;
  82507. var context = dynamicTexture.getContext();
  82508. var centerX = length / 2;
  82509. var centerY = length / 2;
  82510. var radius = 200;
  82511. context.beginPath();
  82512. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82513. context.fillStyle = this._teleportationFillColor;
  82514. context.fill();
  82515. context.lineWidth = 10;
  82516. context.strokeStyle = this._teleportationBorderColor;
  82517. context.stroke();
  82518. context.closePath();
  82519. dynamicTexture.update();
  82520. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82521. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82522. this._teleportationTarget.material = teleportationCircleMaterial;
  82523. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82524. torus.isPickable = false;
  82525. torus.parent = this._teleportationTarget;
  82526. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82527. var keys = [];
  82528. keys.push({
  82529. frame: 0,
  82530. value: 0
  82531. });
  82532. keys.push({
  82533. frame: 30,
  82534. value: 0.4
  82535. });
  82536. keys.push({
  82537. frame: 60,
  82538. value: 0
  82539. });
  82540. animationInnerCircle.setKeys(keys);
  82541. var easingFunction = new BABYLON.SineEase();
  82542. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82543. animationInnerCircle.setEasingFunction(easingFunction);
  82544. torus.animations = [];
  82545. torus.animations.push(animationInnerCircle);
  82546. this._scene.beginAnimation(torus, 0, 60, true);
  82547. this._hideTeleportationTarget();
  82548. };
  82549. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82550. this._teleportActive = true;
  82551. if (this._teleportationInitialized) {
  82552. this._teleportationTarget.isVisible = true;
  82553. if (this._isDefaultTeleportationTarget) {
  82554. this._teleportationTarget.getChildren()[0].isVisible = true;
  82555. }
  82556. }
  82557. };
  82558. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82559. this._teleportActive = false;
  82560. if (this._teleportationInitialized) {
  82561. this._teleportationTarget.isVisible = false;
  82562. if (this._isDefaultTeleportationTarget) {
  82563. this._teleportationTarget.getChildren()[0].isVisible = false;
  82564. }
  82565. }
  82566. };
  82567. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82568. var _this = this;
  82569. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82570. return;
  82571. }
  82572. if (right) {
  82573. this._rotationAngle++;
  82574. }
  82575. else {
  82576. this._rotationAngle--;
  82577. }
  82578. this.currentVRCamera.animations = [];
  82579. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82580. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82581. var animationRotationKeys = [];
  82582. animationRotationKeys.push({
  82583. frame: 0,
  82584. value: this.currentVRCamera.rotationQuaternion
  82585. });
  82586. animationRotationKeys.push({
  82587. frame: 6,
  82588. value: target
  82589. });
  82590. animationRotation.setKeys(animationRotationKeys);
  82591. animationRotation.setEasingFunction(this._circleEase);
  82592. this.currentVRCamera.animations.push(animationRotation);
  82593. this._postProcessMove.animations = [];
  82594. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82595. var vignetteWeightKeys = [];
  82596. vignetteWeightKeys.push({
  82597. frame: 0,
  82598. value: 0
  82599. });
  82600. vignetteWeightKeys.push({
  82601. frame: 3,
  82602. value: 4
  82603. });
  82604. vignetteWeightKeys.push({
  82605. frame: 6,
  82606. value: 0
  82607. });
  82608. animationPP.setKeys(vignetteWeightKeys);
  82609. animationPP.setEasingFunction(this._circleEase);
  82610. this._postProcessMove.animations.push(animationPP);
  82611. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82612. var vignetteStretchKeys = [];
  82613. vignetteStretchKeys.push({
  82614. frame: 0,
  82615. value: 0
  82616. });
  82617. vignetteStretchKeys.push({
  82618. frame: 3,
  82619. value: 10
  82620. });
  82621. vignetteStretchKeys.push({
  82622. frame: 6,
  82623. value: 0
  82624. });
  82625. animationPP2.setKeys(vignetteStretchKeys);
  82626. animationPP2.setEasingFunction(this._circleEase);
  82627. this._postProcessMove.animations.push(animationPP2);
  82628. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82629. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82630. this._postProcessMove.samples = 4;
  82631. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82632. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82633. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82634. });
  82635. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82636. };
  82637. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82638. if (hit.pickedPoint) {
  82639. if (gazer._teleportationRequestInitiated) {
  82640. this._displayTeleportationTarget();
  82641. this._haloCenter.copyFrom(hit.pickedPoint);
  82642. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82643. }
  82644. var pickNormal = hit.getNormal(true, false);
  82645. if (pickNormal) {
  82646. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82647. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82648. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82649. }
  82650. this._teleportationTarget.position.y += 0.1;
  82651. }
  82652. };
  82653. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82654. var _this = this;
  82655. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82656. return;
  82657. }
  82658. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82659. // offset of the headset from the anchor.
  82660. if (this.webVRCamera.leftCamera) {
  82661. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82662. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82663. location.subtractToRef(this._workingVector, this._workingVector);
  82664. }
  82665. else {
  82666. this._workingVector.copyFrom(location);
  82667. }
  82668. // Add height to account for user's height offset
  82669. if (this.isInVRMode) {
  82670. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82671. }
  82672. else {
  82673. this._workingVector.y += this._defaultHeight;
  82674. }
  82675. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82676. // Create animation from the camera's position to the new location
  82677. this.currentVRCamera.animations = [];
  82678. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82679. var animationCameraTeleportationKeys = [{
  82680. frame: 0,
  82681. value: this.currentVRCamera.position
  82682. },
  82683. {
  82684. frame: 11,
  82685. value: this._workingVector
  82686. }
  82687. ];
  82688. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82689. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82690. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82691. this._postProcessMove.animations = [];
  82692. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82693. var vignetteWeightKeys = [];
  82694. vignetteWeightKeys.push({
  82695. frame: 0,
  82696. value: 0
  82697. });
  82698. vignetteWeightKeys.push({
  82699. frame: 5,
  82700. value: 8
  82701. });
  82702. vignetteWeightKeys.push({
  82703. frame: 11,
  82704. value: 0
  82705. });
  82706. animationPP.setKeys(vignetteWeightKeys);
  82707. this._postProcessMove.animations.push(animationPP);
  82708. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82709. var vignetteStretchKeys = [];
  82710. vignetteStretchKeys.push({
  82711. frame: 0,
  82712. value: 0
  82713. });
  82714. vignetteStretchKeys.push({
  82715. frame: 5,
  82716. value: 10
  82717. });
  82718. vignetteStretchKeys.push({
  82719. frame: 11,
  82720. value: 0
  82721. });
  82722. animationPP2.setKeys(vignetteStretchKeys);
  82723. this._postProcessMove.animations.push(animationPP2);
  82724. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82725. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82726. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82727. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82728. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82729. });
  82730. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82731. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82732. });
  82733. this._hideTeleportationTarget();
  82734. };
  82735. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82736. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82737. return;
  82738. }
  82739. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82740. // Moving the gazeTracker on the mesh face targetted
  82741. if (hit && hit.pickedPoint) {
  82742. if (this._displayGaze) {
  82743. var multiplier = 1;
  82744. gazer._gazeTracker.isVisible = true;
  82745. if (gazer._isActionableMesh) {
  82746. multiplier = 3;
  82747. }
  82748. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82749. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82750. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82751. var pickNormal = hit.getNormal();
  82752. // To avoid z-fighting
  82753. var deltaFighting = 0.002;
  82754. if (pickNormal) {
  82755. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82756. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82757. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82758. }
  82759. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82760. if (gazer._gazeTracker.position.x < 0) {
  82761. gazer._gazeTracker.position.x += deltaFighting;
  82762. }
  82763. else {
  82764. gazer._gazeTracker.position.x -= deltaFighting;
  82765. }
  82766. if (gazer._gazeTracker.position.y < 0) {
  82767. gazer._gazeTracker.position.y += deltaFighting;
  82768. }
  82769. else {
  82770. gazer._gazeTracker.position.y -= deltaFighting;
  82771. }
  82772. if (gazer._gazeTracker.position.z < 0) {
  82773. gazer._gazeTracker.position.z += deltaFighting;
  82774. }
  82775. else {
  82776. gazer._gazeTracker.position.z -= deltaFighting;
  82777. }
  82778. }
  82779. // Changing the size of the laser pointer based on the distance from the targetted point
  82780. gazer._updatePointerDistance(hit.distance);
  82781. }
  82782. else {
  82783. gazer._gazeTracker.isVisible = false;
  82784. }
  82785. if (hit && hit.pickedMesh) {
  82786. gazer._currentHit = hit;
  82787. if (gazer._pointerDownOnMeshAsked) {
  82788. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82789. }
  82790. // The object selected is the floor, we're in a teleportation scenario
  82791. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82792. // Moving the teleportation area to this targetted point
  82793. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82794. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82795. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82796. }
  82797. gazer._currentMeshSelected = null;
  82798. if (gazer._teleportationRequestInitiated) {
  82799. this._moveTeleportationSelectorTo(hit, gazer);
  82800. }
  82801. return;
  82802. }
  82803. // If not, we're in a selection scenario
  82804. //this._teleportationAllowed = false;
  82805. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82806. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82807. this.onNewMeshPicked.notifyObservers(hit);
  82808. gazer._currentMeshSelected = hit.pickedMesh;
  82809. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82810. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82811. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82812. gazer._isActionableMesh = true;
  82813. }
  82814. else {
  82815. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82816. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82817. gazer._isActionableMesh = false;
  82818. }
  82819. try {
  82820. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82821. }
  82822. catch (err) {
  82823. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82824. }
  82825. }
  82826. else {
  82827. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82828. gazer._currentMeshSelected = null;
  82829. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82830. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82831. }
  82832. }
  82833. }
  82834. else {
  82835. gazer._currentHit = null;
  82836. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82837. gazer._currentMeshSelected = null;
  82838. //this._teleportationAllowed = false;
  82839. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82840. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82841. }
  82842. };
  82843. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82844. if (mesh) {
  82845. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82846. }
  82847. };
  82848. /**
  82849. * Sets the color of the laser ray from the vr controllers.
  82850. * @param color new color for the ray.
  82851. */
  82852. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82853. if (this.leftController) {
  82854. this.leftController._setLaserPointerColor(color);
  82855. }
  82856. if (this.rightController) {
  82857. this.rightController._setLaserPointerColor(color);
  82858. }
  82859. };
  82860. /**
  82861. * Sets the color of the ray from the vr headsets gaze.
  82862. * @param color new color for the ray.
  82863. */
  82864. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82865. if (!this._cameraGazer._gazeTracker.material) {
  82866. return;
  82867. }
  82868. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82869. if (this.leftController) {
  82870. this.leftController._gazeTracker.material.emissiveColor = color;
  82871. }
  82872. if (this.rightController) {
  82873. this.rightController._gazeTracker.material.emissiveColor = color;
  82874. }
  82875. };
  82876. /**
  82877. * Exits VR and disposes of the vr experience helper
  82878. */
  82879. VRExperienceHelper.prototype.dispose = function () {
  82880. if (this.isInVRMode) {
  82881. this.exitVR();
  82882. }
  82883. if (this._postProcessMove) {
  82884. this._postProcessMove.dispose();
  82885. }
  82886. if (this._webVRCamera) {
  82887. this._webVRCamera.dispose();
  82888. }
  82889. if (this._vrDeviceOrientationCamera) {
  82890. this._vrDeviceOrientationCamera.dispose();
  82891. }
  82892. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82893. document.body.removeChild(this._btnVR);
  82894. }
  82895. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82896. this._deviceOrientationCamera.dispose();
  82897. }
  82898. if (this._cameraGazer) {
  82899. this._cameraGazer.dispose();
  82900. }
  82901. if (this.leftController) {
  82902. this.leftController.dispose();
  82903. }
  82904. if (this.rightController) {
  82905. this.rightController.dispose();
  82906. }
  82907. if (this._teleportationTarget) {
  82908. this._teleportationTarget.dispose();
  82909. }
  82910. this._floorMeshesCollection = [];
  82911. document.removeEventListener("keydown", this._onKeyDown);
  82912. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82913. window.removeEventListener("resize", this._onResize);
  82914. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82915. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82916. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82917. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82918. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82919. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82920. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82921. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82922. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82923. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82924. this._scene.unregisterBeforeRender(this.beforeRender);
  82925. };
  82926. /**
  82927. * Gets the name of the VRExperienceHelper class
  82928. * @returns "VRExperienceHelper"
  82929. */
  82930. VRExperienceHelper.prototype.getClassName = function () {
  82931. return "VRExperienceHelper";
  82932. };
  82933. return VRExperienceHelper;
  82934. }());
  82935. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82936. })(BABYLON || (BABYLON = {}));
  82937. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82938. // Mainly based on these 2 articles :
  82939. // 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
  82940. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82941. var BABYLON;
  82942. (function (BABYLON) {
  82943. var JoystickAxis;
  82944. (function (JoystickAxis) {
  82945. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82946. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82947. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82948. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82949. var VirtualJoystick = /** @class */ (function () {
  82950. function VirtualJoystick(leftJoystick) {
  82951. var _this = this;
  82952. if (leftJoystick) {
  82953. this._leftJoystick = true;
  82954. }
  82955. else {
  82956. this._leftJoystick = false;
  82957. }
  82958. VirtualJoystick._globalJoystickIndex++;
  82959. // By default left & right arrow keys are moving the X
  82960. // and up & down keys are moving the Y
  82961. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82962. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82963. this.reverseLeftRight = false;
  82964. this.reverseUpDown = false;
  82965. // collections of pointers
  82966. this._touches = new BABYLON.StringDictionary();
  82967. this.deltaPosition = BABYLON.Vector3.Zero();
  82968. this._joystickSensibility = 25;
  82969. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82970. this._onResize = function (evt) {
  82971. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82972. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82973. if (VirtualJoystick.vjCanvas) {
  82974. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82975. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82976. }
  82977. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82978. };
  82979. // injecting a canvas element on top of the canvas 3D game
  82980. if (!VirtualJoystick.vjCanvas) {
  82981. window.addEventListener("resize", this._onResize, false);
  82982. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82983. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82984. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82985. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82986. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82987. VirtualJoystick.vjCanvas.style.width = "100%";
  82988. VirtualJoystick.vjCanvas.style.height = "100%";
  82989. VirtualJoystick.vjCanvas.style.position = "absolute";
  82990. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82991. VirtualJoystick.vjCanvas.style.top = "0px";
  82992. VirtualJoystick.vjCanvas.style.left = "0px";
  82993. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82994. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82995. // Support for jQuery PEP polyfill
  82996. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82997. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82998. if (!context) {
  82999. throw new Error("Unable to create canvas for virtual joystick");
  83000. }
  83001. VirtualJoystick.vjCanvasContext = context;
  83002. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83003. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83004. document.body.appendChild(VirtualJoystick.vjCanvas);
  83005. }
  83006. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83007. this.pressed = false;
  83008. // default joystick color
  83009. this._joystickColor = "cyan";
  83010. this._joystickPointerID = -1;
  83011. // current joystick position
  83012. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83013. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83014. // origin joystick position
  83015. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83016. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83017. this._onPointerDownHandlerRef = function (evt) {
  83018. _this._onPointerDown(evt);
  83019. };
  83020. this._onPointerMoveHandlerRef = function (evt) {
  83021. _this._onPointerMove(evt);
  83022. };
  83023. this._onPointerUpHandlerRef = function (evt) {
  83024. _this._onPointerUp(evt);
  83025. };
  83026. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83027. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83028. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83029. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83030. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83031. evt.preventDefault(); // Disables system menu
  83032. }, false);
  83033. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83034. }
  83035. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83036. this._joystickSensibility = newJoystickSensibility;
  83037. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83038. };
  83039. VirtualJoystick.prototype._onPointerDown = function (e) {
  83040. var positionOnScreenCondition;
  83041. e.preventDefault();
  83042. if (this._leftJoystick === true) {
  83043. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83044. }
  83045. else {
  83046. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83047. }
  83048. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83049. // First contact will be dedicated to the virtual joystick
  83050. this._joystickPointerID = e.pointerId;
  83051. this._joystickPointerStartPos.x = e.clientX;
  83052. this._joystickPointerStartPos.y = e.clientY;
  83053. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83054. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83055. this._deltaJoystickVector.x = 0;
  83056. this._deltaJoystickVector.y = 0;
  83057. this.pressed = true;
  83058. this._touches.add(e.pointerId.toString(), e);
  83059. }
  83060. else {
  83061. // You can only trigger the action buttons with a joystick declared
  83062. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83063. this._action();
  83064. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83065. }
  83066. }
  83067. };
  83068. VirtualJoystick.prototype._onPointerMove = function (e) {
  83069. // If the current pointer is the one associated to the joystick (first touch contact)
  83070. if (this._joystickPointerID == e.pointerId) {
  83071. this._joystickPointerPos.x = e.clientX;
  83072. this._joystickPointerPos.y = e.clientY;
  83073. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83074. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83075. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83076. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83077. switch (this._axisTargetedByLeftAndRight) {
  83078. case JoystickAxis.X:
  83079. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83080. break;
  83081. case JoystickAxis.Y:
  83082. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83083. break;
  83084. case JoystickAxis.Z:
  83085. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83086. break;
  83087. }
  83088. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83089. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83090. switch (this._axisTargetedByUpAndDown) {
  83091. case JoystickAxis.X:
  83092. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83093. break;
  83094. case JoystickAxis.Y:
  83095. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83096. break;
  83097. case JoystickAxis.Z:
  83098. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83099. break;
  83100. }
  83101. }
  83102. else {
  83103. var data = this._touches.get(e.pointerId.toString());
  83104. if (data) {
  83105. data.x = e.clientX;
  83106. data.y = e.clientY;
  83107. }
  83108. }
  83109. };
  83110. VirtualJoystick.prototype._onPointerUp = function (e) {
  83111. if (this._joystickPointerID == e.pointerId) {
  83112. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83113. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83114. this._joystickPointerID = -1;
  83115. this.pressed = false;
  83116. }
  83117. else {
  83118. var touch = this._touches.get(e.pointerId.toString());
  83119. if (touch) {
  83120. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83121. }
  83122. }
  83123. this._deltaJoystickVector.x = 0;
  83124. this._deltaJoystickVector.y = 0;
  83125. this._touches.remove(e.pointerId.toString());
  83126. };
  83127. /**
  83128. * Change the color of the virtual joystick
  83129. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83130. */
  83131. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83132. this._joystickColor = newColor;
  83133. };
  83134. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83135. this._action = action;
  83136. };
  83137. // Define which axis you'd like to control for left & right
  83138. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83139. switch (axis) {
  83140. case JoystickAxis.X:
  83141. case JoystickAxis.Y:
  83142. case JoystickAxis.Z:
  83143. this._axisTargetedByLeftAndRight = axis;
  83144. break;
  83145. default:
  83146. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83147. break;
  83148. }
  83149. };
  83150. // Define which axis you'd like to control for up & down
  83151. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83152. switch (axis) {
  83153. case JoystickAxis.X:
  83154. case JoystickAxis.Y:
  83155. case JoystickAxis.Z:
  83156. this._axisTargetedByUpAndDown = axis;
  83157. break;
  83158. default:
  83159. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83160. break;
  83161. }
  83162. };
  83163. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83164. var _this = this;
  83165. if (this.pressed) {
  83166. this._touches.forEach(function (key, touch) {
  83167. if (touch.pointerId === _this._joystickPointerID) {
  83168. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83169. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83170. VirtualJoystick.vjCanvasContext.beginPath();
  83171. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83172. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83173. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83174. VirtualJoystick.vjCanvasContext.stroke();
  83175. VirtualJoystick.vjCanvasContext.closePath();
  83176. VirtualJoystick.vjCanvasContext.beginPath();
  83177. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83178. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83179. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83180. VirtualJoystick.vjCanvasContext.stroke();
  83181. VirtualJoystick.vjCanvasContext.closePath();
  83182. VirtualJoystick.vjCanvasContext.beginPath();
  83183. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83184. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83185. VirtualJoystick.vjCanvasContext.stroke();
  83186. VirtualJoystick.vjCanvasContext.closePath();
  83187. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83188. }
  83189. else {
  83190. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83191. VirtualJoystick.vjCanvasContext.beginPath();
  83192. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83193. VirtualJoystick.vjCanvasContext.beginPath();
  83194. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83195. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83196. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83197. VirtualJoystick.vjCanvasContext.stroke();
  83198. VirtualJoystick.vjCanvasContext.closePath();
  83199. touch.prevX = touch.x;
  83200. touch.prevY = touch.y;
  83201. }
  83202. ;
  83203. });
  83204. }
  83205. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83206. };
  83207. VirtualJoystick.prototype.releaseCanvas = function () {
  83208. if (VirtualJoystick.vjCanvas) {
  83209. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83210. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83211. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83212. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83213. window.removeEventListener("resize", this._onResize);
  83214. document.body.removeChild(VirtualJoystick.vjCanvas);
  83215. VirtualJoystick.vjCanvas = null;
  83216. }
  83217. };
  83218. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83219. VirtualJoystick._globalJoystickIndex = 0;
  83220. return VirtualJoystick;
  83221. }());
  83222. BABYLON.VirtualJoystick = VirtualJoystick;
  83223. })(BABYLON || (BABYLON = {}));
  83224. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83225. var BABYLON;
  83226. (function (BABYLON) {
  83227. // We're mainly based on the logic defined into the FreeCamera code
  83228. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83229. __extends(VirtualJoysticksCamera, _super);
  83230. function VirtualJoysticksCamera(name, position, scene) {
  83231. var _this = _super.call(this, name, position, scene) || this;
  83232. _this.inputs.addVirtualJoystick();
  83233. return _this;
  83234. }
  83235. VirtualJoysticksCamera.prototype.getClassName = function () {
  83236. return "VirtualJoysticksCamera";
  83237. };
  83238. return VirtualJoysticksCamera;
  83239. }(BABYLON.FreeCamera));
  83240. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83241. })(BABYLON || (BABYLON = {}));
  83242. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83243. var BABYLON;
  83244. (function (BABYLON) {
  83245. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83246. function FreeCameraVirtualJoystickInput() {
  83247. }
  83248. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83249. return this._leftjoystick;
  83250. };
  83251. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83252. return this._rightjoystick;
  83253. };
  83254. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83255. if (this._leftjoystick) {
  83256. var camera = this.camera;
  83257. var speed = camera._computeLocalCameraSpeed() * 50;
  83258. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83259. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83260. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83261. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83262. if (!this._leftjoystick.pressed) {
  83263. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83264. }
  83265. if (!this._rightjoystick.pressed) {
  83266. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83267. }
  83268. }
  83269. };
  83270. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83271. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83272. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83273. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83274. this._leftjoystick.setJoystickSensibility(0.15);
  83275. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83276. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83277. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83278. this._rightjoystick.reverseUpDown = true;
  83279. this._rightjoystick.setJoystickSensibility(0.05);
  83280. this._rightjoystick.setJoystickColor("yellow");
  83281. };
  83282. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83283. this._leftjoystick.releaseCanvas();
  83284. this._rightjoystick.releaseCanvas();
  83285. };
  83286. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83287. return "FreeCameraVirtualJoystickInput";
  83288. };
  83289. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83290. return "virtualJoystick";
  83291. };
  83292. return FreeCameraVirtualJoystickInput;
  83293. }());
  83294. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83295. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83296. })(BABYLON || (BABYLON = {}));
  83297. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83298. var BABYLON;
  83299. (function (BABYLON) {
  83300. var SimplificationSettings = /** @class */ (function () {
  83301. function SimplificationSettings(quality, distance, optimizeMesh) {
  83302. this.quality = quality;
  83303. this.distance = distance;
  83304. this.optimizeMesh = optimizeMesh;
  83305. }
  83306. return SimplificationSettings;
  83307. }());
  83308. BABYLON.SimplificationSettings = SimplificationSettings;
  83309. var SimplificationQueue = /** @class */ (function () {
  83310. function SimplificationQueue() {
  83311. this.running = false;
  83312. this._simplificationArray = [];
  83313. }
  83314. SimplificationQueue.prototype.addTask = function (task) {
  83315. this._simplificationArray.push(task);
  83316. };
  83317. SimplificationQueue.prototype.executeNext = function () {
  83318. var task = this._simplificationArray.pop();
  83319. if (task) {
  83320. this.running = true;
  83321. this.runSimplification(task);
  83322. }
  83323. else {
  83324. this.running = false;
  83325. }
  83326. };
  83327. SimplificationQueue.prototype.runSimplification = function (task) {
  83328. var _this = this;
  83329. if (task.parallelProcessing) {
  83330. //parallel simplifier
  83331. task.settings.forEach(function (setting) {
  83332. var simplifier = _this.getSimplifier(task);
  83333. simplifier.simplify(setting, function (newMesh) {
  83334. task.mesh.addLODLevel(setting.distance, newMesh);
  83335. newMesh.isVisible = true;
  83336. //check if it is the last
  83337. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83338. //all done, run the success callback.
  83339. task.successCallback();
  83340. }
  83341. _this.executeNext();
  83342. });
  83343. });
  83344. }
  83345. else {
  83346. //single simplifier.
  83347. var simplifier = this.getSimplifier(task);
  83348. var runDecimation = function (setting, callback) {
  83349. simplifier.simplify(setting, function (newMesh) {
  83350. task.mesh.addLODLevel(setting.distance, newMesh);
  83351. newMesh.isVisible = true;
  83352. //run the next quality level
  83353. callback();
  83354. });
  83355. };
  83356. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83357. runDecimation(task.settings[loop.index], function () {
  83358. loop.executeNext();
  83359. });
  83360. }, function () {
  83361. //execution ended, run the success callback.
  83362. if (task.successCallback) {
  83363. task.successCallback();
  83364. }
  83365. _this.executeNext();
  83366. });
  83367. }
  83368. };
  83369. SimplificationQueue.prototype.getSimplifier = function (task) {
  83370. switch (task.simplificationType) {
  83371. case SimplificationType.QUADRATIC:
  83372. default:
  83373. return new QuadraticErrorSimplification(task.mesh);
  83374. }
  83375. };
  83376. return SimplificationQueue;
  83377. }());
  83378. BABYLON.SimplificationQueue = SimplificationQueue;
  83379. /**
  83380. * The implemented types of simplification.
  83381. * At the moment only Quadratic Error Decimation is implemented.
  83382. */
  83383. var SimplificationType;
  83384. (function (SimplificationType) {
  83385. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83386. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83387. var DecimationTriangle = /** @class */ (function () {
  83388. function DecimationTriangle(vertices) {
  83389. this.vertices = vertices;
  83390. this.error = new Array(4);
  83391. this.deleted = false;
  83392. this.isDirty = false;
  83393. this.deletePending = false;
  83394. this.borderFactor = 0;
  83395. }
  83396. return DecimationTriangle;
  83397. }());
  83398. BABYLON.DecimationTriangle = DecimationTriangle;
  83399. var DecimationVertex = /** @class */ (function () {
  83400. function DecimationVertex(position, id) {
  83401. this.position = position;
  83402. this.id = id;
  83403. this.isBorder = true;
  83404. this.q = new QuadraticMatrix();
  83405. this.triangleCount = 0;
  83406. this.triangleStart = 0;
  83407. this.originalOffsets = [];
  83408. }
  83409. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83410. this.position.copyFrom(newPosition);
  83411. };
  83412. return DecimationVertex;
  83413. }());
  83414. BABYLON.DecimationVertex = DecimationVertex;
  83415. var QuadraticMatrix = /** @class */ (function () {
  83416. function QuadraticMatrix(data) {
  83417. this.data = new Array(10);
  83418. for (var i = 0; i < 10; ++i) {
  83419. if (data && data[i]) {
  83420. this.data[i] = data[i];
  83421. }
  83422. else {
  83423. this.data[i] = 0;
  83424. }
  83425. }
  83426. }
  83427. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83428. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83429. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83430. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83431. return det;
  83432. };
  83433. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83434. for (var i = 0; i < 10; ++i) {
  83435. this.data[i] += matrix.data[i];
  83436. }
  83437. };
  83438. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83439. for (var i = 0; i < 10; ++i) {
  83440. this.data[i] += data[i];
  83441. }
  83442. };
  83443. QuadraticMatrix.prototype.add = function (matrix) {
  83444. var m = new QuadraticMatrix();
  83445. for (var i = 0; i < 10; ++i) {
  83446. m.data[i] = this.data[i] + matrix.data[i];
  83447. }
  83448. return m;
  83449. };
  83450. QuadraticMatrix.FromData = function (a, b, c, d) {
  83451. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83452. };
  83453. //returning an array to avoid garbage collection
  83454. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83455. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83456. };
  83457. return QuadraticMatrix;
  83458. }());
  83459. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83460. var Reference = /** @class */ (function () {
  83461. function Reference(vertexId, triangleId) {
  83462. this.vertexId = vertexId;
  83463. this.triangleId = triangleId;
  83464. }
  83465. return Reference;
  83466. }());
  83467. BABYLON.Reference = Reference;
  83468. /**
  83469. * An implementation of the Quadratic Error simplification algorithm.
  83470. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83471. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83472. * @author RaananW
  83473. */
  83474. var QuadraticErrorSimplification = /** @class */ (function () {
  83475. function QuadraticErrorSimplification(_mesh) {
  83476. this._mesh = _mesh;
  83477. this.syncIterations = 5000;
  83478. this.aggressiveness = 7;
  83479. this.decimationIterations = 100;
  83480. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83481. }
  83482. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83483. var _this = this;
  83484. this.initDecimatedMesh();
  83485. //iterating through the submeshes array, one after the other.
  83486. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83487. _this.initWithMesh(loop.index, function () {
  83488. _this.runDecimation(settings, loop.index, function () {
  83489. loop.executeNext();
  83490. });
  83491. }, settings.optimizeMesh);
  83492. }, function () {
  83493. setTimeout(function () {
  83494. successCallback(_this._reconstructedMesh);
  83495. }, 0);
  83496. });
  83497. };
  83498. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83499. var _this = this;
  83500. var targetCount = ~~(this.triangles.length * settings.quality);
  83501. var deletedTriangles = 0;
  83502. var triangleCount = this.triangles.length;
  83503. var iterationFunction = function (iteration, callback) {
  83504. setTimeout(function () {
  83505. if (iteration % 5 === 0) {
  83506. _this.updateMesh(iteration === 0);
  83507. }
  83508. for (var i = 0; i < _this.triangles.length; ++i) {
  83509. _this.triangles[i].isDirty = false;
  83510. }
  83511. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83512. var trianglesIterator = function (i) {
  83513. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83514. var t = _this.triangles[tIdx];
  83515. if (!t)
  83516. return;
  83517. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83518. return;
  83519. }
  83520. for (var j = 0; j < 3; ++j) {
  83521. if (t.error[j] < threshold) {
  83522. var deleted0 = [];
  83523. var deleted1 = [];
  83524. var v0 = t.vertices[j];
  83525. var v1 = t.vertices[(j + 1) % 3];
  83526. if (v0.isBorder || v1.isBorder)
  83527. continue;
  83528. var p = BABYLON.Vector3.Zero();
  83529. var n = BABYLON.Vector3.Zero();
  83530. var uv = BABYLON.Vector2.Zero();
  83531. var color = new BABYLON.Color4(0, 0, 0, 1);
  83532. _this.calculateError(v0, v1, p, n, uv, color);
  83533. var delTr = new Array();
  83534. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83535. continue;
  83536. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83537. continue;
  83538. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83539. continue;
  83540. var uniqueArray = new Array();
  83541. delTr.forEach(function (deletedT) {
  83542. if (uniqueArray.indexOf(deletedT) === -1) {
  83543. deletedT.deletePending = true;
  83544. uniqueArray.push(deletedT);
  83545. }
  83546. });
  83547. if (uniqueArray.length % 2 !== 0) {
  83548. continue;
  83549. }
  83550. v0.q = v1.q.add(v0.q);
  83551. v0.updatePosition(p);
  83552. var tStart = _this.references.length;
  83553. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83554. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83555. var tCount = _this.references.length - tStart;
  83556. if (tCount <= v0.triangleCount) {
  83557. if (tCount) {
  83558. for (var c = 0; c < tCount; c++) {
  83559. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83560. }
  83561. }
  83562. }
  83563. else {
  83564. v0.triangleStart = tStart;
  83565. }
  83566. v0.triangleCount = tCount;
  83567. break;
  83568. }
  83569. }
  83570. };
  83571. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83572. }, 0);
  83573. };
  83574. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83575. if (triangleCount - deletedTriangles <= targetCount)
  83576. loop.breakLoop();
  83577. else {
  83578. iterationFunction(loop.index, function () {
  83579. loop.executeNext();
  83580. });
  83581. }
  83582. }, function () {
  83583. setTimeout(function () {
  83584. //reconstruct this part of the mesh
  83585. _this.reconstructMesh(submeshIndex);
  83586. successCallback();
  83587. }, 0);
  83588. });
  83589. };
  83590. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83591. var _this = this;
  83592. this.vertices = [];
  83593. this.triangles = [];
  83594. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83595. var indices = this._mesh.getIndices();
  83596. var submesh = this._mesh.subMeshes[submeshIndex];
  83597. var findInVertices = function (positionToSearch) {
  83598. if (optimizeMesh) {
  83599. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83600. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83601. return _this.vertices[ii];
  83602. }
  83603. }
  83604. }
  83605. return null;
  83606. };
  83607. var vertexReferences = [];
  83608. var vertexInit = function (i) {
  83609. if (!positionData) {
  83610. return;
  83611. }
  83612. var offset = i + submesh.verticesStart;
  83613. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83614. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83615. vertex.originalOffsets.push(offset);
  83616. if (vertex.id === _this.vertices.length) {
  83617. _this.vertices.push(vertex);
  83618. }
  83619. vertexReferences.push(vertex.id);
  83620. };
  83621. //var totalVertices = mesh.getTotalVertices();
  83622. var totalVertices = submesh.verticesCount;
  83623. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83624. var indicesInit = function (i) {
  83625. if (!indices) {
  83626. return;
  83627. }
  83628. var offset = (submesh.indexStart / 3) + i;
  83629. var pos = (offset * 3);
  83630. var i0 = indices[pos + 0];
  83631. var i1 = indices[pos + 1];
  83632. var i2 = indices[pos + 2];
  83633. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83634. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83635. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83636. var triangle = new DecimationTriangle([v0, v1, v2]);
  83637. triangle.originalOffset = pos;
  83638. _this.triangles.push(triangle);
  83639. };
  83640. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83641. _this.init(callback);
  83642. });
  83643. });
  83644. };
  83645. QuadraticErrorSimplification.prototype.init = function (callback) {
  83646. var _this = this;
  83647. var triangleInit1 = function (i) {
  83648. var t = _this.triangles[i];
  83649. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83650. for (var j = 0; j < 3; j++) {
  83651. 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))));
  83652. }
  83653. };
  83654. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83655. var triangleInit2 = function (i) {
  83656. var t = _this.triangles[i];
  83657. for (var j = 0; j < 3; ++j) {
  83658. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83659. }
  83660. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83661. };
  83662. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83663. callback();
  83664. });
  83665. });
  83666. };
  83667. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83668. var newTriangles = [];
  83669. var i;
  83670. for (i = 0; i < this.vertices.length; ++i) {
  83671. this.vertices[i].triangleCount = 0;
  83672. }
  83673. var t;
  83674. var j;
  83675. for (i = 0; i < this.triangles.length; ++i) {
  83676. if (!this.triangles[i].deleted) {
  83677. t = this.triangles[i];
  83678. for (j = 0; j < 3; ++j) {
  83679. t.vertices[j].triangleCount = 1;
  83680. }
  83681. newTriangles.push(t);
  83682. }
  83683. }
  83684. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83685. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83686. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83687. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83688. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83689. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83690. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83691. var vertexCount = 0;
  83692. for (i = 0; i < this.vertices.length; ++i) {
  83693. var vertex = this.vertices[i];
  83694. vertex.id = vertexCount;
  83695. if (vertex.triangleCount) {
  83696. vertex.originalOffsets.forEach(function (originalOffset) {
  83697. if (!normalData) {
  83698. return;
  83699. }
  83700. newPositionData.push(vertex.position.x);
  83701. newPositionData.push(vertex.position.y);
  83702. newPositionData.push(vertex.position.z);
  83703. newNormalData.push(normalData[originalOffset * 3]);
  83704. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83705. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83706. if (uvs && uvs.length) {
  83707. newUVsData.push(uvs[(originalOffset * 2)]);
  83708. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83709. }
  83710. else if (colorsData && colorsData.length) {
  83711. newColorsData.push(colorsData[(originalOffset * 4)]);
  83712. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83713. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83714. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83715. }
  83716. ++vertexCount;
  83717. });
  83718. }
  83719. }
  83720. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83721. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83722. var submeshesArray = this._reconstructedMesh.subMeshes;
  83723. this._reconstructedMesh.subMeshes = [];
  83724. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83725. var originalIndices = this._mesh.getIndices();
  83726. for (i = 0; i < newTriangles.length; ++i) {
  83727. t = newTriangles[i]; //now get the new referencing point for each vertex
  83728. [0, 1, 2].forEach(function (idx) {
  83729. var id = originalIndices[t.originalOffset + idx];
  83730. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83731. if (offset < 0)
  83732. offset = 0;
  83733. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83734. });
  83735. }
  83736. //overwriting the old vertex buffers and indices.
  83737. this._reconstructedMesh.setIndices(newIndicesArray);
  83738. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83739. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83740. if (newUVsData.length > 0)
  83741. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83742. if (newColorsData.length > 0)
  83743. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83744. //create submesh
  83745. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83746. if (submeshIndex > 0) {
  83747. this._reconstructedMesh.subMeshes = [];
  83748. submeshesArray.forEach(function (submesh) {
  83749. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83750. });
  83751. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83752. }
  83753. };
  83754. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83755. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83756. this._reconstructedMesh.material = this._mesh.material;
  83757. this._reconstructedMesh.parent = this._mesh.parent;
  83758. this._reconstructedMesh.isVisible = false;
  83759. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83760. };
  83761. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83762. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83763. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83764. if (t.deleted)
  83765. continue;
  83766. var s = this.references[vertex1.triangleStart + i].vertexId;
  83767. var v1 = t.vertices[(s + 1) % 3];
  83768. var v2 = t.vertices[(s + 2) % 3];
  83769. if ((v1 === vertex2 || v2 === vertex2)) {
  83770. deletedArray[i] = true;
  83771. delTr.push(t);
  83772. continue;
  83773. }
  83774. var d1 = v1.position.subtract(point);
  83775. d1 = d1.normalize();
  83776. var d2 = v2.position.subtract(point);
  83777. d2 = d2.normalize();
  83778. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83779. return true;
  83780. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83781. deletedArray[i] = false;
  83782. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83783. return true;
  83784. }
  83785. return false;
  83786. };
  83787. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83788. var newDeleted = deletedTriangles;
  83789. for (var i = 0; i < vertex.triangleCount; ++i) {
  83790. var ref = this.references[vertex.triangleStart + i];
  83791. var t = this.triangles[ref.triangleId];
  83792. if (t.deleted)
  83793. continue;
  83794. if (deletedArray[i] && t.deletePending) {
  83795. t.deleted = true;
  83796. newDeleted++;
  83797. continue;
  83798. }
  83799. t.vertices[ref.vertexId] = origVertex;
  83800. t.isDirty = true;
  83801. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83802. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83803. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83804. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83805. this.references.push(ref);
  83806. }
  83807. return newDeleted;
  83808. };
  83809. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83810. for (var i = 0; i < this.vertices.length; ++i) {
  83811. var vCount = [];
  83812. var vId = [];
  83813. var v = this.vertices[i];
  83814. var j;
  83815. for (j = 0; j < v.triangleCount; ++j) {
  83816. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83817. for (var ii = 0; ii < 3; ii++) {
  83818. var ofs = 0;
  83819. var vv = triangle.vertices[ii];
  83820. while (ofs < vCount.length) {
  83821. if (vId[ofs] === vv.id)
  83822. break;
  83823. ++ofs;
  83824. }
  83825. if (ofs === vCount.length) {
  83826. vCount.push(1);
  83827. vId.push(vv.id);
  83828. }
  83829. else {
  83830. vCount[ofs]++;
  83831. }
  83832. }
  83833. }
  83834. for (j = 0; j < vCount.length; ++j) {
  83835. if (vCount[j] === 1) {
  83836. this.vertices[vId[j]].isBorder = true;
  83837. }
  83838. else {
  83839. this.vertices[vId[j]].isBorder = false;
  83840. }
  83841. }
  83842. }
  83843. };
  83844. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83845. if (identifyBorders === void 0) { identifyBorders = false; }
  83846. var i;
  83847. if (!identifyBorders) {
  83848. var newTrianglesVector = [];
  83849. for (i = 0; i < this.triangles.length; ++i) {
  83850. if (!this.triangles[i].deleted) {
  83851. newTrianglesVector.push(this.triangles[i]);
  83852. }
  83853. }
  83854. this.triangles = newTrianglesVector;
  83855. }
  83856. for (i = 0; i < this.vertices.length; ++i) {
  83857. this.vertices[i].triangleCount = 0;
  83858. this.vertices[i].triangleStart = 0;
  83859. }
  83860. var t;
  83861. var j;
  83862. var v;
  83863. for (i = 0; i < this.triangles.length; ++i) {
  83864. t = this.triangles[i];
  83865. for (j = 0; j < 3; ++j) {
  83866. v = t.vertices[j];
  83867. v.triangleCount++;
  83868. }
  83869. }
  83870. var tStart = 0;
  83871. for (i = 0; i < this.vertices.length; ++i) {
  83872. this.vertices[i].triangleStart = tStart;
  83873. tStart += this.vertices[i].triangleCount;
  83874. this.vertices[i].triangleCount = 0;
  83875. }
  83876. var newReferences = new Array(this.triangles.length * 3);
  83877. for (i = 0; i < this.triangles.length; ++i) {
  83878. t = this.triangles[i];
  83879. for (j = 0; j < 3; ++j) {
  83880. v = t.vertices[j];
  83881. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83882. v.triangleCount++;
  83883. }
  83884. }
  83885. this.references = newReferences;
  83886. if (identifyBorders) {
  83887. this.identifyBorder();
  83888. }
  83889. };
  83890. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83891. var x = point.x;
  83892. var y = point.y;
  83893. var z = point.z;
  83894. 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
  83895. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83896. };
  83897. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83898. var q = vertex1.q.add(vertex2.q);
  83899. var border = vertex1.isBorder && vertex2.isBorder;
  83900. var error = 0;
  83901. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83902. if (qDet !== 0 && !border) {
  83903. if (!pointResult) {
  83904. pointResult = BABYLON.Vector3.Zero();
  83905. }
  83906. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83907. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83908. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83909. error = this.vertexError(q, pointResult);
  83910. }
  83911. else {
  83912. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83913. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83914. var error1 = this.vertexError(q, vertex1.position);
  83915. var error2 = this.vertexError(q, vertex2.position);
  83916. var error3 = this.vertexError(q, p3);
  83917. error = Math.min(error1, error2, error3);
  83918. if (error === error1) {
  83919. if (pointResult) {
  83920. pointResult.copyFrom(vertex1.position);
  83921. }
  83922. }
  83923. else if (error === error2) {
  83924. if (pointResult) {
  83925. pointResult.copyFrom(vertex2.position);
  83926. }
  83927. }
  83928. else {
  83929. if (pointResult) {
  83930. pointResult.copyFrom(p3);
  83931. }
  83932. }
  83933. }
  83934. return error;
  83935. };
  83936. return QuadraticErrorSimplification;
  83937. }());
  83938. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83939. })(BABYLON || (BABYLON = {}));
  83940. //# sourceMappingURL=babylon.meshSimplification.js.map
  83941. var BABYLON;
  83942. (function (BABYLON) {
  83943. var MeshLODLevel = /** @class */ (function () {
  83944. function MeshLODLevel(distance, mesh) {
  83945. this.distance = distance;
  83946. this.mesh = mesh;
  83947. }
  83948. return MeshLODLevel;
  83949. }());
  83950. BABYLON.MeshLODLevel = MeshLODLevel;
  83951. })(BABYLON || (BABYLON = {}));
  83952. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83953. var BABYLON;
  83954. (function (BABYLON) {
  83955. /**
  83956. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83957. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83958. */
  83959. var SceneOptimization = /** @class */ (function () {
  83960. /**
  83961. * Creates the SceneOptimization object
  83962. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83963. * @param desc defines the description associated with the optimization
  83964. */
  83965. function SceneOptimization(
  83966. /**
  83967. * Defines the priority of this optimization (0 by default which means first in the list)
  83968. */
  83969. priority) {
  83970. if (priority === void 0) { priority = 0; }
  83971. this.priority = priority;
  83972. }
  83973. /**
  83974. * Gets a string describing the action executed by the current optimization
  83975. * @returns description string
  83976. */
  83977. SceneOptimization.prototype.getDescription = function () {
  83978. return "";
  83979. };
  83980. /**
  83981. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83982. * @param scene defines the current scene where to apply this optimization
  83983. * @param optimizer defines the current optimizer
  83984. * @returns true if everything that can be done was applied
  83985. */
  83986. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83987. return true;
  83988. };
  83989. ;
  83990. return SceneOptimization;
  83991. }());
  83992. BABYLON.SceneOptimization = SceneOptimization;
  83993. /**
  83994. * Defines an optimization used to reduce the size of render target textures
  83995. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83996. */
  83997. var TextureOptimization = /** @class */ (function (_super) {
  83998. __extends(TextureOptimization, _super);
  83999. /**
  84000. * Creates the TextureOptimization object
  84001. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84002. * @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
  84003. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84004. */
  84005. function TextureOptimization(
  84006. /**
  84007. * Defines the priority of this optimization (0 by default which means first in the list)
  84008. */
  84009. priority,
  84010. /**
  84011. * 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
  84012. */
  84013. maximumSize,
  84014. /**
  84015. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84016. */
  84017. step) {
  84018. if (priority === void 0) { priority = 0; }
  84019. if (maximumSize === void 0) { maximumSize = 1024; }
  84020. if (step === void 0) { step = 0.5; }
  84021. var _this = _super.call(this, priority) || this;
  84022. _this.priority = priority;
  84023. _this.maximumSize = maximumSize;
  84024. _this.step = step;
  84025. return _this;
  84026. }
  84027. /**
  84028. * Gets a string describing the action executed by the current optimization
  84029. * @returns description string
  84030. */
  84031. TextureOptimization.prototype.getDescription = function () {
  84032. return "Reducing render target texture size to " + this.maximumSize;
  84033. };
  84034. /**
  84035. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84036. * @param scene defines the current scene where to apply this optimization
  84037. * @param optimizer defines the current optimizer
  84038. * @returns true if everything that can be done was applied
  84039. */
  84040. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84041. var allDone = true;
  84042. for (var index = 0; index < scene.textures.length; index++) {
  84043. var texture = scene.textures[index];
  84044. if (!texture.canRescale || texture.getContext) {
  84045. continue;
  84046. }
  84047. var currentSize = texture.getSize();
  84048. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84049. if (maxDimension > this.maximumSize) {
  84050. texture.scale(this.step);
  84051. allDone = false;
  84052. }
  84053. }
  84054. return allDone;
  84055. };
  84056. return TextureOptimization;
  84057. }(SceneOptimization));
  84058. BABYLON.TextureOptimization = TextureOptimization;
  84059. /**
  84060. * Defines an optimization used to increase or decrease the rendering resolution
  84061. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84062. */
  84063. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84064. __extends(HardwareScalingOptimization, _super);
  84065. /**
  84066. * Creates the HardwareScalingOptimization object
  84067. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84068. * @param maximumScale defines the maximum scale to use (2 by default)
  84069. * @param step defines the step to use between two passes (0.5 by default)
  84070. */
  84071. function HardwareScalingOptimization(
  84072. /**
  84073. * Defines the priority of this optimization (0 by default which means first in the list)
  84074. */
  84075. priority,
  84076. /**
  84077. * Defines the maximum scale to use (2 by default)
  84078. */
  84079. maximumScale,
  84080. /**
  84081. * Defines the step to use between two passes (0.5 by default)
  84082. */
  84083. step) {
  84084. if (priority === void 0) { priority = 0; }
  84085. if (maximumScale === void 0) { maximumScale = 2; }
  84086. if (step === void 0) { step = 0.25; }
  84087. var _this = _super.call(this, priority) || this;
  84088. _this.priority = priority;
  84089. _this.maximumScale = maximumScale;
  84090. _this.step = step;
  84091. _this._currentScale = -1;
  84092. _this._directionOffset = 1;
  84093. return _this;
  84094. }
  84095. /**
  84096. * Gets a string describing the action executed by the current optimization
  84097. * @return description string
  84098. */
  84099. HardwareScalingOptimization.prototype.getDescription = function () {
  84100. return "Setting hardware scaling level to " + this._currentScale;
  84101. };
  84102. /**
  84103. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84104. * @param scene defines the current scene where to apply this optimization
  84105. * @param optimizer defines the current optimizer
  84106. * @returns true if everything that can be done was applied
  84107. */
  84108. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84109. if (this._currentScale === -1) {
  84110. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84111. if (this._currentScale > this.maximumScale) {
  84112. this._directionOffset = -1;
  84113. }
  84114. }
  84115. this._currentScale += this._directionOffset * this.step;
  84116. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84117. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84118. };
  84119. ;
  84120. return HardwareScalingOptimization;
  84121. }(SceneOptimization));
  84122. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84123. /**
  84124. * Defines an optimization used to remove shadows
  84125. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84126. */
  84127. var ShadowsOptimization = /** @class */ (function (_super) {
  84128. __extends(ShadowsOptimization, _super);
  84129. function ShadowsOptimization() {
  84130. return _super !== null && _super.apply(this, arguments) || this;
  84131. }
  84132. /**
  84133. * Gets a string describing the action executed by the current optimization
  84134. * @return description string
  84135. */
  84136. ShadowsOptimization.prototype.getDescription = function () {
  84137. return "Turning shadows on/off";
  84138. };
  84139. /**
  84140. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84141. * @param scene defines the current scene where to apply this optimization
  84142. * @param optimizer defines the current optimizer
  84143. * @returns true if everything that can be done was applied
  84144. */
  84145. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84146. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84147. return true;
  84148. };
  84149. ;
  84150. return ShadowsOptimization;
  84151. }(SceneOptimization));
  84152. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84153. /**
  84154. * Defines an optimization used to turn post-processes off
  84155. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84156. */
  84157. var PostProcessesOptimization = /** @class */ (function (_super) {
  84158. __extends(PostProcessesOptimization, _super);
  84159. function PostProcessesOptimization() {
  84160. return _super !== null && _super.apply(this, arguments) || this;
  84161. }
  84162. /**
  84163. * Gets a string describing the action executed by the current optimization
  84164. * @return description string
  84165. */
  84166. PostProcessesOptimization.prototype.getDescription = function () {
  84167. return "Turning post-processes on/off";
  84168. };
  84169. /**
  84170. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84171. * @param scene defines the current scene where to apply this optimization
  84172. * @param optimizer defines the current optimizer
  84173. * @returns true if everything that can be done was applied
  84174. */
  84175. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84176. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84177. return true;
  84178. };
  84179. ;
  84180. return PostProcessesOptimization;
  84181. }(SceneOptimization));
  84182. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84183. /**
  84184. * Defines an optimization used to turn lens flares off
  84185. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84186. */
  84187. var LensFlaresOptimization = /** @class */ (function (_super) {
  84188. __extends(LensFlaresOptimization, _super);
  84189. function LensFlaresOptimization() {
  84190. return _super !== null && _super.apply(this, arguments) || this;
  84191. }
  84192. /**
  84193. * Gets a string describing the action executed by the current optimization
  84194. * @return description string
  84195. */
  84196. LensFlaresOptimization.prototype.getDescription = function () {
  84197. return "Turning lens flares on/off";
  84198. };
  84199. /**
  84200. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84201. * @param scene defines the current scene where to apply this optimization
  84202. * @param optimizer defines the current optimizer
  84203. * @returns true if everything that can be done was applied
  84204. */
  84205. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84206. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84207. return true;
  84208. };
  84209. ;
  84210. return LensFlaresOptimization;
  84211. }(SceneOptimization));
  84212. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84213. /**
  84214. * Defines an optimization based on user defined callback.
  84215. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84216. */
  84217. var CustomOptimization = /** @class */ (function (_super) {
  84218. __extends(CustomOptimization, _super);
  84219. function CustomOptimization() {
  84220. return _super !== null && _super.apply(this, arguments) || this;
  84221. }
  84222. /**
  84223. * Gets a string describing the action executed by the current optimization
  84224. * @returns description string
  84225. */
  84226. CustomOptimization.prototype.getDescription = function () {
  84227. if (this.onGetDescription) {
  84228. return this.onGetDescription();
  84229. }
  84230. return "Running user defined callback";
  84231. };
  84232. /**
  84233. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84234. * @param scene defines the current scene where to apply this optimization
  84235. * @param optimizer defines the current optimizer
  84236. * @returns true if everything that can be done was applied
  84237. */
  84238. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84239. if (this.onApply) {
  84240. return this.onApply(scene, optimizer);
  84241. }
  84242. return true;
  84243. };
  84244. ;
  84245. return CustomOptimization;
  84246. }(SceneOptimization));
  84247. BABYLON.CustomOptimization = CustomOptimization;
  84248. /**
  84249. * Defines an optimization used to turn particles off
  84250. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84251. */
  84252. var ParticlesOptimization = /** @class */ (function (_super) {
  84253. __extends(ParticlesOptimization, _super);
  84254. function ParticlesOptimization() {
  84255. return _super !== null && _super.apply(this, arguments) || this;
  84256. }
  84257. /**
  84258. * Gets a string describing the action executed by the current optimization
  84259. * @return description string
  84260. */
  84261. ParticlesOptimization.prototype.getDescription = function () {
  84262. return "Turning particles on/off";
  84263. };
  84264. /**
  84265. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84266. * @param scene defines the current scene where to apply this optimization
  84267. * @param optimizer defines the current optimizer
  84268. * @returns true if everything that can be done was applied
  84269. */
  84270. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84271. scene.particlesEnabled = optimizer.isInImprovementMode;
  84272. return true;
  84273. };
  84274. ;
  84275. return ParticlesOptimization;
  84276. }(SceneOptimization));
  84277. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84278. /**
  84279. * Defines an optimization used to turn render targets off
  84280. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84281. */
  84282. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84283. __extends(RenderTargetsOptimization, _super);
  84284. function RenderTargetsOptimization() {
  84285. return _super !== null && _super.apply(this, arguments) || this;
  84286. }
  84287. /**
  84288. * Gets a string describing the action executed by the current optimization
  84289. * @return description string
  84290. */
  84291. RenderTargetsOptimization.prototype.getDescription = function () {
  84292. return "Turning render targets off";
  84293. };
  84294. /**
  84295. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84296. * @param scene defines the current scene where to apply this optimization
  84297. * @param optimizer defines the current optimizer
  84298. * @returns true if everything that can be done was applied
  84299. */
  84300. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84301. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84302. return true;
  84303. };
  84304. ;
  84305. return RenderTargetsOptimization;
  84306. }(SceneOptimization));
  84307. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84308. /**
  84309. * Defines an optimization used to merge meshes with compatible materials
  84310. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84311. */
  84312. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84313. __extends(MergeMeshesOptimization, _super);
  84314. function MergeMeshesOptimization() {
  84315. var _this = _super !== null && _super.apply(this, arguments) || this;
  84316. _this._canBeMerged = function (abstractMesh) {
  84317. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84318. return false;
  84319. }
  84320. var mesh = abstractMesh;
  84321. if (!mesh.isVisible || !mesh.isEnabled()) {
  84322. return false;
  84323. }
  84324. if (mesh.instances.length > 0) {
  84325. return false;
  84326. }
  84327. if (mesh.skeleton || mesh.hasLODLevels) {
  84328. return false;
  84329. }
  84330. if (mesh.parent) {
  84331. return false;
  84332. }
  84333. return true;
  84334. };
  84335. return _this;
  84336. }
  84337. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84338. /**
  84339. * Gets or sets a boolean which defines if optimization octree has to be updated
  84340. */
  84341. get: function () {
  84342. return MergeMeshesOptimization._UpdateSelectionTree;
  84343. },
  84344. /**
  84345. * Gets or sets a boolean which defines if optimization octree has to be updated
  84346. */
  84347. set: function (value) {
  84348. MergeMeshesOptimization._UpdateSelectionTree = value;
  84349. },
  84350. enumerable: true,
  84351. configurable: true
  84352. });
  84353. /**
  84354. * Gets a string describing the action executed by the current optimization
  84355. * @return description string
  84356. */
  84357. MergeMeshesOptimization.prototype.getDescription = function () {
  84358. return "Merging similar meshes together";
  84359. };
  84360. /**
  84361. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84362. * @param scene defines the current scene where to apply this optimization
  84363. * @param optimizer defines the current optimizer
  84364. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84365. * @returns true if everything that can be done was applied
  84366. */
  84367. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84368. var globalPool = scene.meshes.slice(0);
  84369. var globalLength = globalPool.length;
  84370. for (var index = 0; index < globalLength; index++) {
  84371. var currentPool = new Array();
  84372. var current = globalPool[index];
  84373. // Checks
  84374. if (!this._canBeMerged(current)) {
  84375. continue;
  84376. }
  84377. currentPool.push(current);
  84378. // Find compatible meshes
  84379. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84380. var otherMesh = globalPool[subIndex];
  84381. if (!this._canBeMerged(otherMesh)) {
  84382. continue;
  84383. }
  84384. if (otherMesh.material !== current.material) {
  84385. continue;
  84386. }
  84387. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84388. continue;
  84389. }
  84390. currentPool.push(otherMesh);
  84391. globalLength--;
  84392. globalPool.splice(subIndex, 1);
  84393. subIndex--;
  84394. }
  84395. if (currentPool.length < 2) {
  84396. continue;
  84397. }
  84398. // Merge meshes
  84399. BABYLON.Mesh.MergeMeshes(currentPool);
  84400. }
  84401. if (updateSelectionTree != undefined) {
  84402. if (updateSelectionTree) {
  84403. scene.createOrUpdateSelectionOctree();
  84404. }
  84405. }
  84406. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84407. scene.createOrUpdateSelectionOctree();
  84408. }
  84409. return true;
  84410. };
  84411. ;
  84412. MergeMeshesOptimization._UpdateSelectionTree = false;
  84413. return MergeMeshesOptimization;
  84414. }(SceneOptimization));
  84415. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84416. /**
  84417. * Defines a list of options used by SceneOptimizer
  84418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84419. */
  84420. var SceneOptimizerOptions = /** @class */ (function () {
  84421. /**
  84422. * Creates a new list of options used by SceneOptimizer
  84423. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84424. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84425. */
  84426. function SceneOptimizerOptions(
  84427. /**
  84428. * Defines the target frame rate to reach (60 by default)
  84429. */
  84430. targetFrameRate,
  84431. /**
  84432. * Defines the interval between two checkes (2000ms by default)
  84433. */
  84434. trackerDuration) {
  84435. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84436. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84437. this.targetFrameRate = targetFrameRate;
  84438. this.trackerDuration = trackerDuration;
  84439. /**
  84440. * Gets the list of optimizations to apply
  84441. */
  84442. this.optimizations = new Array();
  84443. }
  84444. /**
  84445. * Add a new optimization
  84446. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84447. * @returns the current SceneOptimizerOptions
  84448. */
  84449. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84450. this.optimizations.push(optimization);
  84451. return this;
  84452. };
  84453. /**
  84454. * Add a new custom optimization
  84455. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84456. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84457. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84458. * @returns the current SceneOptimizerOptions
  84459. */
  84460. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84461. if (priority === void 0) { priority = 0; }
  84462. var optimization = new CustomOptimization(priority);
  84463. optimization.onApply = onApply;
  84464. optimization.onGetDescription = onGetDescription;
  84465. this.optimizations.push(optimization);
  84466. return this;
  84467. };
  84468. /**
  84469. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84470. * @param targetFrameRate defines the target frame rate (60 by default)
  84471. * @returns a SceneOptimizerOptions object
  84472. */
  84473. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84474. var result = new SceneOptimizerOptions(targetFrameRate);
  84475. var priority = 0;
  84476. result.addOptimization(new MergeMeshesOptimization(priority));
  84477. result.addOptimization(new ShadowsOptimization(priority));
  84478. result.addOptimization(new LensFlaresOptimization(priority));
  84479. // Next priority
  84480. priority++;
  84481. result.addOptimization(new PostProcessesOptimization(priority));
  84482. result.addOptimization(new ParticlesOptimization(priority));
  84483. // Next priority
  84484. priority++;
  84485. result.addOptimization(new TextureOptimization(priority, 1024));
  84486. return result;
  84487. };
  84488. /**
  84489. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84490. * @param targetFrameRate defines the target frame rate (60 by default)
  84491. * @returns a SceneOptimizerOptions object
  84492. */
  84493. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84494. var result = new SceneOptimizerOptions(targetFrameRate);
  84495. var priority = 0;
  84496. result.addOptimization(new MergeMeshesOptimization(priority));
  84497. result.addOptimization(new ShadowsOptimization(priority));
  84498. result.addOptimization(new LensFlaresOptimization(priority));
  84499. // Next priority
  84500. priority++;
  84501. result.addOptimization(new PostProcessesOptimization(priority));
  84502. result.addOptimization(new ParticlesOptimization(priority));
  84503. // Next priority
  84504. priority++;
  84505. result.addOptimization(new TextureOptimization(priority, 512));
  84506. // Next priority
  84507. priority++;
  84508. result.addOptimization(new RenderTargetsOptimization(priority));
  84509. // Next priority
  84510. priority++;
  84511. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84512. return result;
  84513. };
  84514. /**
  84515. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84516. * @param targetFrameRate defines the target frame rate (60 by default)
  84517. * @returns a SceneOptimizerOptions object
  84518. */
  84519. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84520. var result = new SceneOptimizerOptions(targetFrameRate);
  84521. var priority = 0;
  84522. result.addOptimization(new MergeMeshesOptimization(priority));
  84523. result.addOptimization(new ShadowsOptimization(priority));
  84524. result.addOptimization(new LensFlaresOptimization(priority));
  84525. // Next priority
  84526. priority++;
  84527. result.addOptimization(new PostProcessesOptimization(priority));
  84528. result.addOptimization(new ParticlesOptimization(priority));
  84529. // Next priority
  84530. priority++;
  84531. result.addOptimization(new TextureOptimization(priority, 256));
  84532. // Next priority
  84533. priority++;
  84534. result.addOptimization(new RenderTargetsOptimization(priority));
  84535. // Next priority
  84536. priority++;
  84537. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84538. return result;
  84539. };
  84540. return SceneOptimizerOptions;
  84541. }());
  84542. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84543. /**
  84544. * Class used to run optimizations in order to reach a target frame rate
  84545. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84546. */
  84547. var SceneOptimizer = /** @class */ (function () {
  84548. /**
  84549. * Creates a new SceneOptimizer
  84550. * @param scene defines the scene to work on
  84551. * @param options defines the options to use with the SceneOptimizer
  84552. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84553. * @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)
  84554. */
  84555. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84556. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84557. if (improvementMode === void 0) { improvementMode = false; }
  84558. var _this = this;
  84559. this._isRunning = false;
  84560. this._currentPriorityLevel = 0;
  84561. this._targetFrameRate = 60;
  84562. this._trackerDuration = 2000;
  84563. this._currentFrameRate = 0;
  84564. this._improvementMode = false;
  84565. /**
  84566. * Defines an observable called when the optimizer reaches the target frame rate
  84567. */
  84568. this.onSuccessObservable = new BABYLON.Observable();
  84569. /**
  84570. * Defines an observable called when the optimizer enables an optimization
  84571. */
  84572. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84573. /**
  84574. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84575. */
  84576. this.onFailureObservable = new BABYLON.Observable();
  84577. if (!options) {
  84578. this._options = new SceneOptimizerOptions();
  84579. }
  84580. else {
  84581. this._options = options;
  84582. }
  84583. if (this._options.targetFrameRate) {
  84584. this._targetFrameRate = this._options.targetFrameRate;
  84585. }
  84586. if (this._options.trackerDuration) {
  84587. this._trackerDuration = this._options.trackerDuration;
  84588. }
  84589. if (autoGeneratePriorities) {
  84590. var priority = 0;
  84591. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84592. var optim = _a[_i];
  84593. optim.priority = priority++;
  84594. }
  84595. }
  84596. this._improvementMode = improvementMode;
  84597. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84598. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84599. _this._sceneDisposeObserver = null;
  84600. _this.dispose();
  84601. });
  84602. }
  84603. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84604. /**
  84605. * Gets a boolean indicating if the optimizer is in improvement mode
  84606. */
  84607. get: function () {
  84608. return this._improvementMode;
  84609. },
  84610. enumerable: true,
  84611. configurable: true
  84612. });
  84613. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84614. /**
  84615. * Gets the current priority level (0 at start)
  84616. */
  84617. get: function () {
  84618. return this._currentPriorityLevel;
  84619. },
  84620. enumerable: true,
  84621. configurable: true
  84622. });
  84623. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84624. /**
  84625. * Gets the current frame rate checked by the SceneOptimizer
  84626. */
  84627. get: function () {
  84628. return this._currentFrameRate;
  84629. },
  84630. enumerable: true,
  84631. configurable: true
  84632. });
  84633. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84634. /**
  84635. * Gets or sets the current target frame rate (60 by default)
  84636. */
  84637. get: function () {
  84638. return this._targetFrameRate;
  84639. },
  84640. /**
  84641. * Gets or sets the current target frame rate (60 by default)
  84642. */
  84643. set: function (value) {
  84644. this._targetFrameRate = value;
  84645. },
  84646. enumerable: true,
  84647. configurable: true
  84648. });
  84649. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84650. /**
  84651. * Gets or sets the current interval between two checks (every 2000ms by default)
  84652. */
  84653. get: function () {
  84654. return this._trackerDuration;
  84655. },
  84656. /**
  84657. * Gets or sets the current interval between two checks (every 2000ms by default)
  84658. */
  84659. set: function (value) {
  84660. this._trackerDuration = value;
  84661. },
  84662. enumerable: true,
  84663. configurable: true
  84664. });
  84665. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84666. /**
  84667. * Gets the list of active optimizations
  84668. */
  84669. get: function () {
  84670. return this._options.optimizations;
  84671. },
  84672. enumerable: true,
  84673. configurable: true
  84674. });
  84675. /**
  84676. * Stops the current optimizer
  84677. */
  84678. SceneOptimizer.prototype.stop = function () {
  84679. this._isRunning = false;
  84680. };
  84681. /**
  84682. * Reset the optimizer to initial step (current priority level = 0)
  84683. */
  84684. SceneOptimizer.prototype.reset = function () {
  84685. this._currentPriorityLevel = 0;
  84686. };
  84687. /**
  84688. * Start the optimizer. By default it will try to reach a specific framerate
  84689. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84690. */
  84691. SceneOptimizer.prototype.start = function () {
  84692. var _this = this;
  84693. if (this._isRunning) {
  84694. return;
  84695. }
  84696. this._isRunning = true;
  84697. // Let's wait for the scene to be ready before running our check
  84698. this._scene.executeWhenReady(function () {
  84699. setTimeout(function () {
  84700. _this._checkCurrentState();
  84701. }, _this._trackerDuration);
  84702. });
  84703. };
  84704. SceneOptimizer.prototype._checkCurrentState = function () {
  84705. var _this = this;
  84706. if (!this._isRunning) {
  84707. return;
  84708. }
  84709. var scene = this._scene;
  84710. var options = this._options;
  84711. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84712. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84713. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84714. this._isRunning = false;
  84715. this.onSuccessObservable.notifyObservers(this);
  84716. return;
  84717. }
  84718. // Apply current level of optimizations
  84719. var allDone = true;
  84720. var noOptimizationApplied = true;
  84721. for (var index = 0; index < options.optimizations.length; index++) {
  84722. var optimization = options.optimizations[index];
  84723. if (optimization.priority === this._currentPriorityLevel) {
  84724. noOptimizationApplied = false;
  84725. allDone = allDone && optimization.apply(scene, this);
  84726. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84727. }
  84728. }
  84729. // If no optimization was applied, this is a failure :(
  84730. if (noOptimizationApplied) {
  84731. this._isRunning = false;
  84732. this.onFailureObservable.notifyObservers(this);
  84733. return;
  84734. }
  84735. // If all optimizations were done, move to next level
  84736. if (allDone) {
  84737. this._currentPriorityLevel++;
  84738. }
  84739. // Let's the system running for a specific amount of time before checking FPS
  84740. scene.executeWhenReady(function () {
  84741. setTimeout(function () {
  84742. _this._checkCurrentState();
  84743. }, _this._trackerDuration);
  84744. });
  84745. };
  84746. /**
  84747. * Release all resources
  84748. */
  84749. SceneOptimizer.prototype.dispose = function () {
  84750. this.stop();
  84751. this.onSuccessObservable.clear();
  84752. this.onFailureObservable.clear();
  84753. this.onNewOptimizationAppliedObservable.clear();
  84754. if (this._sceneDisposeObserver) {
  84755. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84756. }
  84757. };
  84758. /**
  84759. * Helper function to create a SceneOptimizer with one single line of code
  84760. * @param scene defines the scene to work on
  84761. * @param options defines the options to use with the SceneOptimizer
  84762. * @param onSuccess defines a callback to call on success
  84763. * @param onFailure defines a callback to call on failure
  84764. * @returns the new SceneOptimizer object
  84765. */
  84766. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84767. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84768. if (onSuccess) {
  84769. optimizer.onSuccessObservable.add(function () {
  84770. onSuccess();
  84771. });
  84772. }
  84773. if (onFailure) {
  84774. optimizer.onFailureObservable.add(function () {
  84775. onFailure();
  84776. });
  84777. }
  84778. optimizer.start();
  84779. return optimizer;
  84780. };
  84781. return SceneOptimizer;
  84782. }());
  84783. BABYLON.SceneOptimizer = SceneOptimizer;
  84784. })(BABYLON || (BABYLON = {}));
  84785. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84786. var BABYLON;
  84787. (function (BABYLON) {
  84788. var OutlineRenderer = /** @class */ (function () {
  84789. function OutlineRenderer(scene) {
  84790. this.zOffset = 1;
  84791. this._scene = scene;
  84792. }
  84793. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84794. var _this = this;
  84795. if (useOverlay === void 0) { useOverlay = false; }
  84796. var scene = this._scene;
  84797. var engine = this._scene.getEngine();
  84798. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84799. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84800. return;
  84801. }
  84802. var mesh = subMesh.getRenderingMesh();
  84803. var material = subMesh.getMaterial();
  84804. if (!material || !scene.activeCamera) {
  84805. return;
  84806. }
  84807. engine.enableEffect(this._effect);
  84808. // Logarithmic depth
  84809. if (material.useLogarithmicDepth) {
  84810. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84811. }
  84812. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84813. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84814. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84815. // Bones
  84816. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84817. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84818. }
  84819. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84820. // Alpha test
  84821. if (material && material.needAlphaTesting()) {
  84822. var alphaTexture = material.getAlphaTestTexture();
  84823. if (alphaTexture) {
  84824. this._effect.setTexture("diffuseSampler", alphaTexture);
  84825. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84826. }
  84827. }
  84828. engine.setZOffset(-this.zOffset);
  84829. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84830. engine.setZOffset(0);
  84831. };
  84832. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84833. var defines = [];
  84834. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84835. var mesh = subMesh.getMesh();
  84836. var material = subMesh.getMaterial();
  84837. if (material) {
  84838. // Alpha test
  84839. if (material.needAlphaTesting()) {
  84840. defines.push("#define ALPHATEST");
  84841. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84842. attribs.push(BABYLON.VertexBuffer.UVKind);
  84843. defines.push("#define UV1");
  84844. }
  84845. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84846. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84847. defines.push("#define UV2");
  84848. }
  84849. }
  84850. //Logarithmic depth
  84851. if (material.useLogarithmicDepth) {
  84852. defines.push("#define LOGARITHMICDEPTH");
  84853. }
  84854. }
  84855. // Bones
  84856. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84859. if (mesh.numBoneInfluencers > 4) {
  84860. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84861. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84862. }
  84863. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84864. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84865. }
  84866. else {
  84867. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84868. }
  84869. // Instances
  84870. if (useInstances) {
  84871. defines.push("#define INSTANCES");
  84872. attribs.push("world0");
  84873. attribs.push("world1");
  84874. attribs.push("world2");
  84875. attribs.push("world3");
  84876. }
  84877. // Get correct effect
  84878. var join = defines.join("\n");
  84879. if (this._cachedDefines !== join) {
  84880. this._cachedDefines = join;
  84881. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84882. }
  84883. return this._effect.isReady();
  84884. };
  84885. return OutlineRenderer;
  84886. }());
  84887. BABYLON.OutlineRenderer = OutlineRenderer;
  84888. })(BABYLON || (BABYLON = {}));
  84889. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84890. var BABYLON;
  84891. (function (BABYLON) {
  84892. var FaceAdjacencies = /** @class */ (function () {
  84893. function FaceAdjacencies() {
  84894. this.edges = new Array();
  84895. this.edgesConnectedCount = 0;
  84896. }
  84897. return FaceAdjacencies;
  84898. }());
  84899. var EdgesRenderer = /** @class */ (function () {
  84900. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84901. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84902. if (epsilon === void 0) { epsilon = 0.95; }
  84903. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84904. this.edgesWidthScalerForOrthographic = 1000.0;
  84905. this.edgesWidthScalerForPerspective = 50.0;
  84906. this._linesPositions = new Array();
  84907. this._linesNormals = new Array();
  84908. this._linesIndices = new Array();
  84909. this._buffers = {};
  84910. this._checkVerticesInsteadOfIndices = false;
  84911. this._source = source;
  84912. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84913. this._epsilon = epsilon;
  84914. this._prepareRessources();
  84915. this._generateEdgesLines();
  84916. }
  84917. EdgesRenderer.prototype._prepareRessources = function () {
  84918. if (this._lineShader) {
  84919. return;
  84920. }
  84921. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84922. attributes: ["position", "normal"],
  84923. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84924. });
  84925. this._lineShader.disableDepthWrite = true;
  84926. this._lineShader.backFaceCulling = false;
  84927. };
  84928. EdgesRenderer.prototype._rebuild = function () {
  84929. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84930. if (buffer) {
  84931. buffer._rebuild();
  84932. }
  84933. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84934. if (buffer) {
  84935. buffer._rebuild();
  84936. }
  84937. var scene = this._source.getScene();
  84938. var engine = scene.getEngine();
  84939. this._ib = engine.createIndexBuffer(this._linesIndices);
  84940. };
  84941. EdgesRenderer.prototype.dispose = function () {
  84942. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84943. if (buffer) {
  84944. buffer.dispose();
  84945. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84946. }
  84947. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84948. if (buffer) {
  84949. buffer.dispose();
  84950. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84951. }
  84952. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84953. this._lineShader.dispose();
  84954. };
  84955. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84956. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84957. return 0;
  84958. }
  84959. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84960. return 1;
  84961. }
  84962. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84963. return 2;
  84964. }
  84965. return -1;
  84966. };
  84967. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84968. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84969. return 0;
  84970. }
  84971. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84972. return 1;
  84973. }
  84974. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84975. return 2;
  84976. }
  84977. return -1;
  84978. };
  84979. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84980. var needToCreateLine;
  84981. if (edge === undefined) {
  84982. needToCreateLine = true;
  84983. }
  84984. else {
  84985. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84986. needToCreateLine = dotProduct < this._epsilon;
  84987. }
  84988. if (needToCreateLine) {
  84989. var offset = this._linesPositions.length / 3;
  84990. var normal = p0.subtract(p1);
  84991. normal.normalize();
  84992. // Positions
  84993. this._linesPositions.push(p0.x);
  84994. this._linesPositions.push(p0.y);
  84995. this._linesPositions.push(p0.z);
  84996. this._linesPositions.push(p0.x);
  84997. this._linesPositions.push(p0.y);
  84998. this._linesPositions.push(p0.z);
  84999. this._linesPositions.push(p1.x);
  85000. this._linesPositions.push(p1.y);
  85001. this._linesPositions.push(p1.z);
  85002. this._linesPositions.push(p1.x);
  85003. this._linesPositions.push(p1.y);
  85004. this._linesPositions.push(p1.z);
  85005. // Normals
  85006. this._linesNormals.push(p1.x);
  85007. this._linesNormals.push(p1.y);
  85008. this._linesNormals.push(p1.z);
  85009. this._linesNormals.push(-1);
  85010. this._linesNormals.push(p1.x);
  85011. this._linesNormals.push(p1.y);
  85012. this._linesNormals.push(p1.z);
  85013. this._linesNormals.push(1);
  85014. this._linesNormals.push(p0.x);
  85015. this._linesNormals.push(p0.y);
  85016. this._linesNormals.push(p0.z);
  85017. this._linesNormals.push(-1);
  85018. this._linesNormals.push(p0.x);
  85019. this._linesNormals.push(p0.y);
  85020. this._linesNormals.push(p0.z);
  85021. this._linesNormals.push(1);
  85022. // Indices
  85023. this._linesIndices.push(offset);
  85024. this._linesIndices.push(offset + 1);
  85025. this._linesIndices.push(offset + 2);
  85026. this._linesIndices.push(offset);
  85027. this._linesIndices.push(offset + 2);
  85028. this._linesIndices.push(offset + 3);
  85029. }
  85030. };
  85031. EdgesRenderer.prototype._generateEdgesLines = function () {
  85032. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85033. var indices = this._source.getIndices();
  85034. if (!indices || !positions) {
  85035. return;
  85036. }
  85037. // First let's find adjacencies
  85038. var adjacencies = new Array();
  85039. var faceNormals = new Array();
  85040. var index;
  85041. var faceAdjacencies;
  85042. // Prepare faces
  85043. for (index = 0; index < indices.length; index += 3) {
  85044. faceAdjacencies = new FaceAdjacencies();
  85045. var p0Index = indices[index];
  85046. var p1Index = indices[index + 1];
  85047. var p2Index = indices[index + 2];
  85048. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85049. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85050. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85051. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85052. faceNormal.normalize();
  85053. faceNormals.push(faceNormal);
  85054. adjacencies.push(faceAdjacencies);
  85055. }
  85056. // Scan
  85057. for (index = 0; index < adjacencies.length; index++) {
  85058. faceAdjacencies = adjacencies[index];
  85059. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85060. var otherFaceAdjacencies = adjacencies[otherIndex];
  85061. if (faceAdjacencies.edgesConnectedCount === 3) {
  85062. break;
  85063. }
  85064. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85065. continue;
  85066. }
  85067. var otherP0 = indices[otherIndex * 3];
  85068. var otherP1 = indices[otherIndex * 3 + 1];
  85069. var otherP2 = indices[otherIndex * 3 + 2];
  85070. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85071. var otherEdgeIndex = 0;
  85072. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85073. continue;
  85074. }
  85075. switch (edgeIndex) {
  85076. case 0:
  85077. if (this._checkVerticesInsteadOfIndices) {
  85078. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85079. }
  85080. else {
  85081. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85082. }
  85083. break;
  85084. case 1:
  85085. if (this._checkVerticesInsteadOfIndices) {
  85086. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85087. }
  85088. else {
  85089. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85090. }
  85091. break;
  85092. case 2:
  85093. if (this._checkVerticesInsteadOfIndices) {
  85094. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85095. }
  85096. else {
  85097. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85098. }
  85099. break;
  85100. }
  85101. if (otherEdgeIndex === -1) {
  85102. continue;
  85103. }
  85104. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85105. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85106. faceAdjacencies.edgesConnectedCount++;
  85107. otherFaceAdjacencies.edgesConnectedCount++;
  85108. if (faceAdjacencies.edgesConnectedCount === 3) {
  85109. break;
  85110. }
  85111. }
  85112. }
  85113. }
  85114. // Create lines
  85115. for (index = 0; index < adjacencies.length; index++) {
  85116. // 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
  85117. var current = adjacencies[index];
  85118. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85119. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85120. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85121. }
  85122. // Merge into a single mesh
  85123. var engine = this._source.getScene().getEngine();
  85124. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85125. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85126. this._ib = engine.createIndexBuffer(this._linesIndices);
  85127. this._indicesCount = this._linesIndices.length;
  85128. };
  85129. EdgesRenderer.prototype.render = function () {
  85130. var scene = this._source.getScene();
  85131. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85132. return;
  85133. }
  85134. var engine = scene.getEngine();
  85135. this._lineShader._preBind();
  85136. // VBOs
  85137. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85138. scene.resetCachedMaterial();
  85139. this._lineShader.setColor4("color", this._source.edgesColor);
  85140. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85141. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85142. }
  85143. else {
  85144. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85145. }
  85146. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85147. this._lineShader.bind(this._source.getWorldMatrix());
  85148. // Draw order
  85149. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85150. this._lineShader.unbind();
  85151. engine.setDepthWrite(true);
  85152. };
  85153. return EdgesRenderer;
  85154. }());
  85155. BABYLON.EdgesRenderer = EdgesRenderer;
  85156. })(BABYLON || (BABYLON = {}));
  85157. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85158. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85159. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85160. s = arguments[i];
  85161. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85162. t[p] = s[p];
  85163. }
  85164. return t;
  85165. };
  85166. var BABYLON;
  85167. (function (BABYLON) {
  85168. /**
  85169. * The effect layer Helps adding post process effect blended with the main pass.
  85170. *
  85171. * This can be for instance use to generate glow or higlight effects on the scene.
  85172. *
  85173. * The effect layer class can not be used directly and is intented to inherited from to be
  85174. * customized per effects.
  85175. */
  85176. var EffectLayer = /** @class */ (function () {
  85177. /**
  85178. * Instantiates a new effect Layer and references it in the scene.
  85179. * @param name The name of the layer
  85180. * @param scene The scene to use the layer in
  85181. */
  85182. function EffectLayer(
  85183. /** The Friendly of the effect in the scene */
  85184. name, scene) {
  85185. this.name = name;
  85186. this._vertexBuffers = {};
  85187. this._maxSize = 0;
  85188. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85189. this._shouldRender = true;
  85190. this._postProcesses = [];
  85191. this._textures = [];
  85192. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85193. /**
  85194. * The clear color of the texture used to generate the glow map.
  85195. */
  85196. this.neutralColor = new BABYLON.Color4();
  85197. /**
  85198. * Specifies wether the highlight layer is enabled or not.
  85199. */
  85200. this.isEnabled = true;
  85201. /**
  85202. * An event triggered when the effect layer has been disposed.
  85203. */
  85204. this.onDisposeObservable = new BABYLON.Observable();
  85205. /**
  85206. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85207. */
  85208. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85209. /**
  85210. * An event triggered when the generated texture is being merged in the scene.
  85211. */
  85212. this.onBeforeComposeObservable = new BABYLON.Observable();
  85213. /**
  85214. * An event triggered when the generated texture has been merged in the scene.
  85215. */
  85216. this.onAfterComposeObservable = new BABYLON.Observable();
  85217. /**
  85218. * An event triggered when the efffect layer changes its size.
  85219. */
  85220. this.onSizeChangedObservable = new BABYLON.Observable();
  85221. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85222. this._engine = scene.getEngine();
  85223. this._maxSize = this._engine.getCaps().maxTextureSize;
  85224. this._scene.effectLayers.push(this);
  85225. // Generate Buffers
  85226. this._generateIndexBuffer();
  85227. this._genrateVertexBuffer();
  85228. }
  85229. Object.defineProperty(EffectLayer.prototype, "camera", {
  85230. /**
  85231. * Gets the camera attached to the layer.
  85232. */
  85233. get: function () {
  85234. return this._effectLayerOptions.camera;
  85235. },
  85236. enumerable: true,
  85237. configurable: true
  85238. });
  85239. /**
  85240. * Initializes the effect layer with the required options.
  85241. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85242. */
  85243. EffectLayer.prototype._init = function (options) {
  85244. // Adapt options
  85245. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85246. this._setMainTextureSize();
  85247. this._createMainTexture();
  85248. this._createTextureAndPostProcesses();
  85249. this._mergeEffect = this._createMergeEffect();
  85250. };
  85251. /**
  85252. * Generates the index buffer of the full screen quad blending to the main canvas.
  85253. */
  85254. EffectLayer.prototype._generateIndexBuffer = function () {
  85255. // Indices
  85256. var indices = [];
  85257. indices.push(0);
  85258. indices.push(1);
  85259. indices.push(2);
  85260. indices.push(0);
  85261. indices.push(2);
  85262. indices.push(3);
  85263. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85264. };
  85265. /**
  85266. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85267. */
  85268. EffectLayer.prototype._genrateVertexBuffer = function () {
  85269. // VBO
  85270. var vertices = [];
  85271. vertices.push(1, 1);
  85272. vertices.push(-1, 1);
  85273. vertices.push(-1, -1);
  85274. vertices.push(1, -1);
  85275. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85277. };
  85278. /**
  85279. * Sets the main texture desired size which is the closest power of two
  85280. * of the engine canvas size.
  85281. */
  85282. EffectLayer.prototype._setMainTextureSize = function () {
  85283. if (this._effectLayerOptions.mainTextureFixedSize) {
  85284. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85285. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85286. }
  85287. else {
  85288. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85289. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85290. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85291. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85292. }
  85293. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85294. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85295. };
  85296. /**
  85297. * Creates the main texture for the effect layer.
  85298. */
  85299. EffectLayer.prototype._createMainTexture = function () {
  85300. var _this = this;
  85301. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85302. width: this._mainTextureDesiredSize.width,
  85303. height: this._mainTextureDesiredSize.height
  85304. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85305. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85306. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85307. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85308. this._mainTexture.anisotropicFilteringLevel = 1;
  85309. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85310. this._mainTexture.renderParticles = false;
  85311. this._mainTexture.renderList = null;
  85312. this._mainTexture.ignoreCameraViewport = true;
  85313. // Custom render function
  85314. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85315. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85316. var index;
  85317. var engine = _this._scene.getEngine();
  85318. if (depthOnlySubMeshes.length) {
  85319. engine.setColorWrite(false);
  85320. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85321. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85322. }
  85323. engine.setColorWrite(true);
  85324. }
  85325. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85326. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85327. }
  85328. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85329. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85330. }
  85331. for (index = 0; index < transparentSubMeshes.length; index++) {
  85332. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85333. }
  85334. };
  85335. this._mainTexture.onClearObservable.add(function (engine) {
  85336. engine.clear(_this.neutralColor, true, true, true);
  85337. });
  85338. };
  85339. /**
  85340. * Checks for the readiness of the element composing the layer.
  85341. * @param subMesh the mesh to check for
  85342. * @param useInstances specify wether or not to use instances to render the mesh
  85343. * @param emissiveTexture the associated emissive texture used to generate the glow
  85344. * @return true if ready otherwise, false
  85345. */
  85346. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85347. var material = subMesh.getMaterial();
  85348. if (!material) {
  85349. return false;
  85350. }
  85351. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85352. return false;
  85353. }
  85354. var defines = [];
  85355. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85356. var mesh = subMesh.getMesh();
  85357. var uv1 = false;
  85358. var uv2 = false;
  85359. // Alpha test
  85360. if (material && material.needAlphaTesting()) {
  85361. var alphaTexture = material.getAlphaTestTexture();
  85362. if (alphaTexture) {
  85363. defines.push("#define ALPHATEST");
  85364. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85365. alphaTexture.coordinatesIndex === 1) {
  85366. defines.push("#define DIFFUSEUV2");
  85367. uv2 = true;
  85368. }
  85369. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85370. defines.push("#define DIFFUSEUV1");
  85371. uv1 = true;
  85372. }
  85373. }
  85374. }
  85375. // Emissive
  85376. if (emissiveTexture) {
  85377. defines.push("#define EMISSIVE");
  85378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85379. emissiveTexture.coordinatesIndex === 1) {
  85380. defines.push("#define EMISSIVEUV2");
  85381. uv2 = true;
  85382. }
  85383. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85384. defines.push("#define EMISSIVEUV1");
  85385. uv1 = true;
  85386. }
  85387. }
  85388. if (uv1) {
  85389. attribs.push(BABYLON.VertexBuffer.UVKind);
  85390. defines.push("#define UV1");
  85391. }
  85392. if (uv2) {
  85393. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85394. defines.push("#define UV2");
  85395. }
  85396. // Bones
  85397. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85400. if (mesh.numBoneInfluencers > 4) {
  85401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85403. }
  85404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85405. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85406. }
  85407. else {
  85408. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85409. }
  85410. // Instances
  85411. if (useInstances) {
  85412. defines.push("#define INSTANCES");
  85413. attribs.push("world0");
  85414. attribs.push("world1");
  85415. attribs.push("world2");
  85416. attribs.push("world3");
  85417. }
  85418. // Get correct effect
  85419. var join = defines.join("\n");
  85420. if (this._cachedDefines !== join) {
  85421. this._cachedDefines = join;
  85422. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85423. }
  85424. return this._effectLayerMapGenerationEffect.isReady();
  85425. };
  85426. /**
  85427. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85428. */
  85429. EffectLayer.prototype.render = function () {
  85430. var currentEffect = this._mergeEffect;
  85431. // Check
  85432. if (!currentEffect.isReady())
  85433. return;
  85434. for (var i = 0; i < this._postProcesses.length; i++) {
  85435. if (!this._postProcesses[i].isReady()) {
  85436. return;
  85437. }
  85438. }
  85439. var engine = this._scene.getEngine();
  85440. this.onBeforeComposeObservable.notifyObservers(this);
  85441. // Render
  85442. engine.enableEffect(currentEffect);
  85443. engine.setState(false);
  85444. // VBOs
  85445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85446. // Cache
  85447. var previousAlphaMode = engine.getAlphaMode();
  85448. // Go Blend.
  85449. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85450. // Blends the map on the main canvas.
  85451. this._internalRender(currentEffect);
  85452. // Restore Alpha
  85453. engine.setAlphaMode(previousAlphaMode);
  85454. this.onAfterComposeObservable.notifyObservers(this);
  85455. // Handle size changes.
  85456. var size = this._mainTexture.getSize();
  85457. this._setMainTextureSize();
  85458. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85459. // Recreate RTT and post processes on size change.
  85460. this.onSizeChangedObservable.notifyObservers(this);
  85461. this._disposeTextureAndPostProcesses();
  85462. this._createMainTexture();
  85463. this._createTextureAndPostProcesses();
  85464. }
  85465. };
  85466. /**
  85467. * Determine if a given mesh will be used in the current effect.
  85468. * @param mesh mesh to test
  85469. * @returns true if the mesh will be used
  85470. */
  85471. EffectLayer.prototype.hasMesh = function (mesh) {
  85472. return true;
  85473. };
  85474. /**
  85475. * Returns true if the layer contains information to display, otherwise false.
  85476. * @returns true if the glow layer should be rendered
  85477. */
  85478. EffectLayer.prototype.shouldRender = function () {
  85479. return this.isEnabled && this._shouldRender;
  85480. };
  85481. /**
  85482. * Returns true if the mesh should render, otherwise false.
  85483. * @param mesh The mesh to render
  85484. * @returns true if it should render otherwise false
  85485. */
  85486. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85487. return true;
  85488. };
  85489. /**
  85490. * Returns true if the mesh should render, otherwise false.
  85491. * @param mesh The mesh to render
  85492. * @returns true if it should render otherwise false
  85493. */
  85494. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85495. return true;
  85496. };
  85497. /**
  85498. * Renders the submesh passed in parameter to the generation map.
  85499. */
  85500. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85501. var _this = this;
  85502. if (!this.shouldRender()) {
  85503. return;
  85504. }
  85505. var material = subMesh.getMaterial();
  85506. var mesh = subMesh.getRenderingMesh();
  85507. var scene = this._scene;
  85508. var engine = scene.getEngine();
  85509. if (!material) {
  85510. return;
  85511. }
  85512. // Do not block in blend mode.
  85513. if (material.needAlphaBlendingForMesh(mesh)) {
  85514. return;
  85515. }
  85516. // Culling
  85517. engine.setState(material.backFaceCulling);
  85518. // Managing instances
  85519. var batch = mesh._getInstancesRenderList(subMesh._id);
  85520. if (batch.mustReturn) {
  85521. return;
  85522. }
  85523. // Early Exit per mesh
  85524. if (!this._shouldRenderMesh(mesh)) {
  85525. return;
  85526. }
  85527. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85528. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85529. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85530. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85531. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85532. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85533. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85534. // Alpha test
  85535. if (material && material.needAlphaTesting()) {
  85536. var alphaTexture = material.getAlphaTestTexture();
  85537. if (alphaTexture) {
  85538. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85539. var textureMatrix = alphaTexture.getTextureMatrix();
  85540. if (textureMatrix) {
  85541. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85542. }
  85543. }
  85544. }
  85545. // Glow emissive only
  85546. if (this._emissiveTextureAndColor.texture) {
  85547. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85548. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85549. }
  85550. // Bones
  85551. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85552. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85553. }
  85554. // Draw
  85555. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85556. }
  85557. else {
  85558. // Need to reset refresh rate of the shadowMap
  85559. this._mainTexture.resetRefreshCounter();
  85560. }
  85561. };
  85562. /**
  85563. * Rebuild the required buffers.
  85564. * @ignore Internal use only.
  85565. */
  85566. EffectLayer.prototype._rebuild = function () {
  85567. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85568. if (vb) {
  85569. vb._rebuild();
  85570. }
  85571. this._generateIndexBuffer();
  85572. };
  85573. /**
  85574. * Dispose only the render target textures and post process.
  85575. */
  85576. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85577. this._mainTexture.dispose();
  85578. for (var i = 0; i < this._postProcesses.length; i++) {
  85579. if (this._postProcesses[i]) {
  85580. this._postProcesses[i].dispose();
  85581. }
  85582. }
  85583. this._postProcesses = [];
  85584. for (var i = 0; i < this._textures.length; i++) {
  85585. if (this._textures[i]) {
  85586. this._textures[i].dispose();
  85587. }
  85588. }
  85589. this._textures = [];
  85590. };
  85591. /**
  85592. * Dispose the highlight layer and free resources.
  85593. */
  85594. EffectLayer.prototype.dispose = function () {
  85595. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85596. if (vertexBuffer) {
  85597. vertexBuffer.dispose();
  85598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85599. }
  85600. if (this._indexBuffer) {
  85601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85602. this._indexBuffer = null;
  85603. }
  85604. // Clean textures and post processes
  85605. this._disposeTextureAndPostProcesses();
  85606. // Remove from scene
  85607. var index = this._scene.effectLayers.indexOf(this, 0);
  85608. if (index > -1) {
  85609. this._scene.effectLayers.splice(index, 1);
  85610. }
  85611. // Callback
  85612. this.onDisposeObservable.notifyObservers(this);
  85613. this.onDisposeObservable.clear();
  85614. this.onBeforeRenderMainTextureObservable.clear();
  85615. this.onBeforeComposeObservable.clear();
  85616. this.onAfterComposeObservable.clear();
  85617. this.onSizeChangedObservable.clear();
  85618. };
  85619. return EffectLayer;
  85620. }());
  85621. BABYLON.EffectLayer = EffectLayer;
  85622. })(BABYLON || (BABYLON = {}));
  85623. //# sourceMappingURL=babylon.effectLayer.js.map
  85624. var BABYLON;
  85625. (function (BABYLON) {
  85626. /**
  85627. * Special Glow Blur post process only blurring the alpha channel
  85628. * It enforces keeping the most luminous color in the color channel.
  85629. */
  85630. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85631. __extends(GlowBlurPostProcess, _super);
  85632. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85634. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85635. _this.direction = direction;
  85636. _this.kernel = kernel;
  85637. _this.onApplyObservable.add(function (effect) {
  85638. effect.setFloat2("screenSize", _this.width, _this.height);
  85639. effect.setVector2("direction", _this.direction);
  85640. effect.setFloat("blurWidth", _this.kernel);
  85641. });
  85642. return _this;
  85643. }
  85644. return GlowBlurPostProcess;
  85645. }(BABYLON.PostProcess));
  85646. /**
  85647. * The highlight layer Helps adding a glow effect around a mesh.
  85648. *
  85649. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85650. * glowy meshes to your scene.
  85651. *
  85652. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85653. */
  85654. var HighlightLayer = /** @class */ (function (_super) {
  85655. __extends(HighlightLayer, _super);
  85656. /**
  85657. * Instantiates a new highlight Layer and references it to the scene..
  85658. * @param name The name of the layer
  85659. * @param scene The scene to use the layer in
  85660. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85661. */
  85662. function HighlightLayer(name, scene, options) {
  85663. var _this = _super.call(this, name, scene) || this;
  85664. _this.name = name;
  85665. /**
  85666. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85667. */
  85668. _this.innerGlow = true;
  85669. /**
  85670. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85671. */
  85672. _this.outerGlow = true;
  85673. /**
  85674. * An event triggered when the highlight layer is being blurred.
  85675. */
  85676. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85677. /**
  85678. * An event triggered when the highlight layer has been blurred.
  85679. */
  85680. _this.onAfterBlurObservable = new BABYLON.Observable();
  85681. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85682. _this._meshes = {};
  85683. _this._excludedMeshes = {};
  85684. _this.neutralColor = HighlightLayer.NeutralColor;
  85685. // Warn on stencil
  85686. if (!_this._engine.isStencilEnable) {
  85687. 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 }");
  85688. }
  85689. // Adapt options
  85690. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85691. // Initialize the layer
  85692. _this._init({
  85693. alphaBlendingMode: _this._options.alphaBlendingMode,
  85694. camera: _this._options.camera,
  85695. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85696. mainTextureRatio: _this._options.mainTextureRatio
  85697. });
  85698. // Do not render as long as no meshes have been added
  85699. _this._shouldRender = false;
  85700. return _this;
  85701. }
  85702. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85703. /**
  85704. * Gets the horizontal size of the blur.
  85705. */
  85706. get: function () {
  85707. return this._horizontalBlurPostprocess.kernel;
  85708. },
  85709. /**
  85710. * Specifies the horizontal size of the blur.
  85711. */
  85712. set: function (value) {
  85713. this._horizontalBlurPostprocess.kernel = value;
  85714. },
  85715. enumerable: true,
  85716. configurable: true
  85717. });
  85718. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85719. /**
  85720. * Gets the vertical size of the blur.
  85721. */
  85722. get: function () {
  85723. return this._verticalBlurPostprocess.kernel;
  85724. },
  85725. /**
  85726. * Specifies the vertical size of the blur.
  85727. */
  85728. set: function (value) {
  85729. this._verticalBlurPostprocess.kernel = value;
  85730. },
  85731. enumerable: true,
  85732. configurable: true
  85733. });
  85734. /**
  85735. * Get the effect name of the layer.
  85736. * @return The effect name
  85737. */
  85738. HighlightLayer.prototype.getEffectName = function () {
  85739. return HighlightLayer.EffectName;
  85740. };
  85741. /**
  85742. * Create the merge effect. This is the shader use to blit the information back
  85743. * to the main canvas at the end of the scene rendering.
  85744. */
  85745. HighlightLayer.prototype._createMergeEffect = function () {
  85746. // Effect
  85747. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85748. };
  85749. /**
  85750. * Creates the render target textures and post processes used in the highlight layer.
  85751. */
  85752. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85753. var _this = this;
  85754. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85755. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85756. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85757. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85758. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85759. width: blurTextureWidth,
  85760. height: blurTextureHeight
  85761. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85762. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85763. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85764. this._blurTexture.anisotropicFilteringLevel = 16;
  85765. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85766. this._blurTexture.renderParticles = false;
  85767. this._blurTexture.ignoreCameraViewport = true;
  85768. this._textures = [this._blurTexture];
  85769. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85770. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85771. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85772. effect.setTexture("textureSampler", _this._mainTexture);
  85773. });
  85774. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85775. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85776. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85777. });
  85778. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85779. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85780. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85781. });
  85782. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85783. }
  85784. else {
  85785. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85786. width: blurTextureWidth,
  85787. height: blurTextureHeight
  85788. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85789. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85790. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85791. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85792. effect.setTexture("textureSampler", _this._mainTexture);
  85793. });
  85794. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85795. width: blurTextureWidth,
  85796. height: blurTextureHeight
  85797. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85798. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85799. }
  85800. this._mainTexture.onAfterUnbindObservable.add(function () {
  85801. _this.onBeforeBlurObservable.notifyObservers(_this);
  85802. var internalTexture = _this._blurTexture.getInternalTexture();
  85803. if (internalTexture) {
  85804. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85805. }
  85806. _this.onAfterBlurObservable.notifyObservers(_this);
  85807. });
  85808. // Prevent autoClear.
  85809. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85810. };
  85811. /**
  85812. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85813. */
  85814. HighlightLayer.prototype.needStencil = function () {
  85815. return true;
  85816. };
  85817. /**
  85818. * Checks for the readiness of the element composing the layer.
  85819. * @param subMesh the mesh to check for
  85820. * @param useInstances specify wether or not to use instances to render the mesh
  85821. * @param emissiveTexture the associated emissive texture used to generate the glow
  85822. * @return true if ready otherwise, false
  85823. */
  85824. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85825. var material = subMesh.getMaterial();
  85826. var mesh = subMesh.getRenderingMesh();
  85827. if (!material || !mesh || !this._meshes) {
  85828. return false;
  85829. }
  85830. var emissiveTexture = null;
  85831. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85832. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85833. emissiveTexture = material.emissiveTexture;
  85834. }
  85835. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85836. };
  85837. /**
  85838. * Implementation specific of rendering the generating effect on the main canvas.
  85839. * @param effect The effect used to render through
  85840. */
  85841. HighlightLayer.prototype._internalRender = function (effect) {
  85842. // Texture
  85843. effect.setTexture("textureSampler", this._blurTexture);
  85844. // Cache
  85845. var engine = this._engine;
  85846. var previousStencilBuffer = engine.getStencilBuffer();
  85847. var previousStencilFunction = engine.getStencilFunction();
  85848. var previousStencilMask = engine.getStencilMask();
  85849. var previousStencilOperationPass = engine.getStencilOperationPass();
  85850. var previousStencilOperationFail = engine.getStencilOperationFail();
  85851. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85852. var previousStencilReference = engine.getStencilFunctionReference();
  85853. // Stencil operations
  85854. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85855. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85856. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85857. // Draw order
  85858. engine.setStencilMask(0x00);
  85859. engine.setStencilBuffer(true);
  85860. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85861. // 2 passes inner outer
  85862. if (this.outerGlow) {
  85863. effect.setFloat("offset", 0);
  85864. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85866. }
  85867. if (this.innerGlow) {
  85868. effect.setFloat("offset", 1);
  85869. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85870. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85871. }
  85872. // Restore Cache
  85873. engine.setStencilFunction(previousStencilFunction);
  85874. engine.setStencilMask(previousStencilMask);
  85875. engine.setStencilBuffer(previousStencilBuffer);
  85876. engine.setStencilOperationPass(previousStencilOperationPass);
  85877. engine.setStencilOperationFail(previousStencilOperationFail);
  85878. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85879. engine.setStencilFunctionReference(previousStencilReference);
  85880. };
  85881. /**
  85882. * Returns true if the layer contains information to display, otherwise false.
  85883. */
  85884. HighlightLayer.prototype.shouldRender = function () {
  85885. if (_super.prototype.shouldRender.call(this)) {
  85886. return this._meshes ? true : false;
  85887. }
  85888. return false;
  85889. };
  85890. /**
  85891. * Returns true if the mesh should render, otherwise false.
  85892. * @param mesh The mesh to render
  85893. * @returns true if it should render otherwise false
  85894. */
  85895. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85896. // Excluded Mesh
  85897. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85898. return false;
  85899. }
  85900. ;
  85901. return true;
  85902. };
  85903. /**
  85904. * Sets the required values for both the emissive texture and and the main color.
  85905. */
  85906. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85907. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85908. if (highlightLayerMesh) {
  85909. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85910. }
  85911. else {
  85912. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85913. }
  85914. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85915. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85916. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85917. }
  85918. else {
  85919. this._emissiveTextureAndColor.texture = null;
  85920. }
  85921. };
  85922. /**
  85923. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85924. * @param mesh The mesh to exclude from the highlight layer
  85925. */
  85926. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85927. if (!this._excludedMeshes) {
  85928. return;
  85929. }
  85930. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85931. if (!meshExcluded) {
  85932. this._excludedMeshes[mesh.uniqueId] = {
  85933. mesh: mesh,
  85934. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85935. mesh.getEngine().setStencilBuffer(false);
  85936. }),
  85937. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85938. mesh.getEngine().setStencilBuffer(true);
  85939. }),
  85940. };
  85941. }
  85942. };
  85943. /**
  85944. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85945. * @param mesh The mesh to highlight
  85946. */
  85947. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85948. if (!this._excludedMeshes) {
  85949. return;
  85950. }
  85951. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85952. if (meshExcluded) {
  85953. if (meshExcluded.beforeRender) {
  85954. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85955. }
  85956. if (meshExcluded.afterRender) {
  85957. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85958. }
  85959. }
  85960. this._excludedMeshes[mesh.uniqueId] = null;
  85961. };
  85962. /**
  85963. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85964. * @param mesh mesh to test
  85965. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85966. */
  85967. HighlightLayer.prototype.hasMesh = function (mesh) {
  85968. if (!this._meshes) {
  85969. return false;
  85970. }
  85971. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85972. };
  85973. /**
  85974. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85975. * @param mesh The mesh to highlight
  85976. * @param color The color of the highlight
  85977. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85978. */
  85979. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85980. var _this = this;
  85981. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85982. if (!this._meshes) {
  85983. return;
  85984. }
  85985. var meshHighlight = this._meshes[mesh.uniqueId];
  85986. if (meshHighlight) {
  85987. meshHighlight.color = color;
  85988. }
  85989. else {
  85990. this._meshes[mesh.uniqueId] = {
  85991. mesh: mesh,
  85992. color: color,
  85993. // Lambda required for capture due to Observable this context
  85994. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85995. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85996. _this._defaultStencilReference(mesh);
  85997. }
  85998. else {
  85999. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86000. }
  86001. }),
  86002. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86003. glowEmissiveOnly: glowEmissiveOnly
  86004. };
  86005. }
  86006. this._shouldRender = true;
  86007. };
  86008. /**
  86009. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86010. * @param mesh The mesh to highlight
  86011. */
  86012. HighlightLayer.prototype.removeMesh = function (mesh) {
  86013. if (!this._meshes) {
  86014. return;
  86015. }
  86016. var meshHighlight = this._meshes[mesh.uniqueId];
  86017. if (meshHighlight) {
  86018. if (meshHighlight.observerHighlight) {
  86019. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86020. }
  86021. if (meshHighlight.observerDefault) {
  86022. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86023. }
  86024. delete this._meshes[mesh.uniqueId];
  86025. }
  86026. this._shouldRender = false;
  86027. for (var meshHighlightToCheck in this._meshes) {
  86028. if (this._meshes[meshHighlightToCheck]) {
  86029. this._shouldRender = true;
  86030. break;
  86031. }
  86032. }
  86033. };
  86034. /**
  86035. * Force the stencil to the normal expected value for none glowing parts
  86036. */
  86037. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86038. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86039. };
  86040. /**
  86041. * Free any resources and references associated to a mesh.
  86042. * Internal use
  86043. * @param mesh The mesh to free.
  86044. */
  86045. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86046. this.removeMesh(mesh);
  86047. this.removeExcludedMesh(mesh);
  86048. };
  86049. /**
  86050. * Dispose the highlight layer and free resources.
  86051. */
  86052. HighlightLayer.prototype.dispose = function () {
  86053. if (this._meshes) {
  86054. // Clean mesh references
  86055. for (var id in this._meshes) {
  86056. var meshHighlight = this._meshes[id];
  86057. if (meshHighlight && meshHighlight.mesh) {
  86058. if (meshHighlight.observerHighlight) {
  86059. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86060. }
  86061. if (meshHighlight.observerDefault) {
  86062. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86063. }
  86064. }
  86065. }
  86066. this._meshes = null;
  86067. }
  86068. if (this._excludedMeshes) {
  86069. for (var id in this._excludedMeshes) {
  86070. var meshHighlight = this._excludedMeshes[id];
  86071. if (meshHighlight) {
  86072. if (meshHighlight.beforeRender) {
  86073. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86074. }
  86075. if (meshHighlight.afterRender) {
  86076. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86077. }
  86078. }
  86079. }
  86080. this._excludedMeshes = null;
  86081. }
  86082. _super.prototype.dispose.call(this);
  86083. };
  86084. /**
  86085. * Effect Name of the highlight layer.
  86086. */
  86087. HighlightLayer.EffectName = "HighlightLayer";
  86088. /**
  86089. * The neutral color used during the preparation of the glow effect.
  86090. * This is black by default as the blend operation is a blend operation.
  86091. */
  86092. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86093. /**
  86094. * Stencil value used for glowing meshes.
  86095. */
  86096. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86097. /**
  86098. * Stencil value used for the other meshes in the scene.
  86099. */
  86100. HighlightLayer.NormalMeshStencilReference = 0x01;
  86101. return HighlightLayer;
  86102. }(BABYLON.EffectLayer));
  86103. BABYLON.HighlightLayer = HighlightLayer;
  86104. })(BABYLON || (BABYLON = {}));
  86105. //# sourceMappingURL=babylon.highlightLayer.js.map
  86106. var BABYLON;
  86107. (function (BABYLON) {
  86108. /**
  86109. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86110. *
  86111. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86112. * glowy meshes to your scene.
  86113. *
  86114. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86115. */
  86116. var GlowLayer = /** @class */ (function (_super) {
  86117. __extends(GlowLayer, _super);
  86118. /**
  86119. * Instantiates a new glow Layer and references it to the scene.
  86120. * @param name The name of the layer
  86121. * @param scene The scene to use the layer in
  86122. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86123. */
  86124. function GlowLayer(name, scene, options) {
  86125. var _this = _super.call(this, name, scene) || this;
  86126. _this.name = name;
  86127. _this._intensity = 1.0;
  86128. _this._includedOnlyMeshes = [];
  86129. _this._excludedMeshes = [];
  86130. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86131. // Adapt options
  86132. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86133. // Initialize the layer
  86134. _this._init({
  86135. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86136. camera: _this._options.camera,
  86137. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86138. mainTextureRatio: _this._options.mainTextureRatio
  86139. });
  86140. return _this;
  86141. }
  86142. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86143. /**
  86144. * Gets the kernel size of the blur.
  86145. */
  86146. get: function () {
  86147. return this._horizontalBlurPostprocess1.kernel;
  86148. },
  86149. /**
  86150. * Sets the kernel size of the blur.
  86151. */
  86152. set: function (value) {
  86153. this._horizontalBlurPostprocess1.kernel = value;
  86154. this._verticalBlurPostprocess1.kernel = value;
  86155. this._horizontalBlurPostprocess2.kernel = value;
  86156. this._verticalBlurPostprocess2.kernel = value;
  86157. },
  86158. enumerable: true,
  86159. configurable: true
  86160. });
  86161. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86162. /**
  86163. * Gets the glow intensity.
  86164. */
  86165. get: function () {
  86166. return this._intensity;
  86167. },
  86168. /**
  86169. * Sets the glow intensity.
  86170. */
  86171. set: function (value) {
  86172. this._intensity = value;
  86173. },
  86174. enumerable: true,
  86175. configurable: true
  86176. });
  86177. /**
  86178. * Get the effect name of the layer.
  86179. * @return The effect name
  86180. */
  86181. GlowLayer.prototype.getEffectName = function () {
  86182. return GlowLayer.EffectName;
  86183. };
  86184. /**
  86185. * Create the merge effect. This is the shader use to blit the information back
  86186. * to the main canvas at the end of the scene rendering.
  86187. */
  86188. GlowLayer.prototype._createMergeEffect = function () {
  86189. // Effect
  86190. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86191. };
  86192. /**
  86193. * Creates the render target textures and post processes used in the glow layer.
  86194. */
  86195. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86196. var _this = this;
  86197. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86198. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86199. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86200. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86201. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86202. width: blurTextureWidth,
  86203. height: blurTextureHeight
  86204. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86205. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86206. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86207. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86208. this._blurTexture1.renderParticles = false;
  86209. this._blurTexture1.ignoreCameraViewport = true;
  86210. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86211. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86212. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86213. width: blurTextureWidth2,
  86214. height: blurTextureHeight2
  86215. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86216. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86217. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86218. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86219. this._blurTexture2.renderParticles = false;
  86220. this._blurTexture2.ignoreCameraViewport = true;
  86221. this._textures = [this._blurTexture1, this._blurTexture2];
  86222. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86223. width: blurTextureWidth,
  86224. height: blurTextureHeight
  86225. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86226. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86227. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86228. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86229. effect.setTexture("textureSampler", _this._mainTexture);
  86230. });
  86231. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86232. width: blurTextureWidth,
  86233. height: blurTextureHeight
  86234. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86235. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86236. width: blurTextureWidth2,
  86237. height: blurTextureHeight2
  86238. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86239. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86240. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86241. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86242. effect.setTexture("textureSampler", _this._blurTexture1);
  86243. });
  86244. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86245. width: blurTextureWidth2,
  86246. height: blurTextureHeight2
  86247. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86248. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86249. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86250. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86251. this._mainTexture.samples = this._options.mainTextureSamples;
  86252. this._mainTexture.onAfterUnbindObservable.add(function () {
  86253. var internalTexture = _this._blurTexture1.getInternalTexture();
  86254. if (internalTexture) {
  86255. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86256. internalTexture = _this._blurTexture2.getInternalTexture();
  86257. if (internalTexture) {
  86258. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86259. }
  86260. }
  86261. });
  86262. // Prevent autoClear.
  86263. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86264. };
  86265. /**
  86266. * Checks for the readiness of the element composing the layer.
  86267. * @param subMesh the mesh to check for
  86268. * @param useInstances specify wether or not to use instances to render the mesh
  86269. * @param emissiveTexture the associated emissive texture used to generate the glow
  86270. * @return true if ready otherwise, false
  86271. */
  86272. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86273. var material = subMesh.getMaterial();
  86274. var mesh = subMesh.getRenderingMesh();
  86275. if (!material || !mesh) {
  86276. return false;
  86277. }
  86278. var emissiveTexture = material.emissiveTexture;
  86279. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86280. };
  86281. /**
  86282. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86283. */
  86284. GlowLayer.prototype.needStencil = function () {
  86285. return false;
  86286. };
  86287. /**
  86288. * Implementation specific of rendering the generating effect on the main canvas.
  86289. * @param effect The effect used to render through
  86290. */
  86291. GlowLayer.prototype._internalRender = function (effect) {
  86292. // Texture
  86293. effect.setTexture("textureSampler", this._blurTexture1);
  86294. effect.setTexture("textureSampler2", this._blurTexture2);
  86295. effect.setFloat("offset", this._intensity);
  86296. // Cache
  86297. var engine = this._engine;
  86298. var previousStencilBuffer = engine.getStencilBuffer();
  86299. // Draw order
  86300. engine.setStencilBuffer(false);
  86301. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86302. // Draw order
  86303. engine.setStencilBuffer(previousStencilBuffer);
  86304. };
  86305. /**
  86306. * Sets the required values for both the emissive texture and and the main color.
  86307. */
  86308. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86309. var textureLevel = 1.0;
  86310. if (this.customEmissiveTextureSelector) {
  86311. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86312. }
  86313. else {
  86314. if (material) {
  86315. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86316. if (this._emissiveTextureAndColor.texture) {
  86317. textureLevel = this._emissiveTextureAndColor.texture.level;
  86318. }
  86319. }
  86320. else {
  86321. this._emissiveTextureAndColor.texture = null;
  86322. }
  86323. }
  86324. if (this.customEmissiveColorSelector) {
  86325. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86326. }
  86327. else {
  86328. if (material.emissiveColor) {
  86329. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86330. }
  86331. else {
  86332. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86333. }
  86334. }
  86335. };
  86336. /**
  86337. * Returns true if the mesh should render, otherwise false.
  86338. * @param mesh The mesh to render
  86339. * @returns true if it should render otherwise false
  86340. */
  86341. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86342. return this.hasMesh(mesh);
  86343. };
  86344. /**
  86345. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86346. * @param mesh The mesh to exclude from the glow layer
  86347. */
  86348. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86349. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86350. this._excludedMeshes.push(mesh.uniqueId);
  86351. }
  86352. };
  86353. /**
  86354. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86355. * @param mesh The mesh to remove
  86356. */
  86357. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86358. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86359. if (index !== -1) {
  86360. this._excludedMeshes.splice(index, 1);
  86361. }
  86362. };
  86363. /**
  86364. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86365. * @param mesh The mesh to include in the glow layer
  86366. */
  86367. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86368. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86369. this._includedOnlyMeshes.push(mesh.uniqueId);
  86370. }
  86371. };
  86372. /**
  86373. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86374. * @param mesh The mesh to remove
  86375. */
  86376. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86377. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86378. if (index !== -1) {
  86379. this._includedOnlyMeshes.splice(index, 1);
  86380. }
  86381. };
  86382. /**
  86383. * Determine if a given mesh will be used in the glow layer
  86384. * @param mesh The mesh to test
  86385. * @returns true if the mesh will be highlighted by the current glow layer
  86386. */
  86387. GlowLayer.prototype.hasMesh = function (mesh) {
  86388. // Included Mesh
  86389. if (this._includedOnlyMeshes.length) {
  86390. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86391. }
  86392. ;
  86393. // Excluded Mesh
  86394. if (this._excludedMeshes.length) {
  86395. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86396. }
  86397. ;
  86398. return true;
  86399. };
  86400. /**
  86401. * Free any resources and references associated to a mesh.
  86402. * Internal use
  86403. * @param mesh The mesh to free.
  86404. */
  86405. GlowLayer.prototype._disposeMesh = function (mesh) {
  86406. this.removeIncludedOnlyMesh(mesh);
  86407. this.removeExcludedMesh(mesh);
  86408. };
  86409. /**
  86410. * Effect Name of the layer.
  86411. */
  86412. GlowLayer.EffectName = "GlowLayer";
  86413. /**
  86414. * The default blur kernel size used for the glow.
  86415. */
  86416. GlowLayer.DefaultBlurKernelSize = 32;
  86417. /**
  86418. * The default texture size ratio used for the glow.
  86419. */
  86420. GlowLayer.DefaultTextureRatio = 0.5;
  86421. return GlowLayer;
  86422. }(BABYLON.EffectLayer));
  86423. BABYLON.GlowLayer = GlowLayer;
  86424. })(BABYLON || (BABYLON = {}));
  86425. //# sourceMappingURL=babylon.glowLayer.js.map
  86426. var BABYLON;
  86427. (function (BABYLON) {
  86428. /**
  86429. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86430. */
  86431. var AssetTaskState;
  86432. (function (AssetTaskState) {
  86433. /**
  86434. * Initialization
  86435. */
  86436. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86437. /**
  86438. * Running
  86439. */
  86440. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86441. /**
  86442. * Done
  86443. */
  86444. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86445. /**
  86446. * Error
  86447. */
  86448. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86449. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86450. /**
  86451. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86452. */
  86453. var AbstractAssetTask = /** @class */ (function () {
  86454. /**
  86455. * Creates a new {BABYLON.AssetsManager}
  86456. * @param name defines the name of the task
  86457. */
  86458. function AbstractAssetTask(
  86459. /**
  86460. * Task name
  86461. */ name) {
  86462. this.name = name;
  86463. this._isCompleted = false;
  86464. this._taskState = AssetTaskState.INIT;
  86465. }
  86466. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86467. /**
  86468. * Get if the task is completed
  86469. */
  86470. get: function () {
  86471. return this._isCompleted;
  86472. },
  86473. enumerable: true,
  86474. configurable: true
  86475. });
  86476. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86477. /**
  86478. * Gets the current state of the task
  86479. */
  86480. get: function () {
  86481. return this._taskState;
  86482. },
  86483. enumerable: true,
  86484. configurable: true
  86485. });
  86486. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86487. /**
  86488. * Gets the current error object (if task is in error)
  86489. */
  86490. get: function () {
  86491. return this._errorObject;
  86492. },
  86493. enumerable: true,
  86494. configurable: true
  86495. });
  86496. /**
  86497. * Internal only
  86498. * @ignore
  86499. */
  86500. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86501. if (this._errorObject) {
  86502. return;
  86503. }
  86504. this._errorObject = {
  86505. message: message,
  86506. exception: exception
  86507. };
  86508. };
  86509. /**
  86510. * Execute the current task
  86511. * @param scene defines the scene where you want your assets to be loaded
  86512. * @param onSuccess is a callback called when the task is successfully executed
  86513. * @param onError is a callback called if an error occurs
  86514. */
  86515. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86516. var _this = this;
  86517. this._taskState = AssetTaskState.RUNNING;
  86518. this.runTask(scene, function () {
  86519. _this.onDoneCallback(onSuccess, onError);
  86520. }, function (msg, exception) {
  86521. _this.onErrorCallback(onError, msg, exception);
  86522. });
  86523. };
  86524. /**
  86525. * Execute the current task
  86526. * @param scene defines the scene where you want your assets to be loaded
  86527. * @param onSuccess is a callback called when the task is successfully executed
  86528. * @param onError is a callback called if an error occurs
  86529. */
  86530. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86531. throw new Error("runTask is not implemented");
  86532. };
  86533. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86534. this._taskState = AssetTaskState.ERROR;
  86535. this._errorObject = {
  86536. message: message,
  86537. exception: exception
  86538. };
  86539. if (this.onError) {
  86540. this.onError(this, message, exception);
  86541. }
  86542. onError();
  86543. };
  86544. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86545. try {
  86546. this._taskState = AssetTaskState.DONE;
  86547. this._isCompleted = true;
  86548. if (this.onSuccess) {
  86549. this.onSuccess(this);
  86550. }
  86551. onSuccess();
  86552. }
  86553. catch (e) {
  86554. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86555. }
  86556. };
  86557. return AbstractAssetTask;
  86558. }());
  86559. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86560. /**
  86561. * Class used to share progress information about assets loading
  86562. */
  86563. var AssetsProgressEvent = /** @class */ (function () {
  86564. /**
  86565. * Creates a {BABYLON.AssetsProgressEvent}
  86566. * @param remainingCount defines the number of remaining tasks to process
  86567. * @param totalCount defines the total number of tasks
  86568. * @param task defines the task that was just processed
  86569. */
  86570. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86571. this.remainingCount = remainingCount;
  86572. this.totalCount = totalCount;
  86573. this.task = task;
  86574. }
  86575. return AssetsProgressEvent;
  86576. }());
  86577. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86578. /**
  86579. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86580. */
  86581. var MeshAssetTask = /** @class */ (function (_super) {
  86582. __extends(MeshAssetTask, _super);
  86583. /**
  86584. * Creates a new {BABYLON.MeshAssetTask}
  86585. * @param name defines the name of the task
  86586. * @param meshesNames defines the list of mesh's names you want to load
  86587. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86588. * @param sceneFilename defines the filename of the scene to load from
  86589. */
  86590. function MeshAssetTask(
  86591. /**
  86592. * Defines the name of the task
  86593. */
  86594. name,
  86595. /**
  86596. * Defines the list of mesh's names you want to load
  86597. */
  86598. meshesNames,
  86599. /**
  86600. * Defines the root url to use as a base to load your meshes and associated resources
  86601. */
  86602. rootUrl,
  86603. /**
  86604. * Defines the filename of the scene to load from
  86605. */
  86606. sceneFilename) {
  86607. var _this = _super.call(this, name) || this;
  86608. _this.name = name;
  86609. _this.meshesNames = meshesNames;
  86610. _this.rootUrl = rootUrl;
  86611. _this.sceneFilename = sceneFilename;
  86612. return _this;
  86613. }
  86614. /**
  86615. * Execute the current task
  86616. * @param scene defines the scene where you want your assets to be loaded
  86617. * @param onSuccess is a callback called when the task is successfully executed
  86618. * @param onError is a callback called if an error occurs
  86619. */
  86620. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86621. var _this = this;
  86622. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86623. _this.loadedMeshes = meshes;
  86624. _this.loadedParticleSystems = particleSystems;
  86625. _this.loadedSkeletons = skeletons;
  86626. onSuccess();
  86627. }, null, function (scene, message, exception) {
  86628. onError(message, exception);
  86629. });
  86630. };
  86631. return MeshAssetTask;
  86632. }(AbstractAssetTask));
  86633. BABYLON.MeshAssetTask = MeshAssetTask;
  86634. /**
  86635. * Define a task used by {BABYLON.AssetsManager} to load text content
  86636. */
  86637. var TextFileAssetTask = /** @class */ (function (_super) {
  86638. __extends(TextFileAssetTask, _super);
  86639. /**
  86640. * Creates a new TextFileAssetTask object
  86641. * @param name defines the name of the task
  86642. * @param url defines the location of the file to load
  86643. */
  86644. function TextFileAssetTask(
  86645. /**
  86646. * Defines the name of the task
  86647. */
  86648. name,
  86649. /**
  86650. * Defines the location of the file to load
  86651. */
  86652. url) {
  86653. var _this = _super.call(this, name) || this;
  86654. _this.name = name;
  86655. _this.url = url;
  86656. return _this;
  86657. }
  86658. /**
  86659. * Execute the current task
  86660. * @param scene defines the scene where you want your assets to be loaded
  86661. * @param onSuccess is a callback called when the task is successfully executed
  86662. * @param onError is a callback called if an error occurs
  86663. */
  86664. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86665. var _this = this;
  86666. scene._loadFile(this.url, function (data) {
  86667. _this.text = data;
  86668. onSuccess();
  86669. }, undefined, false, false, function (request, exception) {
  86670. if (request) {
  86671. onError(request.status + " " + request.statusText, exception);
  86672. }
  86673. });
  86674. };
  86675. return TextFileAssetTask;
  86676. }(AbstractAssetTask));
  86677. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86678. /**
  86679. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86680. */
  86681. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86682. __extends(BinaryFileAssetTask, _super);
  86683. /**
  86684. * Creates a new BinaryFileAssetTask object
  86685. * @param name defines the name of the new task
  86686. * @param url defines the location of the file to load
  86687. */
  86688. function BinaryFileAssetTask(
  86689. /**
  86690. * Defines the name of the task
  86691. */
  86692. name,
  86693. /**
  86694. * Defines the location of the file to load
  86695. */
  86696. url) {
  86697. var _this = _super.call(this, name) || this;
  86698. _this.name = name;
  86699. _this.url = url;
  86700. return _this;
  86701. }
  86702. /**
  86703. * Execute the current task
  86704. * @param scene defines the scene where you want your assets to be loaded
  86705. * @param onSuccess is a callback called when the task is successfully executed
  86706. * @param onError is a callback called if an error occurs
  86707. */
  86708. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86709. var _this = this;
  86710. scene._loadFile(this.url, function (data) {
  86711. _this.data = data;
  86712. onSuccess();
  86713. }, undefined, true, true, function (request, exception) {
  86714. if (request) {
  86715. onError(request.status + " " + request.statusText, exception);
  86716. }
  86717. });
  86718. };
  86719. return BinaryFileAssetTask;
  86720. }(AbstractAssetTask));
  86721. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86722. /**
  86723. * Define a task used by {BABYLON.AssetsManager} to load images
  86724. */
  86725. var ImageAssetTask = /** @class */ (function (_super) {
  86726. __extends(ImageAssetTask, _super);
  86727. /**
  86728. * Creates a new ImageAssetTask
  86729. * @param name defines the name of the task
  86730. * @param url defines the location of the image to load
  86731. */
  86732. function ImageAssetTask(
  86733. /**
  86734. * Defines the name of the task
  86735. */
  86736. name,
  86737. /**
  86738. * Defines the location of the image to load
  86739. */
  86740. url) {
  86741. var _this = _super.call(this, name) || this;
  86742. _this.name = name;
  86743. _this.url = url;
  86744. return _this;
  86745. }
  86746. /**
  86747. * Execute the current task
  86748. * @param scene defines the scene where you want your assets to be loaded
  86749. * @param onSuccess is a callback called when the task is successfully executed
  86750. * @param onError is a callback called if an error occurs
  86751. */
  86752. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86753. var _this = this;
  86754. var img = new Image();
  86755. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86756. img.onload = function () {
  86757. _this.image = img;
  86758. onSuccess();
  86759. };
  86760. img.onerror = function (err) {
  86761. onError("Error loading image", err);
  86762. };
  86763. img.src = this.url;
  86764. };
  86765. return ImageAssetTask;
  86766. }(AbstractAssetTask));
  86767. BABYLON.ImageAssetTask = ImageAssetTask;
  86768. /**
  86769. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86770. */
  86771. var TextureAssetTask = /** @class */ (function (_super) {
  86772. __extends(TextureAssetTask, _super);
  86773. /**
  86774. * Creates a new TextureAssetTask object
  86775. * @param name defines the name of the task
  86776. * @param url defines the location of the file to load
  86777. * @param noMipmap defines if mipmap should not be generated (default is false)
  86778. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86779. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86780. */
  86781. function TextureAssetTask(
  86782. /**
  86783. * Defines the name of the task
  86784. */
  86785. name,
  86786. /**
  86787. * Defines the location of the file to load
  86788. */
  86789. url,
  86790. /**
  86791. * Defines if mipmap should not be generated (default is false)
  86792. */
  86793. noMipmap,
  86794. /**
  86795. * Defines if texture must be inverted on Y axis (default is false)
  86796. */
  86797. invertY,
  86798. /**
  86799. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86800. */
  86801. samplingMode) {
  86802. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86803. var _this = _super.call(this, name) || this;
  86804. _this.name = name;
  86805. _this.url = url;
  86806. _this.noMipmap = noMipmap;
  86807. _this.invertY = invertY;
  86808. _this.samplingMode = samplingMode;
  86809. return _this;
  86810. }
  86811. /**
  86812. * Execute the current task
  86813. * @param scene defines the scene where you want your assets to be loaded
  86814. * @param onSuccess is a callback called when the task is successfully executed
  86815. * @param onError is a callback called if an error occurs
  86816. */
  86817. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86818. var onload = function () {
  86819. onSuccess();
  86820. };
  86821. var onerror = function (message, exception) {
  86822. onError(message, exception);
  86823. };
  86824. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86825. };
  86826. return TextureAssetTask;
  86827. }(AbstractAssetTask));
  86828. BABYLON.TextureAssetTask = TextureAssetTask;
  86829. /**
  86830. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86831. */
  86832. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86833. __extends(CubeTextureAssetTask, _super);
  86834. /**
  86835. * Creates a new CubeTextureAssetTask
  86836. * @param name defines the name of the task
  86837. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86838. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86839. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86840. * @param files defines the explicit list of files (undefined by default)
  86841. */
  86842. function CubeTextureAssetTask(
  86843. /**
  86844. * Defines the name of the task
  86845. */
  86846. name,
  86847. /**
  86848. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86849. */
  86850. url,
  86851. /**
  86852. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86853. */
  86854. extensions,
  86855. /**
  86856. * Defines if mipmaps should not be generated (default is false)
  86857. */
  86858. noMipmap,
  86859. /**
  86860. * Defines the explicit list of files (undefined by default)
  86861. */
  86862. files) {
  86863. var _this = _super.call(this, name) || this;
  86864. _this.name = name;
  86865. _this.url = url;
  86866. _this.extensions = extensions;
  86867. _this.noMipmap = noMipmap;
  86868. _this.files = files;
  86869. return _this;
  86870. }
  86871. /**
  86872. * Execute the current task
  86873. * @param scene defines the scene where you want your assets to be loaded
  86874. * @param onSuccess is a callback called when the task is successfully executed
  86875. * @param onError is a callback called if an error occurs
  86876. */
  86877. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86878. var onload = function () {
  86879. onSuccess();
  86880. };
  86881. var onerror = function (message, exception) {
  86882. onError(message, exception);
  86883. };
  86884. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86885. };
  86886. return CubeTextureAssetTask;
  86887. }(AbstractAssetTask));
  86888. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86889. /**
  86890. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86891. */
  86892. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86893. __extends(HDRCubeTextureAssetTask, _super);
  86894. /**
  86895. * Creates a new HDRCubeTextureAssetTask object
  86896. * @param name defines the name of the task
  86897. * @param url defines the location of the file to load
  86898. * @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.
  86899. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86900. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86901. * @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)
  86902. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86903. */
  86904. function HDRCubeTextureAssetTask(
  86905. /**
  86906. * Defines the name of the task
  86907. */
  86908. name,
  86909. /**
  86910. * Defines the location of the file to load
  86911. */
  86912. url,
  86913. /**
  86914. * 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.
  86915. */
  86916. size,
  86917. /**
  86918. * Defines if mipmaps should not be generated (default is false)
  86919. */
  86920. noMipmap,
  86921. /**
  86922. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86923. */
  86924. generateHarmonics,
  86925. /**
  86926. * 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)
  86927. */
  86928. useInGammaSpace,
  86929. /**
  86930. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86931. */
  86932. usePMREMGenerator) {
  86933. if (noMipmap === void 0) { noMipmap = false; }
  86934. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86935. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86936. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86937. var _this = _super.call(this, name) || this;
  86938. _this.name = name;
  86939. _this.url = url;
  86940. _this.size = size;
  86941. _this.noMipmap = noMipmap;
  86942. _this.generateHarmonics = generateHarmonics;
  86943. _this.useInGammaSpace = useInGammaSpace;
  86944. _this.usePMREMGenerator = usePMREMGenerator;
  86945. return _this;
  86946. }
  86947. /**
  86948. * Execute the current task
  86949. * @param scene defines the scene where you want your assets to be loaded
  86950. * @param onSuccess is a callback called when the task is successfully executed
  86951. * @param onError is a callback called if an error occurs
  86952. */
  86953. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86954. var onload = function () {
  86955. onSuccess();
  86956. };
  86957. var onerror = function (message, exception) {
  86958. onError(message, exception);
  86959. };
  86960. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86961. };
  86962. return HDRCubeTextureAssetTask;
  86963. }(AbstractAssetTask));
  86964. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86965. /**
  86966. * This class can be used to easily import assets into a scene
  86967. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86968. */
  86969. var AssetsManager = /** @class */ (function () {
  86970. /**
  86971. * Creates a new AssetsManager
  86972. * @param scene defines the scene to work on
  86973. */
  86974. function AssetsManager(scene) {
  86975. this._isLoading = false;
  86976. this._tasks = new Array();
  86977. this._waitingTasksCount = 0;
  86978. this._totalTasksCount = 0;
  86979. /**
  86980. * Observable called when all tasks are processed
  86981. */
  86982. this.onTaskSuccessObservable = new BABYLON.Observable();
  86983. /**
  86984. * Observable called when a task had an error
  86985. */
  86986. this.onTaskErrorObservable = new BABYLON.Observable();
  86987. /**
  86988. * Observable called when a task is successful
  86989. */
  86990. this.onTasksDoneObservable = new BABYLON.Observable();
  86991. /**
  86992. * Observable called when a task is done (whatever the result is)
  86993. */
  86994. this.onProgressObservable = new BABYLON.Observable();
  86995. /**
  86996. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86997. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86998. */
  86999. this.useDefaultLoadingScreen = true;
  87000. this._scene = scene;
  87001. }
  87002. /**
  87003. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87004. * @param taskName defines the name of the new task
  87005. * @param meshesNames defines the name of meshes to load
  87006. * @param rootUrl defines the root url to use to locate files
  87007. * @param sceneFilename defines the filename of the scene file
  87008. * @returns a new {BABYLON.MeshAssetTask} object
  87009. */
  87010. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87011. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87012. this._tasks.push(task);
  87013. return task;
  87014. };
  87015. /**
  87016. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87017. * @param taskName defines the name of the new task
  87018. * @param url defines the url of the file to load
  87019. * @returns a new {BABYLON.TextFileAssetTask} object
  87020. */
  87021. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87022. var task = new TextFileAssetTask(taskName, url);
  87023. this._tasks.push(task);
  87024. return task;
  87025. };
  87026. /**
  87027. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87028. * @param taskName defines the name of the new task
  87029. * @param url defines the url of the file to load
  87030. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87031. */
  87032. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87033. var task = new BinaryFileAssetTask(taskName, url);
  87034. this._tasks.push(task);
  87035. return task;
  87036. };
  87037. /**
  87038. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87039. * @param taskName defines the name of the new task
  87040. * @param url defines the url of the file to load
  87041. * @returns a new {BABYLON.ImageAssetTask} object
  87042. */
  87043. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87044. var task = new ImageAssetTask(taskName, url);
  87045. this._tasks.push(task);
  87046. return task;
  87047. };
  87048. /**
  87049. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87050. * @param taskName defines the name of the new task
  87051. * @param url defines the url of the file to load
  87052. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87053. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87054. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87055. * @returns a new {BABYLON.TextureAssetTask} object
  87056. */
  87057. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87059. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87060. this._tasks.push(task);
  87061. return task;
  87062. };
  87063. /**
  87064. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87065. * @param taskName defines the name of the new task
  87066. * @param url defines the url of the file to load
  87067. * @param extensions defines the extension to use to load the cube map (can be null)
  87068. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87069. * @param files defines the list of files to load (can be null)
  87070. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87071. */
  87072. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87073. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87074. this._tasks.push(task);
  87075. return task;
  87076. };
  87077. /**
  87078. *
  87079. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87080. * @param taskName defines the name of the new task
  87081. * @param url defines the url of the file to load
  87082. * @param size defines the size you want for the cubemap (can be null)
  87083. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87084. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87085. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87086. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87087. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87088. */
  87089. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87090. if (noMipmap === void 0) { noMipmap = false; }
  87091. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87092. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87093. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87094. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87095. this._tasks.push(task);
  87096. return task;
  87097. };
  87098. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87099. var _this = this;
  87100. this._waitingTasksCount--;
  87101. try {
  87102. if (task.taskState === AssetTaskState.DONE) {
  87103. // Let's remove successfull tasks
  87104. BABYLON.Tools.SetImmediate(function () {
  87105. var index = _this._tasks.indexOf(task);
  87106. if (index > -1) {
  87107. _this._tasks.splice(index, 1);
  87108. }
  87109. });
  87110. }
  87111. if (this.onProgress) {
  87112. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87113. }
  87114. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87115. }
  87116. catch (e) {
  87117. BABYLON.Tools.Error("Error running progress callbacks.");
  87118. console.log(e);
  87119. }
  87120. if (this._waitingTasksCount === 0) {
  87121. try {
  87122. if (this.onFinish) {
  87123. this.onFinish(this._tasks);
  87124. }
  87125. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87126. }
  87127. catch (e) {
  87128. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87129. console.log(e);
  87130. }
  87131. this._isLoading = false;
  87132. this._scene.getEngine().hideLoadingUI();
  87133. }
  87134. };
  87135. AssetsManager.prototype._runTask = function (task) {
  87136. var _this = this;
  87137. var done = function () {
  87138. try {
  87139. if (_this.onTaskSuccess) {
  87140. _this.onTaskSuccess(task);
  87141. }
  87142. _this.onTaskSuccessObservable.notifyObservers(task);
  87143. _this._decreaseWaitingTasksCount(task);
  87144. }
  87145. catch (e) {
  87146. error("Error executing task success callbacks", e);
  87147. }
  87148. };
  87149. var error = function (message, exception) {
  87150. task._setErrorObject(message, exception);
  87151. if (_this.onTaskError) {
  87152. _this.onTaskError(task);
  87153. }
  87154. _this.onTaskErrorObservable.notifyObservers(task);
  87155. _this._decreaseWaitingTasksCount(task);
  87156. };
  87157. task.run(this._scene, done, error);
  87158. };
  87159. /**
  87160. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87161. * @return the current instance of the {BABYLON.AssetsManager}
  87162. */
  87163. AssetsManager.prototype.reset = function () {
  87164. this._isLoading = false;
  87165. this._tasks = new Array();
  87166. return this;
  87167. };
  87168. /**
  87169. * Start the loading process
  87170. * @return the current instance of the {BABYLON.AssetsManager}
  87171. */
  87172. AssetsManager.prototype.load = function () {
  87173. if (this._isLoading) {
  87174. return this;
  87175. }
  87176. this._isLoading = true;
  87177. this._waitingTasksCount = this._tasks.length;
  87178. this._totalTasksCount = this._tasks.length;
  87179. if (this._waitingTasksCount === 0) {
  87180. this._isLoading = false;
  87181. if (this.onFinish) {
  87182. this.onFinish(this._tasks);
  87183. }
  87184. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87185. return this;
  87186. }
  87187. if (this.useDefaultLoadingScreen) {
  87188. this._scene.getEngine().displayLoadingUI();
  87189. }
  87190. for (var index = 0; index < this._tasks.length; index++) {
  87191. var task = this._tasks[index];
  87192. this._runTask(task);
  87193. }
  87194. return this;
  87195. };
  87196. return AssetsManager;
  87197. }());
  87198. BABYLON.AssetsManager = AssetsManager;
  87199. })(BABYLON || (BABYLON = {}));
  87200. //# sourceMappingURL=babylon.assetsManager.js.map
  87201. var BABYLON;
  87202. (function (BABYLON) {
  87203. var serializedGeometries = [];
  87204. var serializeGeometry = function (geometry, serializationGeometries) {
  87205. if (serializedGeometries[geometry.id]) {
  87206. return;
  87207. }
  87208. if (geometry.doNotSerialize) {
  87209. return;
  87210. }
  87211. if (geometry instanceof BABYLON.BoxGeometry) {
  87212. serializationGeometries.boxes.push(geometry.serialize());
  87213. }
  87214. else if (geometry instanceof BABYLON.SphereGeometry) {
  87215. serializationGeometries.spheres.push(geometry.serialize());
  87216. }
  87217. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87218. serializationGeometries.cylinders.push(geometry.serialize());
  87219. }
  87220. else if (geometry instanceof BABYLON.TorusGeometry) {
  87221. serializationGeometries.toruses.push(geometry.serialize());
  87222. }
  87223. else if (geometry instanceof BABYLON.GroundGeometry) {
  87224. serializationGeometries.grounds.push(geometry.serialize());
  87225. }
  87226. else if (geometry instanceof BABYLON.Plane) {
  87227. serializationGeometries.planes.push(geometry.serialize());
  87228. }
  87229. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87230. serializationGeometries.torusKnots.push(geometry.serialize());
  87231. }
  87232. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87233. throw new Error("Unknown primitive type");
  87234. }
  87235. else {
  87236. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87237. }
  87238. serializedGeometries[geometry.id] = true;
  87239. };
  87240. var serializeMesh = function (mesh, serializationScene) {
  87241. var serializationObject = {};
  87242. // Geometry
  87243. var geometry = mesh._geometry;
  87244. if (geometry) {
  87245. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87246. // 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
  87247. serializeGeometry(geometry, serializationScene.geometries);
  87248. }
  87249. }
  87250. // Custom
  87251. if (mesh.serialize) {
  87252. mesh.serialize(serializationObject);
  87253. }
  87254. return serializationObject;
  87255. };
  87256. var finalizeSingleMesh = function (mesh, serializationObject) {
  87257. //only works if the mesh is already loaded
  87258. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87259. //serialize material
  87260. if (mesh.material) {
  87261. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87262. serializationObject.materials = serializationObject.materials || [];
  87263. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87264. serializationObject.materials.push(mesh.material.serialize());
  87265. }
  87266. }
  87267. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87268. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87269. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87270. serializationObject.multiMaterials.push(mesh.material.serialize());
  87271. }
  87272. }
  87273. }
  87274. //serialize geometry
  87275. var geometry = mesh._geometry;
  87276. if (geometry) {
  87277. if (!serializationObject.geometries) {
  87278. serializationObject.geometries = {};
  87279. serializationObject.geometries.boxes = [];
  87280. serializationObject.geometries.spheres = [];
  87281. serializationObject.geometries.cylinders = [];
  87282. serializationObject.geometries.toruses = [];
  87283. serializationObject.geometries.grounds = [];
  87284. serializationObject.geometries.planes = [];
  87285. serializationObject.geometries.torusKnots = [];
  87286. serializationObject.geometries.vertexData = [];
  87287. }
  87288. serializeGeometry(geometry, serializationObject.geometries);
  87289. }
  87290. // Skeletons
  87291. if (mesh.skeleton) {
  87292. serializationObject.skeletons = serializationObject.skeletons || [];
  87293. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87294. }
  87295. //serialize the actual mesh
  87296. serializationObject.meshes = serializationObject.meshes || [];
  87297. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87298. }
  87299. };
  87300. var SceneSerializer = /** @class */ (function () {
  87301. function SceneSerializer() {
  87302. }
  87303. SceneSerializer.ClearCache = function () {
  87304. serializedGeometries = [];
  87305. };
  87306. SceneSerializer.Serialize = function (scene) {
  87307. var serializationObject = {};
  87308. SceneSerializer.ClearCache();
  87309. // Scene
  87310. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87311. serializationObject.autoClear = scene.autoClear;
  87312. serializationObject.clearColor = scene.clearColor.asArray();
  87313. serializationObject.ambientColor = scene.ambientColor.asArray();
  87314. serializationObject.gravity = scene.gravity.asArray();
  87315. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87316. serializationObject.workerCollisions = scene.workerCollisions;
  87317. // Fog
  87318. if (scene.fogMode && scene.fogMode !== 0) {
  87319. serializationObject.fogMode = scene.fogMode;
  87320. serializationObject.fogColor = scene.fogColor.asArray();
  87321. serializationObject.fogStart = scene.fogStart;
  87322. serializationObject.fogEnd = scene.fogEnd;
  87323. serializationObject.fogDensity = scene.fogDensity;
  87324. }
  87325. //Physics
  87326. if (scene.isPhysicsEnabled()) {
  87327. var physicEngine = scene.getPhysicsEngine();
  87328. if (physicEngine) {
  87329. serializationObject.physicsEnabled = true;
  87330. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87331. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87332. }
  87333. }
  87334. // Metadata
  87335. if (scene.metadata) {
  87336. serializationObject.metadata = scene.metadata;
  87337. }
  87338. // Morph targets
  87339. serializationObject.morphTargetManagers = [];
  87340. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87341. var abstractMesh = _a[_i];
  87342. var manager = abstractMesh.morphTargetManager;
  87343. if (manager) {
  87344. serializationObject.morphTargetManagers.push(manager.serialize());
  87345. }
  87346. }
  87347. // Lights
  87348. serializationObject.lights = [];
  87349. var index;
  87350. var light;
  87351. for (index = 0; index < scene.lights.length; index++) {
  87352. light = scene.lights[index];
  87353. if (!light.doNotSerialize) {
  87354. serializationObject.lights.push(light.serialize());
  87355. }
  87356. }
  87357. // Cameras
  87358. serializationObject.cameras = [];
  87359. for (index = 0; index < scene.cameras.length; index++) {
  87360. var camera = scene.cameras[index];
  87361. if (!camera.doNotSerialize) {
  87362. serializationObject.cameras.push(camera.serialize());
  87363. }
  87364. }
  87365. if (scene.activeCamera) {
  87366. serializationObject.activeCameraID = scene.activeCamera.id;
  87367. }
  87368. // Animations
  87369. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87370. // Materials
  87371. serializationObject.materials = [];
  87372. serializationObject.multiMaterials = [];
  87373. var material;
  87374. for (index = 0; index < scene.materials.length; index++) {
  87375. material = scene.materials[index];
  87376. if (!material.doNotSerialize) {
  87377. serializationObject.materials.push(material.serialize());
  87378. }
  87379. }
  87380. // MultiMaterials
  87381. serializationObject.multiMaterials = [];
  87382. for (index = 0; index < scene.multiMaterials.length; index++) {
  87383. var multiMaterial = scene.multiMaterials[index];
  87384. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87385. }
  87386. // Environment texture
  87387. if (scene.environmentTexture) {
  87388. serializationObject.environmentTexture = scene.environmentTexture.name;
  87389. }
  87390. // Skeletons
  87391. serializationObject.skeletons = [];
  87392. for (index = 0; index < scene.skeletons.length; index++) {
  87393. var skeleton = scene.skeletons[index];
  87394. if (!skeleton.doNotSerialize) {
  87395. serializationObject.skeletons.push(skeleton.serialize());
  87396. }
  87397. }
  87398. // Transform nodes
  87399. serializationObject.transformNodes = [];
  87400. for (index = 0; index < scene.transformNodes.length; index++) {
  87401. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87402. }
  87403. // Geometries
  87404. serializationObject.geometries = {};
  87405. serializationObject.geometries.boxes = [];
  87406. serializationObject.geometries.spheres = [];
  87407. serializationObject.geometries.cylinders = [];
  87408. serializationObject.geometries.toruses = [];
  87409. serializationObject.geometries.grounds = [];
  87410. serializationObject.geometries.planes = [];
  87411. serializationObject.geometries.torusKnots = [];
  87412. serializationObject.geometries.vertexData = [];
  87413. serializedGeometries = [];
  87414. var geometries = scene.getGeometries();
  87415. for (index = 0; index < geometries.length; index++) {
  87416. var geometry = geometries[index];
  87417. if (geometry.isReady()) {
  87418. serializeGeometry(geometry, serializationObject.geometries);
  87419. }
  87420. }
  87421. // Meshes
  87422. serializationObject.meshes = [];
  87423. for (index = 0; index < scene.meshes.length; index++) {
  87424. var abstractMesh = scene.meshes[index];
  87425. if (abstractMesh instanceof BABYLON.Mesh) {
  87426. var mesh = abstractMesh;
  87427. if (!mesh.doNotSerialize) {
  87428. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87429. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87430. }
  87431. }
  87432. }
  87433. }
  87434. // Particles Systems
  87435. serializationObject.particleSystems = [];
  87436. for (index = 0; index < scene.particleSystems.length; index++) {
  87437. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87438. }
  87439. // Lens flares
  87440. serializationObject.lensFlareSystems = [];
  87441. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87442. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87443. }
  87444. // Shadows
  87445. serializationObject.shadowGenerators = [];
  87446. for (index = 0; index < scene.lights.length; index++) {
  87447. light = scene.lights[index];
  87448. var shadowGenerator = light.getShadowGenerator();
  87449. if (shadowGenerator) {
  87450. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87451. }
  87452. }
  87453. // Action Manager
  87454. if (scene.actionManager) {
  87455. serializationObject.actions = scene.actionManager.serialize("scene");
  87456. }
  87457. // Audio
  87458. serializationObject.sounds = [];
  87459. for (index = 0; index < scene.soundTracks.length; index++) {
  87460. var soundtrack = scene.soundTracks[index];
  87461. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87462. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87463. }
  87464. }
  87465. return serializationObject;
  87466. };
  87467. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87468. if (withParents === void 0) { withParents = false; }
  87469. if (withChildren === void 0) { withChildren = false; }
  87470. var serializationObject = {};
  87471. SceneSerializer.ClearCache();
  87472. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87473. if (withParents || withChildren) {
  87474. //deliberate for loop! not for each, appended should be processed as well.
  87475. for (var i = 0; i < toSerialize.length; ++i) {
  87476. if (withChildren) {
  87477. toSerialize[i].getDescendants().forEach(function (node) {
  87478. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87479. toSerialize.push(node);
  87480. }
  87481. });
  87482. }
  87483. //make sure the array doesn't contain the object already
  87484. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87485. toSerialize.push(toSerialize[i].parent);
  87486. }
  87487. }
  87488. }
  87489. toSerialize.forEach(function (mesh) {
  87490. finalizeSingleMesh(mesh, serializationObject);
  87491. });
  87492. return serializationObject;
  87493. };
  87494. return SceneSerializer;
  87495. }());
  87496. BABYLON.SceneSerializer = SceneSerializer;
  87497. })(BABYLON || (BABYLON = {}));
  87498. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87499. var BABYLON;
  87500. (function (BABYLON) {
  87501. var ReflectionProbe = /** @class */ (function () {
  87502. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87503. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87504. var _this = this;
  87505. this.name = name;
  87506. this._viewMatrix = BABYLON.Matrix.Identity();
  87507. this._target = BABYLON.Vector3.Zero();
  87508. this._add = BABYLON.Vector3.Zero();
  87509. this._invertYAxis = false;
  87510. this.position = BABYLON.Vector3.Zero();
  87511. this._scene = scene;
  87512. this._scene.reflectionProbes.push(this);
  87513. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87514. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87515. switch (faceIndex) {
  87516. case 0:
  87517. _this._add.copyFromFloats(1, 0, 0);
  87518. break;
  87519. case 1:
  87520. _this._add.copyFromFloats(-1, 0, 0);
  87521. break;
  87522. case 2:
  87523. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87524. break;
  87525. case 3:
  87526. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87527. break;
  87528. case 4:
  87529. _this._add.copyFromFloats(0, 0, 1);
  87530. break;
  87531. case 5:
  87532. _this._add.copyFromFloats(0, 0, -1);
  87533. break;
  87534. }
  87535. if (_this._attachedMesh) {
  87536. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87537. }
  87538. _this.position.addToRef(_this._add, _this._target);
  87539. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87540. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87541. scene._forcedViewPosition = _this.position;
  87542. });
  87543. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87544. scene._forcedViewPosition = null;
  87545. scene.updateTransformMatrix(true);
  87546. });
  87547. if (scene.activeCamera) {
  87548. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87549. }
  87550. }
  87551. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87552. get: function () {
  87553. return this._renderTargetTexture.samples;
  87554. },
  87555. set: function (value) {
  87556. this._renderTargetTexture.samples = value;
  87557. },
  87558. enumerable: true,
  87559. configurable: true
  87560. });
  87561. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87562. get: function () {
  87563. return this._renderTargetTexture.refreshRate;
  87564. },
  87565. set: function (value) {
  87566. this._renderTargetTexture.refreshRate = value;
  87567. },
  87568. enumerable: true,
  87569. configurable: true
  87570. });
  87571. ReflectionProbe.prototype.getScene = function () {
  87572. return this._scene;
  87573. };
  87574. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87575. get: function () {
  87576. return this._renderTargetTexture;
  87577. },
  87578. enumerable: true,
  87579. configurable: true
  87580. });
  87581. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87582. get: function () {
  87583. return this._renderTargetTexture.renderList;
  87584. },
  87585. enumerable: true,
  87586. configurable: true
  87587. });
  87588. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87589. this._attachedMesh = mesh;
  87590. };
  87591. /**
  87592. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87593. *
  87594. * @param renderingGroupId The rendering group id corresponding to its index
  87595. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87596. */
  87597. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87598. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87599. };
  87600. ReflectionProbe.prototype.dispose = function () {
  87601. var index = this._scene.reflectionProbes.indexOf(this);
  87602. if (index !== -1) {
  87603. // Remove from the scene if found
  87604. this._scene.reflectionProbes.splice(index, 1);
  87605. }
  87606. if (this._renderTargetTexture) {
  87607. this._renderTargetTexture.dispose();
  87608. this._renderTargetTexture = null;
  87609. }
  87610. };
  87611. return ReflectionProbe;
  87612. }());
  87613. BABYLON.ReflectionProbe = ReflectionProbe;
  87614. })(BABYLON || (BABYLON = {}));
  87615. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87616. var BABYLON;
  87617. (function (BABYLON) {
  87618. var Layer = /** @class */ (function () {
  87619. function Layer(name, imgUrl, scene, isBackground, color) {
  87620. this.name = name;
  87621. this.scale = new BABYLON.Vector2(1, 1);
  87622. this.offset = new BABYLON.Vector2(0, 0);
  87623. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87624. this.layerMask = 0x0FFFFFFF;
  87625. this._vertexBuffers = {};
  87626. // Events
  87627. /**
  87628. * An event triggered when the layer is disposed.
  87629. * @type {BABYLON.Observable}
  87630. */
  87631. this.onDisposeObservable = new BABYLON.Observable();
  87632. /**
  87633. * An event triggered before rendering the scene
  87634. * @type {BABYLON.Observable}
  87635. */
  87636. this.onBeforeRenderObservable = new BABYLON.Observable();
  87637. /**
  87638. * An event triggered after rendering the scene
  87639. * @type {BABYLON.Observable}
  87640. */
  87641. this.onAfterRenderObservable = new BABYLON.Observable();
  87642. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87643. this.isBackground = isBackground === undefined ? true : isBackground;
  87644. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87645. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87646. this._scene.layers.push(this);
  87647. var engine = this._scene.getEngine();
  87648. // VBO
  87649. var vertices = [];
  87650. vertices.push(1, 1);
  87651. vertices.push(-1, 1);
  87652. vertices.push(-1, -1);
  87653. vertices.push(1, -1);
  87654. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87655. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87656. this._createIndexBuffer();
  87657. // Effects
  87658. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87659. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87660. }
  87661. Object.defineProperty(Layer.prototype, "onDispose", {
  87662. set: function (callback) {
  87663. if (this._onDisposeObserver) {
  87664. this.onDisposeObservable.remove(this._onDisposeObserver);
  87665. }
  87666. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87667. },
  87668. enumerable: true,
  87669. configurable: true
  87670. });
  87671. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87672. set: function (callback) {
  87673. if (this._onBeforeRenderObserver) {
  87674. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87675. }
  87676. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87677. },
  87678. enumerable: true,
  87679. configurable: true
  87680. });
  87681. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87682. set: function (callback) {
  87683. if (this._onAfterRenderObserver) {
  87684. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87685. }
  87686. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87687. },
  87688. enumerable: true,
  87689. configurable: true
  87690. });
  87691. Layer.prototype._createIndexBuffer = function () {
  87692. var engine = this._scene.getEngine();
  87693. // Indices
  87694. var indices = [];
  87695. indices.push(0);
  87696. indices.push(1);
  87697. indices.push(2);
  87698. indices.push(0);
  87699. indices.push(2);
  87700. indices.push(3);
  87701. this._indexBuffer = engine.createIndexBuffer(indices);
  87702. };
  87703. Layer.prototype._rebuild = function () {
  87704. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87705. if (vb) {
  87706. vb._rebuild();
  87707. }
  87708. this._createIndexBuffer();
  87709. };
  87710. Layer.prototype.render = function () {
  87711. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87712. // Check
  87713. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87714. return;
  87715. var engine = this._scene.getEngine();
  87716. this.onBeforeRenderObservable.notifyObservers(this);
  87717. // Render
  87718. engine.enableEffect(currentEffect);
  87719. engine.setState(false);
  87720. // Texture
  87721. currentEffect.setTexture("textureSampler", this.texture);
  87722. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87723. // Color
  87724. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87725. // Scale / offset
  87726. currentEffect.setVector2("offset", this.offset);
  87727. currentEffect.setVector2("scale", this.scale);
  87728. // VBOs
  87729. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87730. // Draw order
  87731. if (!this.alphaTest) {
  87732. engine.setAlphaMode(this.alphaBlendingMode);
  87733. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87734. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87735. }
  87736. else {
  87737. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87738. }
  87739. this.onAfterRenderObservable.notifyObservers(this);
  87740. };
  87741. Layer.prototype.dispose = function () {
  87742. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87743. if (vertexBuffer) {
  87744. vertexBuffer.dispose();
  87745. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87746. }
  87747. if (this._indexBuffer) {
  87748. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87749. this._indexBuffer = null;
  87750. }
  87751. if (this.texture) {
  87752. this.texture.dispose();
  87753. this.texture = null;
  87754. }
  87755. // Remove from scene
  87756. var index = this._scene.layers.indexOf(this);
  87757. this._scene.layers.splice(index, 1);
  87758. // Callback
  87759. this.onDisposeObservable.notifyObservers(this);
  87760. this.onDisposeObservable.clear();
  87761. this.onAfterRenderObservable.clear();
  87762. this.onBeforeRenderObservable.clear();
  87763. };
  87764. return Layer;
  87765. }());
  87766. BABYLON.Layer = Layer;
  87767. })(BABYLON || (BABYLON = {}));
  87768. //# sourceMappingURL=babylon.layer.js.map
  87769. var BABYLON;
  87770. (function (BABYLON) {
  87771. var TextureTools = /** @class */ (function () {
  87772. function TextureTools() {
  87773. }
  87774. /**
  87775. * Uses the GPU to create a copy texture rescaled at a given size
  87776. * @param texture Texture to copy from
  87777. * @param width Desired width
  87778. * @param height Desired height
  87779. * @return Generated texture
  87780. */
  87781. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87782. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87783. var scene = texture.getScene();
  87784. var engine = scene.getEngine();
  87785. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87786. rtt.wrapU = texture.wrapU;
  87787. rtt.wrapV = texture.wrapV;
  87788. rtt.uOffset = texture.uOffset;
  87789. rtt.vOffset = texture.vOffset;
  87790. rtt.uScale = texture.uScale;
  87791. rtt.vScale = texture.vScale;
  87792. rtt.uAng = texture.uAng;
  87793. rtt.vAng = texture.vAng;
  87794. rtt.wAng = texture.wAng;
  87795. rtt.coordinatesIndex = texture.coordinatesIndex;
  87796. rtt.level = texture.level;
  87797. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87798. rtt._texture.isReady = false;
  87799. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87800. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87801. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87802. passPostProcess.getEffect().executeWhenCompiled(function () {
  87803. passPostProcess.onApply = function (effect) {
  87804. effect.setTexture("textureSampler", texture);
  87805. };
  87806. var internalTexture = rtt.getInternalTexture();
  87807. if (internalTexture) {
  87808. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87809. engine.unBindFramebuffer(internalTexture);
  87810. rtt.disposeFramebufferObjects();
  87811. passPostProcess.dispose();
  87812. internalTexture.isReady = true;
  87813. }
  87814. });
  87815. return rtt;
  87816. };
  87817. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87818. if (!scene._environmentBRDFTexture) {
  87819. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87820. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87821. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87822. scene._environmentBRDFTexture = texture;
  87823. }
  87824. return scene._environmentBRDFTexture;
  87825. };
  87826. 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=";
  87827. return TextureTools;
  87828. }());
  87829. BABYLON.TextureTools = TextureTools;
  87830. })(BABYLON || (BABYLON = {}));
  87831. //# sourceMappingURL=babylon.textureTools.js.map
  87832. var BABYLON;
  87833. (function (BABYLON) {
  87834. var FramingBehavior = /** @class */ (function () {
  87835. function FramingBehavior() {
  87836. this._mode = FramingBehavior.FitFrustumSidesMode;
  87837. this._radiusScale = 1.0;
  87838. this._positionScale = 0.5;
  87839. this._defaultElevation = 0.3;
  87840. this._elevationReturnTime = 1500;
  87841. this._elevationReturnWaitTime = 1000;
  87842. this._zoomStopsAnimation = false;
  87843. this._framingTime = 1500;
  87844. this._isPointerDown = false;
  87845. this._lastInteractionTime = -Infinity;
  87846. // Framing control
  87847. this._animatables = new Array();
  87848. this._betaIsAnimating = false;
  87849. }
  87850. Object.defineProperty(FramingBehavior.prototype, "name", {
  87851. get: function () {
  87852. return "Framing";
  87853. },
  87854. enumerable: true,
  87855. configurable: true
  87856. });
  87857. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87858. /**
  87859. * Gets current mode used by the behavior.
  87860. */
  87861. get: function () {
  87862. return this._mode;
  87863. },
  87864. /**
  87865. * Sets the current mode used by the behavior
  87866. */
  87867. set: function (mode) {
  87868. this._mode = mode;
  87869. },
  87870. enumerable: true,
  87871. configurable: true
  87872. });
  87873. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87874. /**
  87875. * Gets the scale applied to the radius
  87876. */
  87877. get: function () {
  87878. return this._radiusScale;
  87879. },
  87880. /**
  87881. * Sets the scale applied to the radius (1 by default)
  87882. */
  87883. set: function (radius) {
  87884. this._radiusScale = radius;
  87885. },
  87886. enumerable: true,
  87887. configurable: true
  87888. });
  87889. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87890. /**
  87891. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87892. */
  87893. get: function () {
  87894. return this._positionScale;
  87895. },
  87896. /**
  87897. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87898. */
  87899. set: function (scale) {
  87900. this._positionScale = scale;
  87901. },
  87902. enumerable: true,
  87903. configurable: true
  87904. });
  87905. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87906. /**
  87907. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87908. * behaviour is triggered, in radians.
  87909. */
  87910. get: function () {
  87911. return this._defaultElevation;
  87912. },
  87913. /**
  87914. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87915. * behaviour is triggered, in radians.
  87916. */
  87917. set: function (elevation) {
  87918. this._defaultElevation = elevation;
  87919. },
  87920. enumerable: true,
  87921. configurable: true
  87922. });
  87923. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87924. /**
  87925. * Gets the time (in milliseconds) taken to return to the default beta position.
  87926. * Negative value indicates camera should not return to default.
  87927. */
  87928. get: function () {
  87929. return this._elevationReturnTime;
  87930. },
  87931. /**
  87932. * Sets the time (in milliseconds) taken to return to the default beta position.
  87933. * Negative value indicates camera should not return to default.
  87934. */
  87935. set: function (speed) {
  87936. this._elevationReturnTime = speed;
  87937. },
  87938. enumerable: true,
  87939. configurable: true
  87940. });
  87941. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87942. /**
  87943. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87944. */
  87945. get: function () {
  87946. return this._elevationReturnWaitTime;
  87947. },
  87948. /**
  87949. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87950. */
  87951. set: function (time) {
  87952. this._elevationReturnWaitTime = time;
  87953. },
  87954. enumerable: true,
  87955. configurable: true
  87956. });
  87957. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87958. /**
  87959. * Gets the flag that indicates if user zooming should stop animation.
  87960. */
  87961. get: function () {
  87962. return this._zoomStopsAnimation;
  87963. },
  87964. /**
  87965. * Sets the flag that indicates if user zooming should stop animation.
  87966. */
  87967. set: function (flag) {
  87968. this._zoomStopsAnimation = flag;
  87969. },
  87970. enumerable: true,
  87971. configurable: true
  87972. });
  87973. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87974. /**
  87975. * Gets the transition time when framing the mesh, in milliseconds
  87976. */
  87977. get: function () {
  87978. return this._framingTime;
  87979. },
  87980. /**
  87981. * Sets the transition time when framing the mesh, in milliseconds
  87982. */
  87983. set: function (time) {
  87984. this._framingTime = time;
  87985. },
  87986. enumerable: true,
  87987. configurable: true
  87988. });
  87989. FramingBehavior.prototype.init = function () {
  87990. // Do notihng
  87991. };
  87992. FramingBehavior.prototype.attach = function (camera) {
  87993. var _this = this;
  87994. this._attachedCamera = camera;
  87995. var scene = this._attachedCamera.getScene();
  87996. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87997. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87998. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87999. _this._isPointerDown = true;
  88000. return;
  88001. }
  88002. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88003. _this._isPointerDown = false;
  88004. }
  88005. });
  88006. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88007. if (mesh) {
  88008. _this.zoomOnMesh(mesh);
  88009. }
  88010. });
  88011. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88012. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88013. _this._applyUserInteraction();
  88014. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88015. // back to the default position after a given timeout
  88016. _this._maintainCameraAboveGround();
  88017. });
  88018. };
  88019. FramingBehavior.prototype.detach = function () {
  88020. if (!this._attachedCamera) {
  88021. return;
  88022. }
  88023. var scene = this._attachedCamera.getScene();
  88024. if (this._onPrePointerObservableObserver) {
  88025. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88026. }
  88027. if (this._onAfterCheckInputsObserver) {
  88028. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88029. }
  88030. if (this._onMeshTargetChangedObserver) {
  88031. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88032. }
  88033. this._attachedCamera = null;
  88034. };
  88035. /**
  88036. * Targets the given mesh and updates zoom level accordingly.
  88037. * @param mesh The mesh to target.
  88038. * @param radius Optional. If a cached radius position already exists, overrides default.
  88039. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88040. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88041. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88042. */
  88043. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88044. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88045. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88046. mesh.computeWorldMatrix(true);
  88047. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88048. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88049. };
  88050. /**
  88051. * Targets the given mesh with its children and updates zoom level accordingly.
  88052. * @param mesh The mesh to target.
  88053. * @param radius Optional. If a cached radius position already exists, overrides default.
  88054. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88055. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88056. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88057. */
  88058. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88059. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88060. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88061. mesh.computeWorldMatrix(true);
  88062. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88063. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88064. };
  88065. /**
  88066. * Targets the given meshes with their children and updates zoom level accordingly.
  88067. * @param meshes The mesh to target.
  88068. * @param radius Optional. If a cached radius position already exists, overrides default.
  88069. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88070. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88071. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88072. */
  88073. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88074. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88076. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88077. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88078. for (var i = 0; i < meshes.length; i++) {
  88079. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88080. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88081. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88082. }
  88083. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88084. };
  88085. /**
  88086. * Targets the given mesh and updates zoom level accordingly.
  88087. * @param mesh The mesh to target.
  88088. * @param radius Optional. If a cached radius position already exists, overrides default.
  88089. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88090. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88091. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88092. */
  88093. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88094. var _this = this;
  88095. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88096. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88097. var zoomTarget;
  88098. if (!this._attachedCamera) {
  88099. return;
  88100. }
  88101. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88102. var bottom = minimumWorld.y;
  88103. var top = maximumWorld.y;
  88104. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88105. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88106. if (focusOnOriginXZ) {
  88107. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88108. }
  88109. else {
  88110. var centerWorld = minimumWorld.add(radiusWorld);
  88111. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88112. }
  88113. if (!this._vectorTransition) {
  88114. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88115. }
  88116. this._betaIsAnimating = true;
  88117. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88118. if (animatable) {
  88119. this._animatables.push(animatable);
  88120. }
  88121. // sets the radius and lower radius bounds
  88122. // Small delta ensures camera is not always at lower zoom limit.
  88123. var radius = 0;
  88124. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88125. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88126. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88127. radius = position;
  88128. }
  88129. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88130. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88131. if (this._attachedCamera.lowerRadiusLimit === null) {
  88132. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88133. }
  88134. }
  88135. // Set sensibilities
  88136. var extend = maximumWorld.subtract(minimumWorld).length();
  88137. this._attachedCamera.panningSensibility = 5000 / extend;
  88138. this._attachedCamera.wheelPrecision = 100 / radius;
  88139. // transition to new radius
  88140. if (!this._radiusTransition) {
  88141. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88142. }
  88143. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88144. _this.stopAllAnimations();
  88145. if (onAnimationEnd) {
  88146. onAnimationEnd();
  88147. }
  88148. if (_this._attachedCamera) {
  88149. _this._attachedCamera.storeState();
  88150. }
  88151. });
  88152. if (animatable) {
  88153. this._animatables.push(animatable);
  88154. }
  88155. };
  88156. /**
  88157. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88158. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88159. * frustum width.
  88160. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88161. * to fully enclose the mesh in the viewing frustum.
  88162. */
  88163. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88164. var size = maximumWorld.subtract(minimumWorld);
  88165. var boxVectorGlobalDiagonal = size.length();
  88166. var frustumSlope = this._getFrustumSlope();
  88167. // Formula for setting distance
  88168. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88169. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88170. // Horizon distance
  88171. var radius = radiusWithoutFraming * this._radiusScale;
  88172. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88173. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88174. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88175. var camera = this._attachedCamera;
  88176. if (!camera) {
  88177. return 0;
  88178. }
  88179. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88180. // Don't exceed the requested limit
  88181. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88182. }
  88183. // Don't exceed the upper radius limit
  88184. if (camera.upperRadiusLimit) {
  88185. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88186. }
  88187. return distance;
  88188. };
  88189. /**
  88190. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88191. * is automatically returned to its default position (expected to be above ground plane).
  88192. */
  88193. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88194. var _this = this;
  88195. if (this._elevationReturnTime < 0) {
  88196. return;
  88197. }
  88198. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88199. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88200. var limitBeta = Math.PI * 0.5;
  88201. // Bring the camera back up if below the ground plane
  88202. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88203. this._betaIsAnimating = true;
  88204. //Transition to new position
  88205. this.stopAllAnimations();
  88206. if (!this._betaTransition) {
  88207. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88208. }
  88209. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88210. _this._clearAnimationLocks();
  88211. _this.stopAllAnimations();
  88212. });
  88213. if (animatabe) {
  88214. this._animatables.push(animatabe);
  88215. }
  88216. }
  88217. };
  88218. /**
  88219. * Returns the frustum slope based on the canvas ratio and camera FOV
  88220. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88221. */
  88222. FramingBehavior.prototype._getFrustumSlope = function () {
  88223. // Calculate the viewport ratio
  88224. // Aspect Ratio is Height/Width.
  88225. var camera = this._attachedCamera;
  88226. if (!camera) {
  88227. return BABYLON.Vector2.Zero();
  88228. }
  88229. var engine = camera.getScene().getEngine();
  88230. var aspectRatio = engine.getAspectRatio(camera);
  88231. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88232. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88233. var frustumSlopeY = Math.tan(camera.fov / 2);
  88234. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88235. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88236. // along the forward vector.
  88237. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88238. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88239. };
  88240. /**
  88241. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88242. */
  88243. FramingBehavior.prototype._clearAnimationLocks = function () {
  88244. this._betaIsAnimating = false;
  88245. };
  88246. /**
  88247. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88248. */
  88249. FramingBehavior.prototype._applyUserInteraction = function () {
  88250. if (this.isUserIsMoving) {
  88251. this._lastInteractionTime = BABYLON.Tools.Now;
  88252. this.stopAllAnimations();
  88253. this._clearAnimationLocks();
  88254. }
  88255. };
  88256. /**
  88257. * Stops and removes all animations that have been applied to the camera
  88258. */
  88259. FramingBehavior.prototype.stopAllAnimations = function () {
  88260. if (this._attachedCamera) {
  88261. this._attachedCamera.animations = [];
  88262. }
  88263. while (this._animatables.length) {
  88264. if (this._animatables[0]) {
  88265. this._animatables[0].onAnimationEnd = null;
  88266. this._animatables[0].stop();
  88267. }
  88268. this._animatables.shift();
  88269. }
  88270. };
  88271. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88272. /**
  88273. * Gets a value indicating if the user is moving the camera
  88274. */
  88275. get: function () {
  88276. if (!this._attachedCamera) {
  88277. return false;
  88278. }
  88279. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88280. this._attachedCamera.inertialBetaOffset !== 0 ||
  88281. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88282. this._attachedCamera.inertialPanningX !== 0 ||
  88283. this._attachedCamera.inertialPanningY !== 0 ||
  88284. this._isPointerDown;
  88285. },
  88286. enumerable: true,
  88287. configurable: true
  88288. });
  88289. /**
  88290. * The easing function used by animations
  88291. */
  88292. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88293. /**
  88294. * The easing mode used by animations
  88295. */
  88296. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88297. // Statics
  88298. /**
  88299. * The camera can move all the way towards the mesh.
  88300. */
  88301. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88302. /**
  88303. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88304. */
  88305. FramingBehavior.FitFrustumSidesMode = 1;
  88306. return FramingBehavior;
  88307. }());
  88308. BABYLON.FramingBehavior = FramingBehavior;
  88309. })(BABYLON || (BABYLON = {}));
  88310. //# sourceMappingURL=babylon.framingBehavior.js.map
  88311. var BABYLON;
  88312. (function (BABYLON) {
  88313. /**
  88314. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88315. */
  88316. var BouncingBehavior = /** @class */ (function () {
  88317. function BouncingBehavior() {
  88318. /**
  88319. * The duration of the animation, in milliseconds
  88320. */
  88321. this.transitionDuration = 450;
  88322. /**
  88323. * Length of the distance animated by the transition when lower radius is reached
  88324. */
  88325. this.lowerRadiusTransitionRange = 2;
  88326. /**
  88327. * Length of the distance animated by the transition when upper radius is reached
  88328. */
  88329. this.upperRadiusTransitionRange = -2;
  88330. this._autoTransitionRange = false;
  88331. // Animations
  88332. this._radiusIsAnimating = false;
  88333. this._radiusBounceTransition = null;
  88334. this._animatables = new Array();
  88335. }
  88336. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88337. get: function () {
  88338. return "Bouncing";
  88339. },
  88340. enumerable: true,
  88341. configurable: true
  88342. });
  88343. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88344. /**
  88345. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88346. */
  88347. get: function () {
  88348. return this._autoTransitionRange;
  88349. },
  88350. /**
  88351. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88352. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88353. */
  88354. set: function (value) {
  88355. var _this = this;
  88356. if (this._autoTransitionRange === value) {
  88357. return;
  88358. }
  88359. this._autoTransitionRange = value;
  88360. var camera = this._attachedCamera;
  88361. if (!camera) {
  88362. return;
  88363. }
  88364. if (value) {
  88365. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88366. if (!mesh) {
  88367. return;
  88368. }
  88369. mesh.computeWorldMatrix(true);
  88370. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88371. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88372. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88373. });
  88374. }
  88375. else if (this._onMeshTargetChangedObserver) {
  88376. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88377. }
  88378. },
  88379. enumerable: true,
  88380. configurable: true
  88381. });
  88382. BouncingBehavior.prototype.init = function () {
  88383. // Do notihng
  88384. };
  88385. BouncingBehavior.prototype.attach = function (camera) {
  88386. var _this = this;
  88387. this._attachedCamera = camera;
  88388. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88389. if (!_this._attachedCamera) {
  88390. return;
  88391. }
  88392. // Add the bounce animation to the lower radius limit
  88393. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88394. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88395. }
  88396. // Add the bounce animation to the upper radius limit
  88397. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88398. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88399. }
  88400. });
  88401. };
  88402. BouncingBehavior.prototype.detach = function () {
  88403. if (!this._attachedCamera) {
  88404. return;
  88405. }
  88406. if (this._onAfterCheckInputsObserver) {
  88407. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88408. }
  88409. if (this._onMeshTargetChangedObserver) {
  88410. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88411. }
  88412. this._attachedCamera = null;
  88413. };
  88414. /**
  88415. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88416. * @param radiusLimit The limit to check against.
  88417. * @return Bool to indicate if at limit.
  88418. */
  88419. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88420. if (!this._attachedCamera) {
  88421. return false;
  88422. }
  88423. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88424. return true;
  88425. }
  88426. return false;
  88427. };
  88428. /**
  88429. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88430. * @param radiusDelta The delta by which to animate to. Can be negative.
  88431. */
  88432. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88433. var _this = this;
  88434. if (!this._attachedCamera) {
  88435. return;
  88436. }
  88437. if (!this._radiusBounceTransition) {
  88438. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88439. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88440. }
  88441. // Prevent zoom until bounce has completed
  88442. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88443. this._attachedCamera.wheelPrecision = Infinity;
  88444. this._attachedCamera.inertialRadiusOffset = 0;
  88445. // Animate to the radius limit
  88446. this.stopAllAnimations();
  88447. this._radiusIsAnimating = true;
  88448. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88449. if (animatable) {
  88450. this._animatables.push(animatable);
  88451. }
  88452. };
  88453. /**
  88454. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88455. */
  88456. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88457. this._radiusIsAnimating = false;
  88458. if (this._attachedCamera) {
  88459. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88460. }
  88461. };
  88462. /**
  88463. * Stops and removes all animations that have been applied to the camera
  88464. */
  88465. BouncingBehavior.prototype.stopAllAnimations = function () {
  88466. if (this._attachedCamera) {
  88467. this._attachedCamera.animations = [];
  88468. }
  88469. while (this._animatables.length) {
  88470. this._animatables[0].onAnimationEnd = null;
  88471. this._animatables[0].stop();
  88472. this._animatables.shift();
  88473. }
  88474. };
  88475. /**
  88476. * The easing function used by animations
  88477. */
  88478. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88479. /**
  88480. * The easing mode used by animations
  88481. */
  88482. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88483. return BouncingBehavior;
  88484. }());
  88485. BABYLON.BouncingBehavior = BouncingBehavior;
  88486. })(BABYLON || (BABYLON = {}));
  88487. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88488. var BABYLON;
  88489. (function (BABYLON) {
  88490. var AutoRotationBehavior = /** @class */ (function () {
  88491. function AutoRotationBehavior() {
  88492. this._zoomStopsAnimation = false;
  88493. this._idleRotationSpeed = 0.05;
  88494. this._idleRotationWaitTime = 2000;
  88495. this._idleRotationSpinupTime = 2000;
  88496. this._isPointerDown = false;
  88497. this._lastFrameTime = null;
  88498. this._lastInteractionTime = -Infinity;
  88499. this._cameraRotationSpeed = 0;
  88500. this._lastFrameRadius = 0;
  88501. }
  88502. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88503. get: function () {
  88504. return "AutoRotation";
  88505. },
  88506. enumerable: true,
  88507. configurable: true
  88508. });
  88509. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88510. /**
  88511. * Gets the flag that indicates if user zooming should stop animation.
  88512. */
  88513. get: function () {
  88514. return this._zoomStopsAnimation;
  88515. },
  88516. /**
  88517. * Sets the flag that indicates if user zooming should stop animation.
  88518. */
  88519. set: function (flag) {
  88520. this._zoomStopsAnimation = flag;
  88521. },
  88522. enumerable: true,
  88523. configurable: true
  88524. });
  88525. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88526. /**
  88527. * Gets the default speed at which the camera rotates around the model.
  88528. */
  88529. get: function () {
  88530. return this._idleRotationSpeed;
  88531. },
  88532. /**
  88533. * Sets the default speed at which the camera rotates around the model.
  88534. */
  88535. set: function (speed) {
  88536. this._idleRotationSpeed = speed;
  88537. },
  88538. enumerable: true,
  88539. configurable: true
  88540. });
  88541. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88542. /**
  88543. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88544. */
  88545. get: function () {
  88546. return this._idleRotationWaitTime;
  88547. },
  88548. /**
  88549. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88550. */
  88551. set: function (time) {
  88552. this._idleRotationWaitTime = time;
  88553. },
  88554. enumerable: true,
  88555. configurable: true
  88556. });
  88557. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88558. /**
  88559. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88560. */
  88561. get: function () {
  88562. return this._idleRotationSpinupTime;
  88563. },
  88564. /**
  88565. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88566. */
  88567. set: function (time) {
  88568. this._idleRotationSpinupTime = time;
  88569. },
  88570. enumerable: true,
  88571. configurable: true
  88572. });
  88573. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88574. /**
  88575. * Gets a value indicating if the camera is currently rotating because of this behavior
  88576. */
  88577. get: function () {
  88578. return Math.abs(this._cameraRotationSpeed) > 0;
  88579. },
  88580. enumerable: true,
  88581. configurable: true
  88582. });
  88583. AutoRotationBehavior.prototype.init = function () {
  88584. // Do notihng
  88585. };
  88586. AutoRotationBehavior.prototype.attach = function (camera) {
  88587. var _this = this;
  88588. this._attachedCamera = camera;
  88589. var scene = this._attachedCamera.getScene();
  88590. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88591. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88592. _this._isPointerDown = true;
  88593. return;
  88594. }
  88595. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88596. _this._isPointerDown = false;
  88597. }
  88598. });
  88599. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88600. var now = BABYLON.Tools.Now;
  88601. var dt = 0;
  88602. if (_this._lastFrameTime != null) {
  88603. dt = now - _this._lastFrameTime;
  88604. }
  88605. _this._lastFrameTime = now;
  88606. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88607. _this._applyUserInteraction();
  88608. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88609. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88610. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88611. // Step camera rotation by rotation speed
  88612. if (_this._attachedCamera) {
  88613. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88614. }
  88615. });
  88616. };
  88617. AutoRotationBehavior.prototype.detach = function () {
  88618. if (!this._attachedCamera) {
  88619. return;
  88620. }
  88621. var scene = this._attachedCamera.getScene();
  88622. if (this._onPrePointerObservableObserver) {
  88623. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88624. }
  88625. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88626. this._attachedCamera = null;
  88627. };
  88628. /**
  88629. * Returns true if user is scrolling.
  88630. * @return true if user is scrolling.
  88631. */
  88632. AutoRotationBehavior.prototype._userIsZooming = function () {
  88633. if (!this._attachedCamera) {
  88634. return false;
  88635. }
  88636. return this._attachedCamera.inertialRadiusOffset !== 0;
  88637. };
  88638. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88639. if (!this._attachedCamera) {
  88640. return false;
  88641. }
  88642. var zoomHasHitLimit = false;
  88643. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88644. zoomHasHitLimit = true;
  88645. }
  88646. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88647. this._lastFrameRadius = this._attachedCamera.radius;
  88648. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88649. };
  88650. /**
  88651. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88652. */
  88653. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88654. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88655. this._lastInteractionTime = BABYLON.Tools.Now;
  88656. }
  88657. };
  88658. // Tools
  88659. AutoRotationBehavior.prototype._userIsMoving = function () {
  88660. if (!this._attachedCamera) {
  88661. return false;
  88662. }
  88663. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88664. this._attachedCamera.inertialBetaOffset !== 0 ||
  88665. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88666. this._attachedCamera.inertialPanningX !== 0 ||
  88667. this._attachedCamera.inertialPanningY !== 0 ||
  88668. this._isPointerDown;
  88669. };
  88670. return AutoRotationBehavior;
  88671. }());
  88672. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88673. })(BABYLON || (BABYLON = {}));
  88674. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88675. var BABYLON;
  88676. (function (BABYLON) {
  88677. var NullEngineOptions = /** @class */ (function () {
  88678. function NullEngineOptions() {
  88679. this.renderWidth = 512;
  88680. this.renderHeight = 256;
  88681. this.textureSize = 512;
  88682. this.deterministicLockstep = false;
  88683. this.lockstepMaxSteps = 4;
  88684. }
  88685. return NullEngineOptions;
  88686. }());
  88687. BABYLON.NullEngineOptions = NullEngineOptions;
  88688. /**
  88689. * The null engine class provides support for headless version of babylon.js.
  88690. * This can be used in server side scenario or for testing purposes
  88691. */
  88692. var NullEngine = /** @class */ (function (_super) {
  88693. __extends(NullEngine, _super);
  88694. function NullEngine(options) {
  88695. if (options === void 0) { options = new NullEngineOptions(); }
  88696. var _this = _super.call(this, null) || this;
  88697. if (options.deterministicLockstep === undefined) {
  88698. options.deterministicLockstep = false;
  88699. }
  88700. if (options.lockstepMaxSteps === undefined) {
  88701. options.lockstepMaxSteps = 4;
  88702. }
  88703. _this._options = options;
  88704. // Init caps
  88705. // We consider we are on a webgl1 capable device
  88706. _this._caps = new BABYLON.EngineCapabilities();
  88707. _this._caps.maxTexturesImageUnits = 16;
  88708. _this._caps.maxVertexTextureImageUnits = 16;
  88709. _this._caps.maxTextureSize = 512;
  88710. _this._caps.maxCubemapTextureSize = 512;
  88711. _this._caps.maxRenderTextureSize = 512;
  88712. _this._caps.maxVertexAttribs = 16;
  88713. _this._caps.maxVaryingVectors = 16;
  88714. _this._caps.maxFragmentUniformVectors = 16;
  88715. _this._caps.maxVertexUniformVectors = 16;
  88716. // Extensions
  88717. _this._caps.standardDerivatives = false;
  88718. _this._caps.astc = null;
  88719. _this._caps.s3tc = null;
  88720. _this._caps.pvrtc = null;
  88721. _this._caps.etc1 = null;
  88722. _this._caps.etc2 = null;
  88723. _this._caps.textureAnisotropicFilterExtension = null;
  88724. _this._caps.maxAnisotropy = 0;
  88725. _this._caps.uintIndices = false;
  88726. _this._caps.fragmentDepthSupported = false;
  88727. _this._caps.highPrecisionShaderSupported = true;
  88728. _this._caps.colorBufferFloat = false;
  88729. _this._caps.textureFloat = false;
  88730. _this._caps.textureFloatLinearFiltering = false;
  88731. _this._caps.textureFloatRender = false;
  88732. _this._caps.textureHalfFloat = false;
  88733. _this._caps.textureHalfFloatLinearFiltering = false;
  88734. _this._caps.textureHalfFloatRender = false;
  88735. _this._caps.textureLOD = false;
  88736. _this._caps.drawBuffersExtension = false;
  88737. _this._caps.depthTextureExtension = false;
  88738. _this._caps.vertexArrayObject = false;
  88739. _this._caps.instancedArrays = false;
  88740. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88741. // Wrappers
  88742. if (typeof URL === "undefined") {
  88743. URL = {
  88744. createObjectURL: function () { },
  88745. revokeObjectURL: function () { }
  88746. };
  88747. }
  88748. if (typeof Blob === "undefined") {
  88749. Blob = function () { };
  88750. }
  88751. return _this;
  88752. }
  88753. NullEngine.prototype.isDeterministicLockStep = function () {
  88754. return this._options.deterministicLockstep;
  88755. };
  88756. NullEngine.prototype.getLockstepMaxSteps = function () {
  88757. return this._options.lockstepMaxSteps;
  88758. };
  88759. NullEngine.prototype.getHardwareScalingLevel = function () {
  88760. return 1.0;
  88761. };
  88762. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88763. return {
  88764. capacity: 0,
  88765. references: 1,
  88766. is32Bits: false
  88767. };
  88768. };
  88769. NullEngine.prototype.createIndexBuffer = function (indices) {
  88770. return {
  88771. capacity: 0,
  88772. references: 1,
  88773. is32Bits: false
  88774. };
  88775. };
  88776. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88777. if (stencil === void 0) { stencil = false; }
  88778. };
  88779. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88780. if (useScreen === void 0) { useScreen = false; }
  88781. if (!useScreen && this._currentRenderTarget) {
  88782. return this._currentRenderTarget.width;
  88783. }
  88784. return this._options.renderWidth;
  88785. };
  88786. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88787. if (useScreen === void 0) { useScreen = false; }
  88788. if (!useScreen && this._currentRenderTarget) {
  88789. return this._currentRenderTarget.height;
  88790. }
  88791. return this._options.renderHeight;
  88792. };
  88793. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88794. this._cachedViewport = viewport;
  88795. };
  88796. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88797. return {
  88798. transformFeedback: null,
  88799. __SPECTOR_rebuildProgram: null
  88800. };
  88801. };
  88802. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88803. return [];
  88804. };
  88805. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88806. return [];
  88807. };
  88808. NullEngine.prototype.bindSamplers = function (effect) {
  88809. this._currentEffect = null;
  88810. };
  88811. NullEngine.prototype.enableEffect = function (effect) {
  88812. this._currentEffect = effect;
  88813. if (effect.onBind) {
  88814. effect.onBind(effect);
  88815. }
  88816. effect.onBindObservable.notifyObservers(effect);
  88817. };
  88818. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88819. if (zOffset === void 0) { zOffset = 0; }
  88820. if (reverseSide === void 0) { reverseSide = false; }
  88821. };
  88822. NullEngine.prototype.setIntArray = function (uniform, array) {
  88823. };
  88824. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88825. };
  88826. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88827. };
  88828. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88829. };
  88830. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88831. };
  88832. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88833. };
  88834. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88835. };
  88836. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88837. };
  88838. NullEngine.prototype.setArray = function (uniform, array) {
  88839. };
  88840. NullEngine.prototype.setArray2 = function (uniform, array) {
  88841. };
  88842. NullEngine.prototype.setArray3 = function (uniform, array) {
  88843. };
  88844. NullEngine.prototype.setArray4 = function (uniform, array) {
  88845. };
  88846. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88847. };
  88848. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88849. };
  88850. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88851. };
  88852. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88853. };
  88854. NullEngine.prototype.setFloat = function (uniform, value) {
  88855. };
  88856. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88857. };
  88858. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88859. };
  88860. NullEngine.prototype.setBool = function (uniform, bool) {
  88861. };
  88862. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88863. };
  88864. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88865. };
  88866. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88867. };
  88868. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88869. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88870. if (this._alphaMode === mode) {
  88871. return;
  88872. }
  88873. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88874. if (!noDepthWriteChange) {
  88875. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88876. }
  88877. this._alphaMode = mode;
  88878. };
  88879. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88880. };
  88881. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88882. if (this.preventCacheWipeBetweenFrames) {
  88883. return;
  88884. }
  88885. this.resetTextureCache();
  88886. this._currentEffect = null;
  88887. if (bruteForce) {
  88888. this._currentProgram = null;
  88889. this._stencilState.reset();
  88890. this._depthCullingState.reset();
  88891. this._alphaState.reset();
  88892. }
  88893. this._cachedVertexBuffers = null;
  88894. this._cachedIndexBuffer = null;
  88895. this._cachedEffectForVertexBuffers = null;
  88896. };
  88897. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88898. };
  88899. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88900. };
  88901. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88902. };
  88903. NullEngine.prototype._createTexture = function () {
  88904. return {};
  88905. };
  88906. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88907. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88908. if (onLoad === void 0) { onLoad = null; }
  88909. if (onError === void 0) { onError = null; }
  88910. if (buffer === void 0) { buffer = null; }
  88911. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88912. var url = String(urlArg);
  88913. texture.url = url;
  88914. texture.generateMipMaps = !noMipmap;
  88915. texture.samplingMode = samplingMode;
  88916. texture.invertY = invertY;
  88917. texture.baseWidth = this._options.textureSize;
  88918. texture.baseHeight = this._options.textureSize;
  88919. texture.width = this._options.textureSize;
  88920. texture.height = this._options.textureSize;
  88921. if (format) {
  88922. texture.format = format;
  88923. }
  88924. texture.isReady = true;
  88925. if (onLoad) {
  88926. onLoad();
  88927. }
  88928. return texture;
  88929. };
  88930. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88931. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88932. if (options !== undefined && typeof options === "object") {
  88933. fullOptions.generateMipMaps = options.generateMipMaps;
  88934. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88935. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88936. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88937. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88938. }
  88939. else {
  88940. fullOptions.generateMipMaps = options;
  88941. fullOptions.generateDepthBuffer = true;
  88942. fullOptions.generateStencilBuffer = false;
  88943. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88944. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88945. }
  88946. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88947. var width = size.width || size;
  88948. var height = size.height || size;
  88949. texture._depthStencilBuffer = {};
  88950. texture._framebuffer = {};
  88951. texture.baseWidth = width;
  88952. texture.baseHeight = height;
  88953. texture.width = width;
  88954. texture.height = height;
  88955. texture.isReady = true;
  88956. texture.samples = 1;
  88957. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88958. texture.samplingMode = fullOptions.samplingMode;
  88959. texture.type = fullOptions.type;
  88960. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88961. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88962. return texture;
  88963. };
  88964. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88965. texture.samplingMode = samplingMode;
  88966. };
  88967. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88968. if (this._currentRenderTarget) {
  88969. this.unBindFramebuffer(this._currentRenderTarget);
  88970. }
  88971. this._currentRenderTarget = texture;
  88972. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88973. if (this._cachedViewport && !forceFullscreenViewport) {
  88974. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88975. }
  88976. };
  88977. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88978. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88979. this._currentRenderTarget = null;
  88980. if (onBeforeUnbind) {
  88981. if (texture._MSAAFramebuffer) {
  88982. this._currentFramebuffer = texture._framebuffer;
  88983. }
  88984. onBeforeUnbind();
  88985. }
  88986. this._currentFramebuffer = null;
  88987. };
  88988. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88989. var vbo = {
  88990. capacity: 1,
  88991. references: 1,
  88992. is32Bits: false
  88993. };
  88994. return vbo;
  88995. };
  88996. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88997. if (offset === void 0) { offset = 0; }
  88998. };
  88999. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89000. };
  89001. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89002. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89003. this._boundTexturesCache[this._activeChannel] = texture;
  89004. }
  89005. };
  89006. NullEngine.prototype._bindTexture = function (channel, texture) {
  89007. if (channel < 0) {
  89008. return;
  89009. }
  89010. this._bindTextureDirectly(0, texture);
  89011. };
  89012. NullEngine.prototype._releaseBuffer = function (buffer) {
  89013. buffer.references--;
  89014. if (buffer.references === 0) {
  89015. return true;
  89016. }
  89017. return false;
  89018. };
  89019. return NullEngine;
  89020. }(BABYLON.Engine));
  89021. BABYLON.NullEngine = NullEngine;
  89022. })(BABYLON || (BABYLON = {}));
  89023. //# sourceMappingURL=babylon.nullEngine.js.map
  89024. var BABYLON;
  89025. (function (BABYLON) {
  89026. /**
  89027. * This class can be used to get instrumentation data from a Babylon engine
  89028. */
  89029. var EngineInstrumentation = /** @class */ (function () {
  89030. function EngineInstrumentation(engine) {
  89031. this.engine = engine;
  89032. this._captureGPUFrameTime = false;
  89033. this._gpuFrameTime = new BABYLON.PerfCounter();
  89034. this._captureShaderCompilationTime = false;
  89035. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89036. // Observers
  89037. this._onBeginFrameObserver = null;
  89038. this._onEndFrameObserver = null;
  89039. this._onBeforeShaderCompilationObserver = null;
  89040. this._onAfterShaderCompilationObserver = null;
  89041. }
  89042. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89043. // Properties
  89044. /**
  89045. * Gets the perf counter used for GPU frame time
  89046. */
  89047. get: function () {
  89048. return this._gpuFrameTime;
  89049. },
  89050. enumerable: true,
  89051. configurable: true
  89052. });
  89053. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89054. /**
  89055. * Gets the GPU frame time capture status
  89056. */
  89057. get: function () {
  89058. return this._captureGPUFrameTime;
  89059. },
  89060. /**
  89061. * Enable or disable the GPU frame time capture
  89062. */
  89063. set: function (value) {
  89064. var _this = this;
  89065. if (value === this._captureGPUFrameTime) {
  89066. return;
  89067. }
  89068. this._captureGPUFrameTime = value;
  89069. if (value) {
  89070. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89071. if (!_this._gpuFrameTimeToken) {
  89072. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89073. }
  89074. });
  89075. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89076. if (!_this._gpuFrameTimeToken) {
  89077. return;
  89078. }
  89079. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89080. if (time > -1) {
  89081. _this._gpuFrameTimeToken = null;
  89082. _this._gpuFrameTime.fetchNewFrame();
  89083. _this._gpuFrameTime.addCount(time, true);
  89084. }
  89085. });
  89086. }
  89087. else {
  89088. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89089. this._onBeginFrameObserver = null;
  89090. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89091. this._onEndFrameObserver = null;
  89092. }
  89093. },
  89094. enumerable: true,
  89095. configurable: true
  89096. });
  89097. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89098. /**
  89099. * Gets the perf counter used for shader compilation time
  89100. */
  89101. get: function () {
  89102. return this._shaderCompilationTime;
  89103. },
  89104. enumerable: true,
  89105. configurable: true
  89106. });
  89107. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89108. /**
  89109. * Gets the shader compilation time capture status
  89110. */
  89111. get: function () {
  89112. return this._captureShaderCompilationTime;
  89113. },
  89114. /**
  89115. * Enable or disable the shader compilation time capture
  89116. */
  89117. set: function (value) {
  89118. var _this = this;
  89119. if (value === this._captureShaderCompilationTime) {
  89120. return;
  89121. }
  89122. this._captureShaderCompilationTime = value;
  89123. if (value) {
  89124. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89125. _this._shaderCompilationTime.fetchNewFrame();
  89126. _this._shaderCompilationTime.beginMonitoring();
  89127. });
  89128. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89129. _this._shaderCompilationTime.endMonitoring();
  89130. });
  89131. }
  89132. else {
  89133. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89134. this._onBeforeShaderCompilationObserver = null;
  89135. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89136. this._onAfterShaderCompilationObserver = null;
  89137. }
  89138. },
  89139. enumerable: true,
  89140. configurable: true
  89141. });
  89142. EngineInstrumentation.prototype.dispose = function () {
  89143. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89144. this._onBeginFrameObserver = null;
  89145. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89146. this._onEndFrameObserver = null;
  89147. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89148. this._onBeforeShaderCompilationObserver = null;
  89149. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89150. this._onAfterShaderCompilationObserver = null;
  89151. this.engine = null;
  89152. };
  89153. return EngineInstrumentation;
  89154. }());
  89155. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89156. })(BABYLON || (BABYLON = {}));
  89157. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89158. var BABYLON;
  89159. (function (BABYLON) {
  89160. /**
  89161. * This class can be used to get instrumentation data from a Babylon engine
  89162. */
  89163. var SceneInstrumentation = /** @class */ (function () {
  89164. function SceneInstrumentation(scene) {
  89165. var _this = this;
  89166. this.scene = scene;
  89167. this._captureActiveMeshesEvaluationTime = false;
  89168. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89169. this._captureRenderTargetsRenderTime = false;
  89170. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89171. this._captureFrameTime = false;
  89172. this._frameTime = new BABYLON.PerfCounter();
  89173. this._captureRenderTime = false;
  89174. this._renderTime = new BABYLON.PerfCounter();
  89175. this._captureInterFrameTime = false;
  89176. this._interFrameTime = new BABYLON.PerfCounter();
  89177. this._captureParticlesRenderTime = false;
  89178. this._particlesRenderTime = new BABYLON.PerfCounter();
  89179. this._captureSpritesRenderTime = false;
  89180. this._spritesRenderTime = new BABYLON.PerfCounter();
  89181. this._capturePhysicsTime = false;
  89182. this._physicsTime = new BABYLON.PerfCounter();
  89183. this._captureAnimationsTime = false;
  89184. this._animationsTime = new BABYLON.PerfCounter();
  89185. // Observers
  89186. this._onBeforeActiveMeshesEvaluationObserver = null;
  89187. this._onAfterActiveMeshesEvaluationObserver = null;
  89188. this._onBeforeRenderTargetsRenderObserver = null;
  89189. this._onAfterRenderTargetsRenderObserver = null;
  89190. this._onAfterRenderObserver = null;
  89191. this._onBeforeDrawPhaseObserver = null;
  89192. this._onAfterDrawPhaseObserver = null;
  89193. this._onBeforeAnimationsObserver = null;
  89194. this._onBeforeParticlesRenderingObserver = null;
  89195. this._onAfterParticlesRenderingObserver = null;
  89196. this._onBeforeSpritesRenderingObserver = null;
  89197. this._onAfterSpritesRenderingObserver = null;
  89198. this._onBeforePhysicsObserver = null;
  89199. this._onAfterPhysicsObserver = null;
  89200. this._onAfterAnimationsObserver = null;
  89201. // Before render
  89202. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89203. if (_this._captureActiveMeshesEvaluationTime) {
  89204. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89205. }
  89206. if (_this._captureRenderTargetsRenderTime) {
  89207. _this._renderTargetsRenderTime.fetchNewFrame();
  89208. }
  89209. if (_this._captureFrameTime) {
  89210. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89211. _this._frameTime.beginMonitoring();
  89212. }
  89213. if (_this._captureInterFrameTime) {
  89214. _this._interFrameTime.endMonitoring();
  89215. }
  89216. if (_this._captureParticlesRenderTime) {
  89217. _this._particlesRenderTime.fetchNewFrame();
  89218. }
  89219. if (_this._captureSpritesRenderTime) {
  89220. _this._spritesRenderTime.fetchNewFrame();
  89221. }
  89222. if (_this._captureAnimationsTime) {
  89223. _this._animationsTime.beginMonitoring();
  89224. }
  89225. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89226. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89227. });
  89228. // After render
  89229. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89230. if (_this._captureFrameTime) {
  89231. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89232. _this._frameTime.endMonitoring();
  89233. }
  89234. if (_this._captureRenderTime) {
  89235. _this._renderTime.endMonitoring(false);
  89236. }
  89237. if (_this._captureInterFrameTime) {
  89238. _this._interFrameTime.beginMonitoring();
  89239. }
  89240. });
  89241. }
  89242. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89243. // Properties
  89244. /**
  89245. * Gets the perf counter used for active meshes evaluation time
  89246. */
  89247. get: function () {
  89248. return this._activeMeshesEvaluationTime;
  89249. },
  89250. enumerable: true,
  89251. configurable: true
  89252. });
  89253. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89254. /**
  89255. * Gets the active meshes evaluation time capture status
  89256. */
  89257. get: function () {
  89258. return this._captureActiveMeshesEvaluationTime;
  89259. },
  89260. /**
  89261. * Enable or disable the active meshes evaluation time capture
  89262. */
  89263. set: function (value) {
  89264. var _this = this;
  89265. if (value === this._captureActiveMeshesEvaluationTime) {
  89266. return;
  89267. }
  89268. this._captureActiveMeshesEvaluationTime = value;
  89269. if (value) {
  89270. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89271. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89272. _this._activeMeshesEvaluationTime.beginMonitoring();
  89273. });
  89274. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89275. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89276. _this._activeMeshesEvaluationTime.endMonitoring();
  89277. });
  89278. }
  89279. else {
  89280. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89281. this._onBeforeActiveMeshesEvaluationObserver = null;
  89282. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89283. this._onAfterActiveMeshesEvaluationObserver = null;
  89284. }
  89285. },
  89286. enumerable: true,
  89287. configurable: true
  89288. });
  89289. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89290. /**
  89291. * Gets the perf counter used for render targets render time
  89292. */
  89293. get: function () {
  89294. return this._renderTargetsRenderTime;
  89295. },
  89296. enumerable: true,
  89297. configurable: true
  89298. });
  89299. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89300. /**
  89301. * Gets the render targets render time capture status
  89302. */
  89303. get: function () {
  89304. return this._captureRenderTargetsRenderTime;
  89305. },
  89306. /**
  89307. * Enable or disable the render targets render time capture
  89308. */
  89309. set: function (value) {
  89310. var _this = this;
  89311. if (value === this._captureRenderTargetsRenderTime) {
  89312. return;
  89313. }
  89314. this._captureRenderTargetsRenderTime = value;
  89315. if (value) {
  89316. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89317. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89318. _this._renderTargetsRenderTime.beginMonitoring();
  89319. });
  89320. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89321. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89322. _this._renderTargetsRenderTime.endMonitoring(false);
  89323. });
  89324. }
  89325. else {
  89326. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89327. this._onBeforeRenderTargetsRenderObserver = null;
  89328. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89329. this._onAfterRenderTargetsRenderObserver = null;
  89330. }
  89331. },
  89332. enumerable: true,
  89333. configurable: true
  89334. });
  89335. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89336. /**
  89337. * Gets the perf counter used for particles render time
  89338. */
  89339. get: function () {
  89340. return this._particlesRenderTime;
  89341. },
  89342. enumerable: true,
  89343. configurable: true
  89344. });
  89345. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89346. /**
  89347. * Gets the particles render time capture status
  89348. */
  89349. get: function () {
  89350. return this._captureParticlesRenderTime;
  89351. },
  89352. /**
  89353. * Enable or disable the particles render time capture
  89354. */
  89355. set: function (value) {
  89356. var _this = this;
  89357. if (value === this._captureParticlesRenderTime) {
  89358. return;
  89359. }
  89360. this._captureParticlesRenderTime = value;
  89361. if (value) {
  89362. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89363. BABYLON.Tools.StartPerformanceCounter("Particles");
  89364. _this._particlesRenderTime.beginMonitoring();
  89365. });
  89366. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89367. BABYLON.Tools.EndPerformanceCounter("Particles");
  89368. _this._particlesRenderTime.endMonitoring(false);
  89369. });
  89370. }
  89371. else {
  89372. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89373. this._onBeforeParticlesRenderingObserver = null;
  89374. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89375. this._onAfterParticlesRenderingObserver = null;
  89376. }
  89377. },
  89378. enumerable: true,
  89379. configurable: true
  89380. });
  89381. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89382. /**
  89383. * Gets the perf counter used for sprites render time
  89384. */
  89385. get: function () {
  89386. return this._spritesRenderTime;
  89387. },
  89388. enumerable: true,
  89389. configurable: true
  89390. });
  89391. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89392. /**
  89393. * Gets the sprites render time capture status
  89394. */
  89395. get: function () {
  89396. return this._captureSpritesRenderTime;
  89397. },
  89398. /**
  89399. * Enable or disable the sprites render time capture
  89400. */
  89401. set: function (value) {
  89402. var _this = this;
  89403. if (value === this._captureSpritesRenderTime) {
  89404. return;
  89405. }
  89406. this._captureSpritesRenderTime = value;
  89407. if (value) {
  89408. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89409. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89410. _this._spritesRenderTime.beginMonitoring();
  89411. });
  89412. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89413. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89414. _this._spritesRenderTime.endMonitoring(false);
  89415. });
  89416. }
  89417. else {
  89418. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89419. this._onBeforeSpritesRenderingObserver = null;
  89420. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89421. this._onAfterSpritesRenderingObserver = null;
  89422. }
  89423. },
  89424. enumerable: true,
  89425. configurable: true
  89426. });
  89427. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89428. /**
  89429. * Gets the perf counter used for physics time
  89430. */
  89431. get: function () {
  89432. return this._physicsTime;
  89433. },
  89434. enumerable: true,
  89435. configurable: true
  89436. });
  89437. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89438. /**
  89439. * Gets the physics time capture status
  89440. */
  89441. get: function () {
  89442. return this._capturePhysicsTime;
  89443. },
  89444. /**
  89445. * Enable or disable the physics time capture
  89446. */
  89447. set: function (value) {
  89448. var _this = this;
  89449. if (value === this._capturePhysicsTime) {
  89450. return;
  89451. }
  89452. this._capturePhysicsTime = value;
  89453. if (value) {
  89454. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89455. BABYLON.Tools.StartPerformanceCounter("Physics");
  89456. _this._physicsTime.beginMonitoring();
  89457. });
  89458. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89459. BABYLON.Tools.EndPerformanceCounter("Physics");
  89460. _this._physicsTime.endMonitoring();
  89461. });
  89462. }
  89463. else {
  89464. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89465. this._onBeforePhysicsObserver = null;
  89466. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89467. this._onAfterPhysicsObserver = null;
  89468. }
  89469. },
  89470. enumerable: true,
  89471. configurable: true
  89472. });
  89473. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89474. /**
  89475. * Gets the perf counter used for animations time
  89476. */
  89477. get: function () {
  89478. return this._animationsTime;
  89479. },
  89480. enumerable: true,
  89481. configurable: true
  89482. });
  89483. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89484. /**
  89485. * Gets the animations time capture status
  89486. */
  89487. get: function () {
  89488. return this._captureAnimationsTime;
  89489. },
  89490. /**
  89491. * Enable or disable the animations time capture
  89492. */
  89493. set: function (value) {
  89494. var _this = this;
  89495. if (value === this._captureAnimationsTime) {
  89496. return;
  89497. }
  89498. this._captureAnimationsTime = value;
  89499. if (value) {
  89500. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89501. _this._animationsTime.endMonitoring();
  89502. });
  89503. }
  89504. else {
  89505. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89506. this._onAfterAnimationsObserver = null;
  89507. }
  89508. },
  89509. enumerable: true,
  89510. configurable: true
  89511. });
  89512. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89513. /**
  89514. * Gets the perf counter used for frame time capture
  89515. */
  89516. get: function () {
  89517. return this._frameTime;
  89518. },
  89519. enumerable: true,
  89520. configurable: true
  89521. });
  89522. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89523. /**
  89524. * Gets the frame time capture status
  89525. */
  89526. get: function () {
  89527. return this._captureFrameTime;
  89528. },
  89529. /**
  89530. * Enable or disable the frame time capture
  89531. */
  89532. set: function (value) {
  89533. this._captureFrameTime = value;
  89534. },
  89535. enumerable: true,
  89536. configurable: true
  89537. });
  89538. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89539. /**
  89540. * Gets the perf counter used for inter-frames time capture
  89541. */
  89542. get: function () {
  89543. return this._interFrameTime;
  89544. },
  89545. enumerable: true,
  89546. configurable: true
  89547. });
  89548. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89549. /**
  89550. * Gets the inter-frames time capture status
  89551. */
  89552. get: function () {
  89553. return this._captureInterFrameTime;
  89554. },
  89555. /**
  89556. * Enable or disable the inter-frames time capture
  89557. */
  89558. set: function (value) {
  89559. this._captureInterFrameTime = value;
  89560. },
  89561. enumerable: true,
  89562. configurable: true
  89563. });
  89564. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89565. /**
  89566. * Gets the perf counter used for render time capture
  89567. */
  89568. get: function () {
  89569. return this._renderTime;
  89570. },
  89571. enumerable: true,
  89572. configurable: true
  89573. });
  89574. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89575. /**
  89576. * Gets the render time capture status
  89577. */
  89578. get: function () {
  89579. return this._captureRenderTime;
  89580. },
  89581. /**
  89582. * Enable or disable the render time capture
  89583. */
  89584. set: function (value) {
  89585. var _this = this;
  89586. if (value === this._captureRenderTime) {
  89587. return;
  89588. }
  89589. this._captureRenderTime = value;
  89590. if (value) {
  89591. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89592. _this._renderTime.beginMonitoring();
  89593. BABYLON.Tools.StartPerformanceCounter("Main render");
  89594. });
  89595. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89596. _this._renderTime.endMonitoring(false);
  89597. BABYLON.Tools.EndPerformanceCounter("Main render");
  89598. });
  89599. }
  89600. else {
  89601. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89602. this._onBeforeDrawPhaseObserver = null;
  89603. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89604. this._onAfterDrawPhaseObserver = null;
  89605. }
  89606. },
  89607. enumerable: true,
  89608. configurable: true
  89609. });
  89610. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89611. /**
  89612. * Gets the perf counter used for draw calls
  89613. */
  89614. get: function () {
  89615. return this.scene.getEngine()._drawCalls;
  89616. },
  89617. enumerable: true,
  89618. configurable: true
  89619. });
  89620. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89621. /**
  89622. * Gets the perf counter used for texture collisions
  89623. */
  89624. get: function () {
  89625. return this.scene.getEngine()._textureCollisions;
  89626. },
  89627. enumerable: true,
  89628. configurable: true
  89629. });
  89630. SceneInstrumentation.prototype.dispose = function () {
  89631. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89632. this._onAfterRenderObserver = null;
  89633. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89634. this._onBeforeActiveMeshesEvaluationObserver = null;
  89635. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89636. this._onAfterActiveMeshesEvaluationObserver = null;
  89637. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89638. this._onBeforeRenderTargetsRenderObserver = null;
  89639. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89640. this._onAfterRenderTargetsRenderObserver = null;
  89641. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89642. this._onBeforeAnimationsObserver = null;
  89643. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89644. this._onBeforeParticlesRenderingObserver = null;
  89645. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89646. this._onAfterParticlesRenderingObserver = null;
  89647. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89648. this._onBeforeSpritesRenderingObserver = null;
  89649. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89650. this._onAfterSpritesRenderingObserver = null;
  89651. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89652. this._onBeforeDrawPhaseObserver = null;
  89653. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89654. this._onAfterDrawPhaseObserver = null;
  89655. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89656. this._onBeforePhysicsObserver = null;
  89657. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89658. this._onAfterPhysicsObserver = null;
  89659. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89660. this._onAfterAnimationsObserver = null;
  89661. this.scene = null;
  89662. };
  89663. return SceneInstrumentation;
  89664. }());
  89665. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89666. })(BABYLON || (BABYLON = {}));
  89667. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89668. var BABYLON;
  89669. (function (BABYLON) {
  89670. var _TimeToken = /** @class */ (function () {
  89671. function _TimeToken() {
  89672. this._timeElapsedQueryEnded = false;
  89673. }
  89674. return _TimeToken;
  89675. }());
  89676. BABYLON._TimeToken = _TimeToken;
  89677. })(BABYLON || (BABYLON = {}));
  89678. //# sourceMappingURL=babylon.timeToken.js.map
  89679. var BABYLON;
  89680. (function (BABYLON) {
  89681. /**
  89682. * Background material defines definition.
  89683. * @ignore Mainly internal Use
  89684. */
  89685. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89686. __extends(BackgroundMaterialDefines, _super);
  89687. /**
  89688. * Constructor of the defines.
  89689. */
  89690. function BackgroundMaterialDefines() {
  89691. var _this = _super.call(this) || this;
  89692. /**
  89693. * True if the diffuse texture is in use.
  89694. */
  89695. _this.DIFFUSE = false;
  89696. /**
  89697. * The direct UV channel to use.
  89698. */
  89699. _this.DIFFUSEDIRECTUV = 0;
  89700. /**
  89701. * True if the diffuse texture is in gamma space.
  89702. */
  89703. _this.GAMMADIFFUSE = false;
  89704. /**
  89705. * True if the diffuse texture has opacity in the alpha channel.
  89706. */
  89707. _this.DIFFUSEHASALPHA = false;
  89708. /**
  89709. * True if you want the material to fade to transparent at grazing angle.
  89710. */
  89711. _this.OPACITYFRESNEL = false;
  89712. /**
  89713. * True if an extra blur needs to be added in the reflection.
  89714. */
  89715. _this.REFLECTIONBLUR = false;
  89716. /**
  89717. * True if you want the material to fade to reflection at grazing angle.
  89718. */
  89719. _this.REFLECTIONFRESNEL = false;
  89720. /**
  89721. * True if you want the material to falloff as far as you move away from the scene center.
  89722. */
  89723. _this.REFLECTIONFALLOFF = false;
  89724. /**
  89725. * False if the current Webgl implementation does not support the texture lod extension.
  89726. */
  89727. _this.TEXTURELODSUPPORT = false;
  89728. /**
  89729. * True to ensure the data are premultiplied.
  89730. */
  89731. _this.PREMULTIPLYALPHA = false;
  89732. /**
  89733. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89734. */
  89735. _this.USERGBCOLOR = false;
  89736. /**
  89737. * True to add noise in order to reduce the banding effect.
  89738. */
  89739. _this.NOISE = false;
  89740. /**
  89741. * is the reflection texture in BGR color scheme?
  89742. * Mainly used to solve a bug in ios10 video tag
  89743. */
  89744. _this.REFLECTIONBGR = false;
  89745. _this.IMAGEPROCESSING = false;
  89746. _this.VIGNETTE = false;
  89747. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89748. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89749. _this.TONEMAPPING = false;
  89750. _this.CONTRAST = false;
  89751. _this.COLORCURVES = false;
  89752. _this.COLORGRADING = false;
  89753. _this.COLORGRADING3D = false;
  89754. _this.SAMPLER3DGREENDEPTH = false;
  89755. _this.SAMPLER3DBGRMAP = false;
  89756. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89757. _this.EXPOSURE = false;
  89758. _this.GRAIN = false;
  89759. // Reflection.
  89760. _this.REFLECTION = false;
  89761. _this.REFLECTIONMAP_3D = false;
  89762. _this.REFLECTIONMAP_SPHERICAL = false;
  89763. _this.REFLECTIONMAP_PLANAR = false;
  89764. _this.REFLECTIONMAP_CUBIC = false;
  89765. _this.REFLECTIONMAP_PROJECTION = false;
  89766. _this.REFLECTIONMAP_SKYBOX = false;
  89767. _this.REFLECTIONMAP_EXPLICIT = false;
  89768. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89769. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89770. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89771. _this.INVERTCUBICMAP = false;
  89772. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89773. _this.LODINREFLECTIONALPHA = false;
  89774. _this.GAMMAREFLECTION = false;
  89775. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89776. // Default BJS.
  89777. _this.MAINUV1 = false;
  89778. _this.MAINUV2 = false;
  89779. _this.UV1 = false;
  89780. _this.UV2 = false;
  89781. _this.CLIPPLANE = false;
  89782. _this.POINTSIZE = false;
  89783. _this.FOG = false;
  89784. _this.NORMAL = false;
  89785. _this.NUM_BONE_INFLUENCERS = 0;
  89786. _this.BonesPerMesh = 0;
  89787. _this.INSTANCES = false;
  89788. _this.SHADOWFLOAT = false;
  89789. _this.rebuild();
  89790. return _this;
  89791. }
  89792. return BackgroundMaterialDefines;
  89793. }(BABYLON.MaterialDefines));
  89794. /**
  89795. * Background material used to create an efficient environement around your scene.
  89796. */
  89797. var BackgroundMaterial = /** @class */ (function (_super) {
  89798. __extends(BackgroundMaterial, _super);
  89799. /**
  89800. * Instantiates a Background Material in the given scene
  89801. * @param name The friendly name of the material
  89802. * @param scene The scene to add the material to
  89803. */
  89804. function BackgroundMaterial(name, scene) {
  89805. var _this = _super.call(this, name, scene) || this;
  89806. /**
  89807. * Key light Color (multiply against the R channel of the environement texture)
  89808. */
  89809. _this.primaryColor = BABYLON.Color3.White();
  89810. /**
  89811. * Key light Level (allowing HDR output of the background)
  89812. */
  89813. _this.primaryLevel = 1;
  89814. /**
  89815. * Secondary light Color (multiply against the G channel of the environement texture)
  89816. */
  89817. _this.secondaryColor = BABYLON.Color3.Gray();
  89818. /**
  89819. * Secondary light Level (allowing HDR output of the background)
  89820. */
  89821. _this.secondaryLevel = 1;
  89822. /**
  89823. * Tertiary light Color (multiply against the B channel of the environement texture)
  89824. */
  89825. _this.tertiaryColor = BABYLON.Color3.Black();
  89826. /**
  89827. * Tertiary light Level (allowing HDR output of the background)
  89828. */
  89829. _this.tertiaryLevel = 1;
  89830. /**
  89831. * Reflection Texture used in the material.
  89832. * Should be author in a specific way for the best result (refer to the documentation).
  89833. */
  89834. _this.reflectionTexture = null;
  89835. /**
  89836. * Reflection Texture level of blur.
  89837. *
  89838. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89839. * texture twice.
  89840. */
  89841. _this.reflectionBlur = 0;
  89842. /**
  89843. * Diffuse Texture used in the material.
  89844. * Should be author in a specific way for the best result (refer to the documentation).
  89845. */
  89846. _this.diffuseTexture = null;
  89847. _this._shadowLights = null;
  89848. /**
  89849. * Specify the list of lights casting shadow on the material.
  89850. * All scene shadow lights will be included if null.
  89851. */
  89852. _this.shadowLights = null;
  89853. /**
  89854. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89855. * soft lighting on the background.
  89856. */
  89857. _this.shadowBlurScale = 1;
  89858. /**
  89859. * Helps adjusting the shadow to a softer level if required.
  89860. * 0 means black shadows and 1 means no shadows.
  89861. */
  89862. _this.shadowLevel = 0;
  89863. /**
  89864. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89865. * It is usually zero but might be interesting to modify according to your setup.
  89866. */
  89867. _this.sceneCenter = BABYLON.Vector3.Zero();
  89868. /**
  89869. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89870. * This helps ensuring a nice transition when the camera goes under the ground.
  89871. */
  89872. _this.opacityFresnel = true;
  89873. /**
  89874. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89875. * This helps adding a mirror texture on the ground.
  89876. */
  89877. _this.reflectionFresnel = false;
  89878. /**
  89879. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89880. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89881. */
  89882. _this.reflectionFalloffDistance = 0.0;
  89883. /**
  89884. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89885. */
  89886. _this.reflectionAmount = 1.0;
  89887. /**
  89888. * This specifies the weight of the reflection at grazing angle.
  89889. */
  89890. _this.reflectionReflectance0 = 0.05;
  89891. /**
  89892. * This specifies the weight of the reflection at a perpendicular point of view.
  89893. */
  89894. _this.reflectionReflectance90 = 0.5;
  89895. /**
  89896. * Helps to directly use the maps channels instead of their level.
  89897. */
  89898. _this.useRGBColor = true;
  89899. /**
  89900. * This helps reducing the banding effect that could occur on the background.
  89901. */
  89902. _this.enableNoise = false;
  89903. _this._fovMultiplier = 1.0;
  89904. /**
  89905. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89906. * @type {boolean}
  89907. */
  89908. _this.useEquirectangularFOV = false;
  89909. _this._maxSimultaneousLights = 4;
  89910. /**
  89911. * Number of Simultaneous lights allowed on the material.
  89912. */
  89913. _this.maxSimultaneousLights = 4;
  89914. /**
  89915. * Keep track of the image processing observer to allow dispose and replace.
  89916. */
  89917. _this._imageProcessingObserver = null;
  89918. /**
  89919. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89920. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89921. */
  89922. _this.switchToBGR = false;
  89923. // Temp values kept as cache in the material.
  89924. _this._renderTargets = new BABYLON.SmartArray(16);
  89925. _this._reflectionControls = BABYLON.Vector4.Zero();
  89926. // Setup the default processing configuration to the scene.
  89927. _this._attachImageProcessingConfiguration(null);
  89928. _this.getRenderTargetTextures = function () {
  89929. _this._renderTargets.reset();
  89930. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89931. _this._renderTargets.push(_this._diffuseTexture);
  89932. }
  89933. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89934. _this._renderTargets.push(_this._reflectionTexture);
  89935. }
  89936. return _this._renderTargets;
  89937. };
  89938. return _this;
  89939. }
  89940. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89941. /**
  89942. * Sets the reflection reflectance fresnel values according to the default standard
  89943. * empirically know to work well :-)
  89944. */
  89945. set: function (value) {
  89946. var reflectionWeight = value;
  89947. if (reflectionWeight < 0.5) {
  89948. reflectionWeight = reflectionWeight * 2.0;
  89949. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89950. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89951. }
  89952. else {
  89953. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89954. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89955. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89956. }
  89957. },
  89958. enumerable: true,
  89959. configurable: true
  89960. });
  89961. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89962. /**
  89963. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89964. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89965. * Recommended to be keep at 1.0 except for special cases.
  89966. */
  89967. get: function () {
  89968. return this._fovMultiplier;
  89969. },
  89970. set: function (value) {
  89971. if (isNaN(value)) {
  89972. value = 1.0;
  89973. }
  89974. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89975. },
  89976. enumerable: true,
  89977. configurable: true
  89978. });
  89979. /**
  89980. * Attaches a new image processing configuration to the PBR Material.
  89981. * @param configuration (if null the scene configuration will be use)
  89982. */
  89983. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89984. var _this = this;
  89985. if (configuration === this._imageProcessingConfiguration) {
  89986. return;
  89987. }
  89988. // Detaches observer.
  89989. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89990. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89991. }
  89992. // Pick the scene configuration if needed.
  89993. if (!configuration) {
  89994. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89995. }
  89996. else {
  89997. this._imageProcessingConfiguration = configuration;
  89998. }
  89999. // Attaches observer.
  90000. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90001. _this._markAllSubMeshesAsImageProcessingDirty();
  90002. });
  90003. };
  90004. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90005. /**
  90006. * Gets the image processing configuration used either in this material.
  90007. */
  90008. get: function () {
  90009. return this._imageProcessingConfiguration;
  90010. },
  90011. /**
  90012. * Sets the Default image processing configuration used either in the this material.
  90013. *
  90014. * If sets to null, the scene one is in use.
  90015. */
  90016. set: function (value) {
  90017. this._attachImageProcessingConfiguration(value);
  90018. // Ensure the effect will be rebuilt.
  90019. this._markAllSubMeshesAsTexturesDirty();
  90020. },
  90021. enumerable: true,
  90022. configurable: true
  90023. });
  90024. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90025. /**
  90026. * Gets wether the color curves effect is enabled.
  90027. */
  90028. get: function () {
  90029. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90030. },
  90031. /**
  90032. * Sets wether the color curves effect is enabled.
  90033. */
  90034. set: function (value) {
  90035. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90036. },
  90037. enumerable: true,
  90038. configurable: true
  90039. });
  90040. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90041. /**
  90042. * Gets wether the color grading effect is enabled.
  90043. */
  90044. get: function () {
  90045. return this.imageProcessingConfiguration.colorGradingEnabled;
  90046. },
  90047. /**
  90048. * Gets wether the color grading effect is enabled.
  90049. */
  90050. set: function (value) {
  90051. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90052. },
  90053. enumerable: true,
  90054. configurable: true
  90055. });
  90056. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90057. /**
  90058. * Gets wether tonemapping is enabled or not.
  90059. */
  90060. get: function () {
  90061. return this._imageProcessingConfiguration.toneMappingEnabled;
  90062. },
  90063. /**
  90064. * Sets wether tonemapping is enabled or not
  90065. */
  90066. set: function (value) {
  90067. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90068. },
  90069. enumerable: true,
  90070. configurable: true
  90071. });
  90072. ;
  90073. ;
  90074. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90075. /**
  90076. * The camera exposure used on this material.
  90077. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90078. * This corresponds to a photographic exposure.
  90079. */
  90080. get: function () {
  90081. return this._imageProcessingConfiguration.exposure;
  90082. },
  90083. /**
  90084. * The camera exposure used on this material.
  90085. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90086. * This corresponds to a photographic exposure.
  90087. */
  90088. set: function (value) {
  90089. this._imageProcessingConfiguration.exposure = value;
  90090. },
  90091. enumerable: true,
  90092. configurable: true
  90093. });
  90094. ;
  90095. ;
  90096. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90097. /**
  90098. * Gets The camera contrast used on this material.
  90099. */
  90100. get: function () {
  90101. return this._imageProcessingConfiguration.contrast;
  90102. },
  90103. /**
  90104. * Sets The camera contrast used on this material.
  90105. */
  90106. set: function (value) {
  90107. this._imageProcessingConfiguration.contrast = value;
  90108. },
  90109. enumerable: true,
  90110. configurable: true
  90111. });
  90112. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90113. /**
  90114. * Gets the Color Grading 2D Lookup Texture.
  90115. */
  90116. get: function () {
  90117. return this._imageProcessingConfiguration.colorGradingTexture;
  90118. },
  90119. /**
  90120. * Sets the Color Grading 2D Lookup Texture.
  90121. */
  90122. set: function (value) {
  90123. this.imageProcessingConfiguration.colorGradingTexture = value;
  90124. },
  90125. enumerable: true,
  90126. configurable: true
  90127. });
  90128. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90129. /**
  90130. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90131. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90132. * 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;
  90133. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90134. */
  90135. get: function () {
  90136. return this.imageProcessingConfiguration.colorCurves;
  90137. },
  90138. /**
  90139. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90140. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90141. * 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;
  90142. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90143. */
  90144. set: function (value) {
  90145. this.imageProcessingConfiguration.colorCurves = value;
  90146. },
  90147. enumerable: true,
  90148. configurable: true
  90149. });
  90150. /**
  90151. * The entire material has been created in order to prevent overdraw.
  90152. * @returns false
  90153. */
  90154. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90155. return true;
  90156. };
  90157. /**
  90158. * The entire material has been created in order to prevent overdraw.
  90159. * @returns true if blending is enable
  90160. */
  90161. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90162. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90163. };
  90164. /**
  90165. * Checks wether the material is ready to be rendered for a given mesh.
  90166. * @param mesh The mesh to render
  90167. * @param subMesh The submesh to check against
  90168. * @param useInstances Specify wether or not the material is used with instances
  90169. * @returns true if all the dependencies are ready (Textures, Effects...)
  90170. */
  90171. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90172. var _this = this;
  90173. if (useInstances === void 0) { useInstances = false; }
  90174. if (subMesh.effect && this.isFrozen) {
  90175. if (this._wasPreviouslyReady) {
  90176. return true;
  90177. }
  90178. }
  90179. if (!subMesh._materialDefines) {
  90180. subMesh._materialDefines = new BackgroundMaterialDefines();
  90181. }
  90182. var scene = this.getScene();
  90183. var defines = subMesh._materialDefines;
  90184. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90185. if (defines._renderId === scene.getRenderId()) {
  90186. return true;
  90187. }
  90188. }
  90189. var engine = scene.getEngine();
  90190. // Lights
  90191. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90192. defines._needNormals = true;
  90193. // Textures
  90194. if (defines._areTexturesDirty) {
  90195. defines._needUVs = false;
  90196. if (scene.texturesEnabled) {
  90197. if (scene.getEngine().getCaps().textureLOD) {
  90198. defines.TEXTURELODSUPPORT = true;
  90199. }
  90200. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90201. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90202. return false;
  90203. }
  90204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90205. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90206. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90207. defines.OPACITYFRESNEL = this._opacityFresnel;
  90208. }
  90209. else {
  90210. defines.DIFFUSE = false;
  90211. defines.DIFFUSEHASALPHA = false;
  90212. defines.GAMMADIFFUSE = false;
  90213. defines.OPACITYFRESNEL = false;
  90214. }
  90215. var reflectionTexture = this._reflectionTexture;
  90216. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90217. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90218. return false;
  90219. }
  90220. defines.REFLECTION = true;
  90221. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90222. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90223. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90224. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90225. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90226. defines.REFLECTIONBGR = this.switchToBGR;
  90227. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90228. defines.INVERTCUBICMAP = true;
  90229. }
  90230. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90231. switch (reflectionTexture.coordinatesMode) {
  90232. case BABYLON.Texture.CUBIC_MODE:
  90233. case BABYLON.Texture.INVCUBIC_MODE:
  90234. defines.REFLECTIONMAP_CUBIC = true;
  90235. break;
  90236. case BABYLON.Texture.EXPLICIT_MODE:
  90237. defines.REFLECTIONMAP_EXPLICIT = true;
  90238. break;
  90239. case BABYLON.Texture.PLANAR_MODE:
  90240. defines.REFLECTIONMAP_PLANAR = true;
  90241. break;
  90242. case BABYLON.Texture.PROJECTION_MODE:
  90243. defines.REFLECTIONMAP_PROJECTION = true;
  90244. break;
  90245. case BABYLON.Texture.SKYBOX_MODE:
  90246. defines.REFLECTIONMAP_SKYBOX = true;
  90247. break;
  90248. case BABYLON.Texture.SPHERICAL_MODE:
  90249. defines.REFLECTIONMAP_SPHERICAL = true;
  90250. break;
  90251. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90252. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90253. break;
  90254. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90255. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90256. break;
  90257. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90258. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90259. break;
  90260. }
  90261. if (this.reflectionFresnel) {
  90262. defines.REFLECTIONFRESNEL = true;
  90263. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90264. this._reflectionControls.x = this.reflectionAmount;
  90265. this._reflectionControls.y = this.reflectionReflectance0;
  90266. this._reflectionControls.z = this.reflectionReflectance90;
  90267. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90268. }
  90269. else {
  90270. defines.REFLECTIONFRESNEL = false;
  90271. defines.REFLECTIONFALLOFF = false;
  90272. }
  90273. }
  90274. else {
  90275. defines.REFLECTION = false;
  90276. defines.REFLECTIONFALLOFF = false;
  90277. defines.REFLECTIONBLUR = false;
  90278. defines.REFLECTIONMAP_3D = false;
  90279. defines.REFLECTIONMAP_SPHERICAL = false;
  90280. defines.REFLECTIONMAP_PLANAR = false;
  90281. defines.REFLECTIONMAP_CUBIC = false;
  90282. defines.REFLECTIONMAP_PROJECTION = false;
  90283. defines.REFLECTIONMAP_SKYBOX = false;
  90284. defines.REFLECTIONMAP_EXPLICIT = false;
  90285. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90286. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90287. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90288. defines.INVERTCUBICMAP = false;
  90289. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90290. defines.LODINREFLECTIONALPHA = false;
  90291. defines.GAMMAREFLECTION = false;
  90292. }
  90293. }
  90294. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90295. defines.USERGBCOLOR = this._useRGBColor;
  90296. defines.NOISE = this._enableNoise;
  90297. }
  90298. if (defines._areImageProcessingDirty) {
  90299. if (!this._imageProcessingConfiguration.isReady()) {
  90300. return false;
  90301. }
  90302. this._imageProcessingConfiguration.prepareDefines(defines);
  90303. }
  90304. // Misc.
  90305. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90306. // Values that need to be evaluated on every frame
  90307. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90308. // Attribs
  90309. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90310. if (mesh) {
  90311. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90312. mesh.createNormals(true);
  90313. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90314. }
  90315. }
  90316. }
  90317. // Get correct effect
  90318. if (defines.isDirty) {
  90319. defines.markAsProcessed();
  90320. scene.resetCachedMaterial();
  90321. // Fallbacks
  90322. var fallbacks = new BABYLON.EffectFallbacks();
  90323. if (defines.FOG) {
  90324. fallbacks.addFallback(0, "FOG");
  90325. }
  90326. if (defines.POINTSIZE) {
  90327. fallbacks.addFallback(1, "POINTSIZE");
  90328. }
  90329. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90330. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90331. fallbacks.addCPUSkinningFallback(0, mesh);
  90332. }
  90333. //Attributes
  90334. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90335. if (defines.NORMAL) {
  90336. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90337. }
  90338. if (defines.UV1) {
  90339. attribs.push(BABYLON.VertexBuffer.UVKind);
  90340. }
  90341. if (defines.UV2) {
  90342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90343. }
  90344. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90345. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90346. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90347. "vFogInfos", "vFogColor", "pointSize",
  90348. "vClipPlane", "mBones",
  90349. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90350. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90351. "shadowLevel", "alpha",
  90352. "vBackgroundCenter", "vReflectionControl",
  90353. "vDiffuseInfos", "diffuseMatrix",
  90354. ];
  90355. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90356. var uniformBuffers = ["Material", "Scene"];
  90357. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90358. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90359. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90360. uniformsNames: uniforms,
  90361. uniformBuffersNames: uniformBuffers,
  90362. samplers: samplers,
  90363. defines: defines,
  90364. maxSimultaneousLights: this._maxSimultaneousLights
  90365. });
  90366. var onCompiled = function (effect) {
  90367. if (_this.onCompiled) {
  90368. _this.onCompiled(effect);
  90369. }
  90370. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90371. };
  90372. var join = defines.toString();
  90373. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90374. attributes: attribs,
  90375. uniformsNames: uniforms,
  90376. uniformBuffersNames: uniformBuffers,
  90377. samplers: samplers,
  90378. defines: join,
  90379. fallbacks: fallbacks,
  90380. onCompiled: onCompiled,
  90381. onError: this.onError,
  90382. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90383. }, engine), defines);
  90384. this.buildUniformLayout();
  90385. }
  90386. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90387. return false;
  90388. }
  90389. defines._renderId = scene.getRenderId();
  90390. this._wasPreviouslyReady = true;
  90391. return true;
  90392. };
  90393. /**
  90394. * Build the uniform buffer used in the material.
  90395. */
  90396. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90397. // Order is important !
  90398. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90399. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90400. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90401. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90402. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90403. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90404. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90405. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90406. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90407. this._uniformBuffer.addUniform("pointSize", 1);
  90408. this._uniformBuffer.addUniform("shadowLevel", 1);
  90409. this._uniformBuffer.addUniform("alpha", 1);
  90410. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90411. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90412. this._uniformBuffer.create();
  90413. };
  90414. /**
  90415. * Unbind the material.
  90416. */
  90417. BackgroundMaterial.prototype.unbind = function () {
  90418. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90419. this._uniformBuffer.setTexture("diffuseSampler", null);
  90420. }
  90421. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90422. this._uniformBuffer.setTexture("reflectionSampler", null);
  90423. }
  90424. _super.prototype.unbind.call(this);
  90425. };
  90426. /**
  90427. * Bind only the world matrix to the material.
  90428. * @param world The world matrix to bind.
  90429. */
  90430. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90431. this._activeEffect.setMatrix("world", world);
  90432. };
  90433. /**
  90434. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90435. * @param world The world matrix to bind.
  90436. * @param subMesh The submesh to bind for.
  90437. */
  90438. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90439. var scene = this.getScene();
  90440. var defines = subMesh._materialDefines;
  90441. if (!defines) {
  90442. return;
  90443. }
  90444. var effect = subMesh.effect;
  90445. if (!effect) {
  90446. return;
  90447. }
  90448. this._activeEffect = effect;
  90449. // Matrices
  90450. this.bindOnlyWorldMatrix(world);
  90451. // Bones
  90452. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90453. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90454. if (mustRebind) {
  90455. this._uniformBuffer.bindToEffect(effect, "Material");
  90456. this.bindViewProjection(effect);
  90457. var reflectionTexture = this._reflectionTexture;
  90458. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90459. // Texture uniforms
  90460. if (scene.texturesEnabled) {
  90461. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90462. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90463. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90464. }
  90465. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90466. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90467. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90468. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90469. }
  90470. }
  90471. if (this.shadowLevel > 0) {
  90472. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90473. }
  90474. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90475. // Point size
  90476. if (this.pointsCloud) {
  90477. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90478. }
  90479. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90480. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90481. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90482. }
  90483. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90484. // Textures
  90485. if (scene.texturesEnabled) {
  90486. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90487. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90488. }
  90489. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90490. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90491. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90492. }
  90493. else if (!defines.REFLECTIONBLUR) {
  90494. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90495. }
  90496. else {
  90497. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90498. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90499. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90500. }
  90501. if (defines.REFLECTIONFRESNEL) {
  90502. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90503. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90504. }
  90505. }
  90506. }
  90507. // Clip plane
  90508. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90509. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90510. }
  90511. if (mustRebind || !this.isFrozen) {
  90512. if (scene.lightsEnabled) {
  90513. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90514. }
  90515. // View
  90516. this.bindView(effect);
  90517. // Fog
  90518. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90519. // image processing
  90520. this._imageProcessingConfiguration.bind(this._activeEffect);
  90521. }
  90522. this._uniformBuffer.update();
  90523. this._afterBind(mesh);
  90524. };
  90525. /**
  90526. * Dispose the material.
  90527. * @param forceDisposeEffect Force disposal of the associated effect.
  90528. * @param forceDisposeTextures Force disposal of the associated textures.
  90529. */
  90530. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90531. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90532. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90533. if (forceDisposeTextures) {
  90534. if (this.diffuseTexture) {
  90535. this.diffuseTexture.dispose();
  90536. }
  90537. if (this.reflectionTexture) {
  90538. this.reflectionTexture.dispose();
  90539. }
  90540. }
  90541. this._renderTargets.dispose();
  90542. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90543. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90544. }
  90545. _super.prototype.dispose.call(this, forceDisposeEffect);
  90546. };
  90547. /**
  90548. * Clones the material.
  90549. * @param name The cloned name.
  90550. * @returns The cloned material.
  90551. */
  90552. BackgroundMaterial.prototype.clone = function (name) {
  90553. var _this = this;
  90554. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90555. };
  90556. /**
  90557. * Serializes the current material to its JSON representation.
  90558. * @returns The JSON representation.
  90559. */
  90560. BackgroundMaterial.prototype.serialize = function () {
  90561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90562. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90563. return serializationObject;
  90564. };
  90565. /**
  90566. * Gets the class name of the material
  90567. * @returns "BackgroundMaterial"
  90568. */
  90569. BackgroundMaterial.prototype.getClassName = function () {
  90570. return "BackgroundMaterial";
  90571. };
  90572. /**
  90573. * Parse a JSON input to create back a background material.
  90574. * @param source The JSON data to parse
  90575. * @param scene The scene to create the parsed material in
  90576. * @param rootUrl The root url of the assets the material depends upon
  90577. * @returns the instantiated BackgroundMaterial.
  90578. */
  90579. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90580. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90581. };
  90582. /**
  90583. * Standard reflectance value at parallel view angle.
  90584. */
  90585. BackgroundMaterial.StandardReflectance0 = 0.05;
  90586. /**
  90587. * Standard reflectance value at grazing angle.
  90588. */
  90589. BackgroundMaterial.StandardReflectance90 = 0.5;
  90590. __decorate([
  90591. BABYLON.serializeAsColor3()
  90592. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90593. __decorate([
  90594. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90595. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90596. __decorate([
  90597. BABYLON.serialize()
  90598. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90599. __decorate([
  90600. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90601. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90602. __decorate([
  90603. BABYLON.serializeAsColor3()
  90604. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90605. __decorate([
  90606. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90607. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90608. __decorate([
  90609. BABYLON.serialize()
  90610. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90611. __decorate([
  90612. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90613. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90614. __decorate([
  90615. BABYLON.serializeAsColor3()
  90616. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90617. __decorate([
  90618. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90619. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90620. __decorate([
  90621. BABYLON.serialize()
  90622. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90623. __decorate([
  90624. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90625. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90626. __decorate([
  90627. BABYLON.serializeAsTexture()
  90628. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90629. __decorate([
  90630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90631. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90632. __decorate([
  90633. BABYLON.serialize()
  90634. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90635. __decorate([
  90636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90637. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90638. __decorate([
  90639. BABYLON.serializeAsTexture()
  90640. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90641. __decorate([
  90642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90643. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90644. __decorate([
  90645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90646. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90647. __decorate([
  90648. BABYLON.serialize()
  90649. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90650. __decorate([
  90651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90652. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90653. __decorate([
  90654. BABYLON.serialize()
  90655. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90656. __decorate([
  90657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90658. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90659. __decorate([
  90660. BABYLON.serializeAsVector3()
  90661. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90662. __decorate([
  90663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90664. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90665. __decorate([
  90666. BABYLON.serialize()
  90667. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90668. __decorate([
  90669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90670. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90671. __decorate([
  90672. BABYLON.serialize()
  90673. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90674. __decorate([
  90675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90676. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90677. __decorate([
  90678. BABYLON.serialize()
  90679. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90680. __decorate([
  90681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90682. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90683. __decorate([
  90684. BABYLON.serialize()
  90685. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90686. __decorate([
  90687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90688. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90689. __decorate([
  90690. BABYLON.serialize()
  90691. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90692. __decorate([
  90693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90694. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90695. __decorate([
  90696. BABYLON.serialize()
  90697. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90698. __decorate([
  90699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90700. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90701. __decorate([
  90702. BABYLON.serialize()
  90703. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90704. __decorate([
  90705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90706. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90707. __decorate([
  90708. BABYLON.serialize()
  90709. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90710. __decorate([
  90711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90712. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90713. __decorate([
  90714. BABYLON.serialize()
  90715. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90716. __decorate([
  90717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90718. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90719. __decorate([
  90720. BABYLON.serializeAsImageProcessingConfiguration()
  90721. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90722. return BackgroundMaterial;
  90723. }(BABYLON.PushMaterial));
  90724. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90725. })(BABYLON || (BABYLON = {}));
  90726. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90727. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90728. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90729. s = arguments[i];
  90730. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90731. t[p] = s[p];
  90732. }
  90733. return t;
  90734. };
  90735. var BABYLON;
  90736. (function (BABYLON) {
  90737. /**
  90738. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90739. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90740. * It also helps with the default setup of your imageProcessing configuration.
  90741. */
  90742. var EnvironmentHelper = /** @class */ (function () {
  90743. /**
  90744. * constructor
  90745. * @param options
  90746. * @param scene The scene to add the material to
  90747. */
  90748. function EnvironmentHelper(options, scene) {
  90749. var _this = this;
  90750. this._errorHandler = function (message, exception) {
  90751. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90752. };
  90753. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90754. this._scene = scene;
  90755. this.onErrorObservable = new BABYLON.Observable();
  90756. this._setupBackground();
  90757. this._setupImageProcessing();
  90758. }
  90759. /**
  90760. * Creates the default options for the helper.
  90761. */
  90762. EnvironmentHelper._getDefaultOptions = function () {
  90763. return {
  90764. createGround: true,
  90765. groundSize: 15,
  90766. groundTexture: this._groundTextureCDNUrl,
  90767. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90768. groundOpacity: 0.9,
  90769. enableGroundShadow: true,
  90770. groundShadowLevel: 0.5,
  90771. enableGroundMirror: false,
  90772. groundMirrorSizeRatio: 0.3,
  90773. groundMirrorBlurKernel: 64,
  90774. groundMirrorAmount: 1,
  90775. groundMirrorFresnelWeight: 1,
  90776. groundMirrorFallOffDistance: 0,
  90777. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90778. groundYBias: 0.00001,
  90779. createSkybox: true,
  90780. skyboxSize: 20,
  90781. skyboxTexture: this._skyboxTextureCDNUrl,
  90782. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90783. backgroundYRotation: 0,
  90784. sizeAuto: true,
  90785. rootPosition: BABYLON.Vector3.Zero(),
  90786. setupImageProcessing: true,
  90787. environmentTexture: this._environmentTextureCDNUrl,
  90788. cameraExposure: 0.8,
  90789. cameraContrast: 1.2,
  90790. toneMappingEnabled: true,
  90791. };
  90792. };
  90793. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90794. /**
  90795. * Gets the root mesh created by the helper.
  90796. */
  90797. get: function () {
  90798. return this._rootMesh;
  90799. },
  90800. enumerable: true,
  90801. configurable: true
  90802. });
  90803. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90804. /**
  90805. * Gets the skybox created by the helper.
  90806. */
  90807. get: function () {
  90808. return this._skybox;
  90809. },
  90810. enumerable: true,
  90811. configurable: true
  90812. });
  90813. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90814. /**
  90815. * Gets the skybox texture created by the helper.
  90816. */
  90817. get: function () {
  90818. return this._skyboxTexture;
  90819. },
  90820. enumerable: true,
  90821. configurable: true
  90822. });
  90823. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90824. /**
  90825. * Gets the skybox material created by the helper.
  90826. */
  90827. get: function () {
  90828. return this._skyboxMaterial;
  90829. },
  90830. enumerable: true,
  90831. configurable: true
  90832. });
  90833. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90834. /**
  90835. * Gets the ground mesh created by the helper.
  90836. */
  90837. get: function () {
  90838. return this._ground;
  90839. },
  90840. enumerable: true,
  90841. configurable: true
  90842. });
  90843. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90844. /**
  90845. * Gets the ground texture created by the helper.
  90846. */
  90847. get: function () {
  90848. return this._groundTexture;
  90849. },
  90850. enumerable: true,
  90851. configurable: true
  90852. });
  90853. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90854. /**
  90855. * Gets the ground mirror created by the helper.
  90856. */
  90857. get: function () {
  90858. return this._groundMirror;
  90859. },
  90860. enumerable: true,
  90861. configurable: true
  90862. });
  90863. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90864. /**
  90865. * Gets the ground mirror render list to helps pushing the meshes
  90866. * you wish in the ground reflection.
  90867. */
  90868. get: function () {
  90869. if (this._groundMirror) {
  90870. return this._groundMirror.renderList;
  90871. }
  90872. return null;
  90873. },
  90874. enumerable: true,
  90875. configurable: true
  90876. });
  90877. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90878. /**
  90879. * Gets the ground material created by the helper.
  90880. */
  90881. get: function () {
  90882. return this._groundMaterial;
  90883. },
  90884. enumerable: true,
  90885. configurable: true
  90886. });
  90887. /**
  90888. * Updates the background according to the new options
  90889. * @param options
  90890. */
  90891. EnvironmentHelper.prototype.updateOptions = function (options) {
  90892. var newOptions = __assign({}, this._options, options);
  90893. if (this._ground && !newOptions.createGround) {
  90894. this._ground.dispose();
  90895. this._ground = null;
  90896. }
  90897. if (this._groundMaterial && !newOptions.createGround) {
  90898. this._groundMaterial.dispose();
  90899. this._groundMaterial = null;
  90900. }
  90901. if (this._groundTexture) {
  90902. if (this._options.groundTexture != newOptions.groundTexture) {
  90903. this._groundTexture.dispose();
  90904. this._groundTexture = null;
  90905. }
  90906. }
  90907. if (this._skybox && !newOptions.createSkybox) {
  90908. this._skybox.dispose();
  90909. this._skybox = null;
  90910. }
  90911. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90912. this._skyboxMaterial.dispose();
  90913. this._skyboxMaterial = null;
  90914. }
  90915. if (this._skyboxTexture) {
  90916. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90917. this._skyboxTexture.dispose();
  90918. this._skyboxTexture = null;
  90919. }
  90920. }
  90921. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90922. this._groundMirror.dispose();
  90923. this._groundMirror = null;
  90924. }
  90925. if (this._scene.environmentTexture) {
  90926. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90927. this._scene.environmentTexture.dispose();
  90928. }
  90929. }
  90930. this._options = newOptions;
  90931. this._setupBackground();
  90932. this._setupImageProcessing();
  90933. };
  90934. /**
  90935. * Sets the primary color of all the available elements.
  90936. * @param color
  90937. */
  90938. EnvironmentHelper.prototype.setMainColor = function (color) {
  90939. if (this.groundMaterial) {
  90940. this.groundMaterial.primaryColor = color;
  90941. }
  90942. if (this.skyboxMaterial) {
  90943. this.skyboxMaterial.primaryColor = color;
  90944. }
  90945. if (this.groundMirror) {
  90946. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90947. }
  90948. };
  90949. /**
  90950. * Setup the image processing according to the specified options.
  90951. */
  90952. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90953. if (this._options.setupImageProcessing) {
  90954. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90955. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90956. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90957. this._setupEnvironmentTexture();
  90958. }
  90959. };
  90960. /**
  90961. * Setup the environment texture according to the specified options.
  90962. */
  90963. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90964. if (this._scene.environmentTexture) {
  90965. return;
  90966. }
  90967. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90968. this._scene.environmentTexture = this._options.environmentTexture;
  90969. return;
  90970. }
  90971. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90972. this._scene.environmentTexture = environmentTexture;
  90973. };
  90974. /**
  90975. * Setup the background according to the specified options.
  90976. */
  90977. EnvironmentHelper.prototype._setupBackground = function () {
  90978. if (!this._rootMesh) {
  90979. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90980. }
  90981. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90982. var sceneSize = this._getSceneSize();
  90983. if (this._options.createGround) {
  90984. this._setupGround(sceneSize);
  90985. this._setupGroundMaterial();
  90986. this._setupGroundDiffuseTexture();
  90987. if (this._options.enableGroundMirror) {
  90988. this._setupGroundMirrorTexture(sceneSize);
  90989. }
  90990. this._setupMirrorInGroundMaterial();
  90991. }
  90992. if (this._options.createSkybox) {
  90993. this._setupSkybox(sceneSize);
  90994. this._setupSkyboxMaterial();
  90995. this._setupSkyboxReflectionTexture();
  90996. }
  90997. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90998. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90999. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91000. };
  91001. /**
  91002. * Get the scene sizes according to the setup.
  91003. */
  91004. EnvironmentHelper.prototype._getSceneSize = function () {
  91005. var _this = this;
  91006. var groundSize = this._options.groundSize;
  91007. var skyboxSize = this._options.skyboxSize;
  91008. var rootPosition = this._options.rootPosition;
  91009. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91010. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91011. }
  91012. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91013. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91014. });
  91015. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91016. if (this._options.sizeAuto) {
  91017. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91018. this._scene.activeCamera.upperRadiusLimit) {
  91019. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91020. skyboxSize = groundSize;
  91021. }
  91022. var sceneDiagonalLenght = sceneDiagonal.length();
  91023. if (sceneDiagonalLenght > groundSize) {
  91024. groundSize = sceneDiagonalLenght * 2;
  91025. skyboxSize = groundSize;
  91026. }
  91027. // 10 % bigger.
  91028. groundSize *= 1.1;
  91029. skyboxSize *= 1.5;
  91030. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91031. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91032. }
  91033. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91034. };
  91035. /**
  91036. * Setup the ground according to the specified options.
  91037. */
  91038. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91039. var _this = this;
  91040. if (!this._ground) {
  91041. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91042. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91043. this._ground.parent = this._rootMesh;
  91044. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91045. }
  91046. this._ground.receiveShadows = this._options.enableGroundShadow;
  91047. };
  91048. /**
  91049. * Setup the ground material according to the specified options.
  91050. */
  91051. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91052. if (!this._groundMaterial) {
  91053. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91054. }
  91055. this._groundMaterial.alpha = this._options.groundOpacity;
  91056. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91057. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91058. this._groundMaterial.primaryLevel = 1;
  91059. this._groundMaterial.primaryColor = this._options.groundColor;
  91060. this._groundMaterial.secondaryLevel = 0;
  91061. this._groundMaterial.tertiaryLevel = 0;
  91062. this._groundMaterial.useRGBColor = false;
  91063. this._groundMaterial.enableNoise = true;
  91064. if (this._ground) {
  91065. this._ground.material = this._groundMaterial;
  91066. }
  91067. };
  91068. /**
  91069. * Setup the ground diffuse texture according to the specified options.
  91070. */
  91071. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91072. if (!this._groundMaterial) {
  91073. return;
  91074. }
  91075. if (this._groundTexture) {
  91076. return;
  91077. }
  91078. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91079. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91080. return;
  91081. }
  91082. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91083. diffuseTexture.gammaSpace = false;
  91084. diffuseTexture.hasAlpha = true;
  91085. this._groundMaterial.diffuseTexture = diffuseTexture;
  91086. };
  91087. /**
  91088. * Setup the ground mirror texture according to the specified options.
  91089. */
  91090. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91091. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91092. if (!this._groundMirror) {
  91093. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91094. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91095. this._groundMirror.anisotropicFilteringLevel = 1;
  91096. this._groundMirror.wrapU = wrapping;
  91097. this._groundMirror.wrapV = wrapping;
  91098. this._groundMirror.gammaSpace = false;
  91099. if (this._groundMirror.renderList) {
  91100. for (var i = 0; i < this._scene.meshes.length; i++) {
  91101. var mesh = this._scene.meshes[i];
  91102. if (mesh !== this._ground &&
  91103. mesh !== this._skybox &&
  91104. mesh !== this._rootMesh) {
  91105. this._groundMirror.renderList.push(mesh);
  91106. }
  91107. }
  91108. }
  91109. }
  91110. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91111. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91112. };
  91113. /**
  91114. * Setup the ground to receive the mirror texture.
  91115. */
  91116. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91117. if (this._groundMaterial) {
  91118. this._groundMaterial.reflectionTexture = this._groundMirror;
  91119. this._groundMaterial.reflectionFresnel = true;
  91120. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91121. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91122. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91123. }
  91124. };
  91125. /**
  91126. * Setup the skybox according to the specified options.
  91127. */
  91128. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91129. var _this = this;
  91130. if (!this._skybox) {
  91131. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91132. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91133. }
  91134. this._skybox.parent = this._rootMesh;
  91135. };
  91136. /**
  91137. * Setup the skybox material according to the specified options.
  91138. */
  91139. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91140. if (!this._skybox) {
  91141. return;
  91142. }
  91143. if (!this._skyboxMaterial) {
  91144. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91145. }
  91146. this._skyboxMaterial.useRGBColor = false;
  91147. this._skyboxMaterial.primaryLevel = 1;
  91148. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91149. this._skyboxMaterial.secondaryLevel = 0;
  91150. this._skyboxMaterial.tertiaryLevel = 0;
  91151. this._skyboxMaterial.enableNoise = true;
  91152. this._skybox.material = this._skyboxMaterial;
  91153. };
  91154. /**
  91155. * Setup the skybox reflection texture according to the specified options.
  91156. */
  91157. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91158. if (!this._skyboxMaterial) {
  91159. return;
  91160. }
  91161. if (this._skyboxTexture) {
  91162. return;
  91163. }
  91164. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91165. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91166. return;
  91167. }
  91168. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91169. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91170. this._skyboxTexture.gammaSpace = false;
  91171. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91172. };
  91173. /**
  91174. * Dispose all the elements created by the Helper.
  91175. */
  91176. EnvironmentHelper.prototype.dispose = function () {
  91177. if (this._groundMaterial) {
  91178. this._groundMaterial.dispose(true, true);
  91179. }
  91180. if (this._skyboxMaterial) {
  91181. this._skyboxMaterial.dispose(true, true);
  91182. }
  91183. this._rootMesh.dispose(false);
  91184. };
  91185. /**
  91186. * Default ground texture URL.
  91187. */
  91188. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91189. /**
  91190. * Default skybox texture URL.
  91191. */
  91192. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91193. /**
  91194. * Default environment texture URL.
  91195. */
  91196. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91197. return EnvironmentHelper;
  91198. }());
  91199. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91200. })(BABYLON || (BABYLON = {}));
  91201. //# sourceMappingURL=babylon.environmentHelper.js.map
  91202. var BABYLON;
  91203. (function (BABYLON) {
  91204. /**
  91205. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91206. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91207. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91208. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91209. */
  91210. var VideoDome = /** @class */ (function (_super) {
  91211. __extends(VideoDome, _super);
  91212. /**
  91213. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91214. * @param name Element's name, child elements will append suffixes for their own names.
  91215. * @param urlsOrVideo
  91216. * @param options An object containing optional or exposed sub element properties:
  91217. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91218. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91219. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91220. * @param options **loop=true** Automatically loop video on end.
  91221. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91222. */
  91223. function VideoDome(name, urlsOrVideo, options, scene) {
  91224. var _this = _super.call(this, name, scene) || this;
  91225. // set defaults and manage values
  91226. name = name || "videoDome";
  91227. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91228. options.clickToPlay = Boolean(options.clickToPlay);
  91229. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91230. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91231. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91232. // create
  91233. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91234. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91235. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91236. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91237. flat: false,
  91238. radius: options.size,
  91239. subdivisions: options.resolution,
  91240. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91241. }, scene);
  91242. // configure material
  91243. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91244. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91245. material.reflectionTexture = _this._videoTexture;
  91246. material.useEquirectangularFOV = true;
  91247. material.fovMultiplier = 1.0;
  91248. // configure mesh
  91249. _this._mesh.material = material;
  91250. _this._mesh.parent = _this;
  91251. // optional configuration
  91252. if (options.clickToPlay) {
  91253. scene.onPointerUp = function () {
  91254. _this._videoTexture.video.play();
  91255. };
  91256. }
  91257. return _this;
  91258. }
  91259. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91260. /**
  91261. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91262. * Also see the options.resolution property.
  91263. */
  91264. get: function () {
  91265. return this._material.fovMultiplier;
  91266. },
  91267. set: function (value) {
  91268. this._material.fovMultiplier = value;
  91269. },
  91270. enumerable: true,
  91271. configurable: true
  91272. });
  91273. /**
  91274. * Releases resources associated with this node.
  91275. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91276. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91277. */
  91278. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91279. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91280. this._videoTexture.dispose();
  91281. this._mesh.dispose();
  91282. this._material.dispose();
  91283. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91284. };
  91285. return VideoDome;
  91286. }(BABYLON.Node));
  91287. BABYLON.VideoDome = VideoDome;
  91288. })(BABYLON || (BABYLON = {}));
  91289. //# sourceMappingURL=babylon.videoDome.js.map
  91290. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=size;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91291. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91292. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91293. globalObject["BABYLON"] = BABYLON
  91294. return BABYLON;
  91295. });
  91296. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91297. /***/ }),
  91298. /* 1 */
  91299. /***/ (function(module, exports, __webpack_require__) {
  91300. "use strict";
  91301. Object.defineProperty(exports, "__esModule", { value: true });
  91302. var babylonjs_1 = __webpack_require__(0);
  91303. var helper_1 = __webpack_require__(2);
  91304. var HTMLMapper = (function () {
  91305. function HTMLMapper() {
  91306. }
  91307. HTMLMapper.prototype.map = function (element) {
  91308. var config = {};
  91309. var _loop_1 = function (attrIdx) {
  91310. var attr = element.attributes.item(attrIdx);
  91311. var split = attr.nodeName.split('.');
  91312. split.reduce(function (currentConfig, key, idx) {
  91313. var camelKey = helper_1.kebabToCamel(key);
  91314. if (idx === split.length - 1) {
  91315. var val = attr.nodeValue;
  91316. if (val === "true") {
  91317. val = true;
  91318. }
  91319. else if (val === "false") {
  91320. val = false;
  91321. }
  91322. else {
  91323. var isnum = /^\d+$/.test(val);
  91324. if (isnum) {
  91325. var number = parseFloat(val);
  91326. if (!isNaN(number)) {
  91327. val = number;
  91328. }
  91329. }
  91330. }
  91331. currentConfig[camelKey] = val;
  91332. }
  91333. else {
  91334. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91335. }
  91336. return currentConfig[camelKey];
  91337. }, config);
  91338. };
  91339. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91340. _loop_1(attrIdx);
  91341. }
  91342. return config;
  91343. };
  91344. return HTMLMapper;
  91345. }());
  91346. var JSONMapper = (function () {
  91347. function JSONMapper() {
  91348. }
  91349. JSONMapper.prototype.map = function (rawSource) {
  91350. return JSON.parse(rawSource);
  91351. };
  91352. return JSONMapper;
  91353. }());
  91354. var DOMMapper = (function () {
  91355. function DOMMapper() {
  91356. }
  91357. DOMMapper.prototype.map = function (baseElement) {
  91358. var htmlMapper = new HTMLMapper();
  91359. var config = htmlMapper.map(baseElement);
  91360. var traverseChildren = function (element, partConfig) {
  91361. var children = element.children;
  91362. if (children.length) {
  91363. for (var i = 0; i < children.length; ++i) {
  91364. var item = children.item(i);
  91365. var configMapped = htmlMapper.map(item);
  91366. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91367. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91368. partConfig[key] = [];
  91369. }
  91370. else {
  91371. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91372. partConfig.push(configMapped);
  91373. }
  91374. else if (partConfig[key]) {
  91375. element.setAttribute('array', 'true');
  91376. var oldItem = partConfig[key];
  91377. partConfig = [oldItem, configMapped];
  91378. }
  91379. else {
  91380. partConfig[key] = configMapped;
  91381. }
  91382. }
  91383. traverseChildren(item, partConfig[key] || configMapped);
  91384. }
  91385. }
  91386. return partConfig;
  91387. };
  91388. traverseChildren(baseElement, config);
  91389. return config;
  91390. };
  91391. return DOMMapper;
  91392. }());
  91393. var MapperManager = (function () {
  91394. function MapperManager() {
  91395. this.mappers = {
  91396. "html": new HTMLMapper(),
  91397. "json": new JSONMapper(),
  91398. "dom": new DOMMapper()
  91399. };
  91400. }
  91401. MapperManager.prototype.getMapper = function (type) {
  91402. if (!this.mappers[type]) {
  91403. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91404. }
  91405. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91406. };
  91407. MapperManager.prototype.registerMapper = function (type, mapper) {
  91408. this.mappers[type] = mapper;
  91409. };
  91410. MapperManager.DefaultMapper = 'json';
  91411. return MapperManager;
  91412. }());
  91413. exports.MapperManager = MapperManager;
  91414. exports.mapperManager = new MapperManager();
  91415. /***/ }),
  91416. /* 2 */
  91417. /***/ (function(module, exports, __webpack_require__) {
  91418. "use strict";
  91419. Object.defineProperty(exports, "__esModule", { value: true });
  91420. function isUrl(urlToCheck) {
  91421. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91422. return true;
  91423. }
  91424. return false;
  91425. }
  91426. exports.isUrl = isUrl;
  91427. function kebabToCamel(s) {
  91428. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91429. }
  91430. exports.kebabToCamel = kebabToCamel;
  91431. function camelToKebab(str) {
  91432. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91433. }
  91434. exports.camelToKebab = camelToKebab;
  91435. /***/ }),
  91436. /* 3 */
  91437. /***/ (function(module, exports, __webpack_require__) {
  91438. "use strict";
  91439. Object.defineProperty(exports, "__esModule", { value: true });
  91440. var babylonjs_1 = __webpack_require__(0);
  91441. var ViewerManager = (function () {
  91442. function ViewerManager() {
  91443. this.viewers = {};
  91444. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91445. }
  91446. ViewerManager.prototype.addViewer = function (viewer) {
  91447. this.viewers[viewer.getBaseId()] = viewer;
  91448. this._onViewerAdded(viewer);
  91449. };
  91450. ViewerManager.prototype.getViewerById = function (id) {
  91451. return this.viewers[id];
  91452. };
  91453. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91454. for (var id in this.viewers) {
  91455. if (this.viewers[id].containerElement === element) {
  91456. return this.getViewerById(id);
  91457. }
  91458. }
  91459. };
  91460. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91461. var _this = this;
  91462. return new Promise(function (resolve, reject) {
  91463. var localViewer = _this.getViewerById(id);
  91464. if (localViewer) {
  91465. return resolve(localViewer);
  91466. }
  91467. var viewerFunction = function (viewer) {
  91468. if (viewer.getBaseId() === id) {
  91469. resolve(viewer);
  91470. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91471. }
  91472. };
  91473. _this.onViewerAddedObservable.add(viewerFunction);
  91474. });
  91475. };
  91476. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91477. this.onViewerAdded && this.onViewerAdded(viewer);
  91478. this.onViewerAddedObservable.notifyObservers(viewer);
  91479. };
  91480. return ViewerManager;
  91481. }());
  91482. exports.ViewerManager = ViewerManager;
  91483. exports.viewerManager = new ViewerManager();
  91484. /***/ }),
  91485. /* 4 */
  91486. /***/ (function(module, exports, __webpack_require__) {
  91487. "use strict";
  91488. var __extends = (this && this.__extends) || (function () {
  91489. var extendStatics = Object.setPrototypeOf ||
  91490. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91491. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91492. return function (d, b) {
  91493. extendStatics(d, b);
  91494. function __() { this.constructor = d; }
  91495. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91496. };
  91497. })();
  91498. Object.defineProperty(exports, "__esModule", { value: true });
  91499. var viewer_1 = __webpack_require__(5);
  91500. var babylonjs_1 = __webpack_require__(0);
  91501. var DefaultViewer = (function (_super) {
  91502. __extends(DefaultViewer, _super);
  91503. function DefaultViewer(containerElement, initialConfiguration) {
  91504. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91505. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91506. _this.containerElement = containerElement;
  91507. _this.onModelLoaded = function (model) {
  91508. var hideLoadingDelay = 500;
  91509. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91510. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91511. }
  91512. setTimeout(function () {
  91513. _this.hideLoadingScreen();
  91514. }, hideLoadingDelay);
  91515. return;
  91516. };
  91517. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91518. return _this;
  91519. }
  91520. DefaultViewer.prototype.initScene = function () {
  91521. var _this = this;
  91522. return _super.prototype.initScene.call(this).then(function () {
  91523. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91524. return _this.scene;
  91525. });
  91526. };
  91527. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91528. var _this = this;
  91529. this.showLoadingScreen();
  91530. this.initNavbar();
  91531. var closeButton = document.getElementById('close-button');
  91532. if (closeButton) {
  91533. closeButton.addEventListener('pointerdown', function () {
  91534. _this.hideOverlayScreen();
  91535. });
  91536. }
  91537. return _super.prototype.onTemplatesLoaded.call(this);
  91538. };
  91539. DefaultViewer.prototype.initNavbar = function () {
  91540. var navbar = this.templateManager.getTemplate('navBar');
  91541. if (navbar) {
  91542. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91543. var navbarShown_1 = true;
  91544. var timeoutCancel_1;
  91545. var triggerNavbar = function (show, evt) {
  91546. if (show === void 0) { show = false; }
  91547. if (!navbar || evt.button > 0)
  91548. return;
  91549. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91550. if (show === navbarShown_1)
  91551. return;
  91552. if (show) {
  91553. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91554. navbarShown_1 = show;
  91555. }
  91556. else {
  91557. var visibilityTimeout = 2000;
  91558. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91559. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91560. }
  91561. timeoutCancel_1 = setTimeout(function () {
  91562. if (navbar) {
  91563. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91564. }
  91565. navbarShown_1 = show;
  91566. }, visibilityTimeout);
  91567. }
  91568. };
  91569. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91570. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91571. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91572. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91573. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91574. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91575. var triggerFullscren = function (eventData) {
  91576. if (viewerElement_1) {
  91577. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91578. if (!fullscreenElement) {
  91579. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91580. requestFullScreen.call(viewerElement_1);
  91581. }
  91582. else {
  91583. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91584. exitFullscreen.call(document);
  91585. }
  91586. }
  91587. };
  91588. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91589. }
  91590. };
  91591. DefaultViewer.prototype.prepareContainerElement = function () {
  91592. this.containerElement.style.position = 'relative';
  91593. this.containerElement.style.display = 'flex';
  91594. };
  91595. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91596. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91597. var navbar = this.templateManager.getTemplate('navBar');
  91598. if (!navbar)
  91599. return;
  91600. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91601. if (metadataContainer) {
  91602. if (modelConfiguration.title !== undefined) {
  91603. var element = metadataContainer.querySelector('span.model-title');
  91604. if (element) {
  91605. element.innerHTML = modelConfiguration.title;
  91606. }
  91607. }
  91608. if (modelConfiguration.subtitle !== undefined) {
  91609. var element = metadataContainer.querySelector('span.model-subtitle');
  91610. if (element) {
  91611. element.innerHTML = modelConfiguration.subtitle;
  91612. }
  91613. }
  91614. if (modelConfiguration.thumbnail !== undefined) {
  91615. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91616. }
  91617. }
  91618. };
  91619. DefaultViewer.prototype.loadModel = function (model) {
  91620. var _this = this;
  91621. if (model === void 0) { model = this.configuration.model; }
  91622. this.showLoadingScreen();
  91623. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91624. console.log(error);
  91625. _this.hideLoadingScreen();
  91626. _this.showOverlayScreen('error');
  91627. return Promise.reject(error);
  91628. });
  91629. };
  91630. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91631. var _this = this;
  91632. var template = this.templateManager.getTemplate('overlay');
  91633. if (!template)
  91634. return Promise.resolve('Overlay template not found');
  91635. return template.show((function (template) {
  91636. var canvasRect = _this.containerElement.getBoundingClientRect();
  91637. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91638. template.parent.style.display = 'flex';
  91639. template.parent.style.width = canvasRect.width + "px";
  91640. template.parent.style.height = canvasRect.height + "px";
  91641. template.parent.style.opacity = "1";
  91642. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91643. if (!subTemplate) {
  91644. return Promise.reject(subScreen + ' template not found');
  91645. }
  91646. return subTemplate.show((function (template) {
  91647. template.parent.style.display = 'flex';
  91648. return Promise.resolve(template);
  91649. }));
  91650. }));
  91651. };
  91652. DefaultViewer.prototype.hideOverlayScreen = function () {
  91653. var template = this.templateManager.getTemplate('overlay');
  91654. if (!template)
  91655. return Promise.resolve('Overlay template not found');
  91656. return template.hide((function (template) {
  91657. template.parent.style.opacity = "0";
  91658. var onTransitionEnd = function () {
  91659. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91660. template.parent.style.display = 'none';
  91661. };
  91662. template.parent.addEventListener("transitionend", onTransitionEnd);
  91663. var overlays = template.parent.querySelectorAll('.overlay');
  91664. if (overlays) {
  91665. for (var i = 0; i < overlays.length; ++i) {
  91666. var htmlElement = overlays.item(i);
  91667. htmlElement.style.display = 'none';
  91668. }
  91669. }
  91670. return Promise.resolve(template);
  91671. }));
  91672. };
  91673. DefaultViewer.prototype.showLoadingScreen = function () {
  91674. var _this = this;
  91675. var template = this.templateManager.getTemplate('loadingScreen');
  91676. if (!template)
  91677. return Promise.resolve('Loading Screen template not found');
  91678. return template.show((function (template) {
  91679. var canvasRect = _this.containerElement.getBoundingClientRect();
  91680. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91681. template.parent.style.display = 'flex';
  91682. template.parent.style.width = canvasRect.width + "px";
  91683. template.parent.style.height = canvasRect.height + "px";
  91684. template.parent.style.opacity = "1";
  91685. template.parent.style.backgroundColor = "black";
  91686. return Promise.resolve(template);
  91687. }));
  91688. };
  91689. DefaultViewer.prototype.hideLoadingScreen = function () {
  91690. var template = this.templateManager.getTemplate('loadingScreen');
  91691. if (!template)
  91692. return Promise.resolve('Loading Screen template not found');
  91693. return template.hide((function (template) {
  91694. template.parent.style.opacity = "0";
  91695. var onTransitionEnd = function () {
  91696. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91697. template.parent.style.display = 'none';
  91698. };
  91699. template.parent.addEventListener("transitionend", onTransitionEnd);
  91700. return Promise.resolve(template);
  91701. }));
  91702. };
  91703. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91704. var _this = this;
  91705. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91706. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  91707. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91708. var pointerPosition = BABYLON.Vector3.Zero();
  91709. var lightTarget_1;
  91710. var angle = 0.5;
  91711. var exponent = Math.PI / 2;
  91712. if (typeof this.configuration.lab.flashlight === "object") {
  91713. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91714. angle = this.configuration.lab.flashlight.angle || angle;
  91715. }
  91716. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91717. if (typeof this.configuration.lab.flashlight === "object") {
  91718. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91719. if (this.configuration.lab.flashlight.diffuse) {
  91720. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91721. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91722. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91723. }
  91724. if (this.configuration.lab.flashlight.specular) {
  91725. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91726. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91727. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91728. }
  91729. }
  91730. this.scene.constantlyUpdateMeshUnderPointer = true;
  91731. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91732. if (eventData.type === 4 && eventData.pickInfo) {
  91733. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91734. }
  91735. else {
  91736. lightTarget_1 = undefined;
  91737. }
  91738. });
  91739. var updateFlashlightFunction = function () {
  91740. if (_this.camera && flashlight) {
  91741. flashlight.position.copyFrom(_this.camera.position);
  91742. if (lightTarget_1) {
  91743. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91744. }
  91745. }
  91746. };
  91747. this.scene.registerBeforeRender(updateFlashlightFunction);
  91748. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91749. }
  91750. };
  91751. return DefaultViewer;
  91752. }(viewer_1.AbstractViewer));
  91753. exports.DefaultViewer = DefaultViewer;
  91754. /***/ }),
  91755. /* 5 */
  91756. /***/ (function(module, exports, __webpack_require__) {
  91757. "use strict";
  91758. Object.defineProperty(exports, "__esModule", { value: true });
  91759. var viewerManager_1 = __webpack_require__(3);
  91760. var templateManager_1 = __webpack_require__(19);
  91761. var loader_1 = __webpack_require__(22);
  91762. var babylonjs_1 = __webpack_require__(0);
  91763. var deepmerge = __webpack_require__(13);
  91764. var viewerModel_1 = __webpack_require__(30);
  91765. var AbstractViewer = (function () {
  91766. function AbstractViewer(containerElement, initialConfiguration) {
  91767. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91768. var _this = this;
  91769. this.containerElement = containerElement;
  91770. this.resize = function () {
  91771. if (!_this.isCanvasInDOM()) {
  91772. return;
  91773. }
  91774. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91775. return;
  91776. }
  91777. _this.engine.resize();
  91778. };
  91779. this.render = function () {
  91780. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91781. };
  91782. if (containerElement.id) {
  91783. this.baseId = containerElement.id;
  91784. }
  91785. else {
  91786. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91787. }
  91788. this.onSceneInitObservable = new babylonjs_1.Observable();
  91789. this.onEngineInitObservable = new babylonjs_1.Observable();
  91790. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91791. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91792. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91793. this.onInitDoneObservable = new babylonjs_1.Observable();
  91794. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91795. this.registeredOnBeforerenderFunctions = [];
  91796. this.models = [];
  91797. viewerManager_1.viewerManager.addViewer(this);
  91798. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91799. this.prepareContainerElement();
  91800. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91801. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91802. if (_this.configuration.observers) {
  91803. _this.configureObservers(_this.configuration.observers);
  91804. }
  91805. var templateConfiguration = _this.configuration.templates || {};
  91806. _this.templateManager.initTemplate(templateConfiguration);
  91807. _this.templateManager.onAllLoaded.add(function () {
  91808. var canvas = _this.templateManager.getCanvas();
  91809. if (canvas) {
  91810. _this.canvas = canvas;
  91811. }
  91812. _this._onTemplateLoaded();
  91813. });
  91814. });
  91815. }
  91816. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91817. get: function () {
  91818. return this._hdrSupport;
  91819. },
  91820. enumerable: true,
  91821. configurable: true
  91822. });
  91823. AbstractViewer.prototype.getBaseId = function () {
  91824. return this.baseId;
  91825. };
  91826. AbstractViewer.prototype.isCanvasInDOM = function () {
  91827. return !!this.canvas && !!this.canvas.parentElement;
  91828. };
  91829. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91830. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91831. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91832. if (newConfiguration.scene) {
  91833. this.configureScene(newConfiguration.scene);
  91834. }
  91835. if (newConfiguration.optimizer) {
  91836. this.configureOptimizer(newConfiguration.optimizer);
  91837. }
  91838. if (newConfiguration.observers) {
  91839. this.configureObservers(newConfiguration.observers);
  91840. }
  91841. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91842. this.configureModel(newConfiguration.model);
  91843. }
  91844. if (newConfiguration.lights) {
  91845. this.configureLights(newConfiguration.lights);
  91846. }
  91847. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91848. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91849. }
  91850. if (newConfiguration.camera) {
  91851. this.configureCamera(newConfiguration.camera);
  91852. }
  91853. };
  91854. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91855. if (!skyboxConifguration && !groundConfiguration) {
  91856. if (this.environmentHelper) {
  91857. this.environmentHelper.dispose();
  91858. delete this.environmentHelper;
  91859. }
  91860. ;
  91861. return Promise.resolve(this.scene);
  91862. }
  91863. var options = {
  91864. createGround: !!groundConfiguration,
  91865. createSkybox: !!skyboxConifguration,
  91866. setupImageProcessing: false
  91867. };
  91868. if (groundConfiguration) {
  91869. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91870. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91871. if (groundSize) {
  91872. options.groundSize = groundSize;
  91873. }
  91874. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91875. if (groundConfig.shadowLevel !== undefined) {
  91876. options.groundShadowLevel = groundConfig.shadowLevel;
  91877. }
  91878. options.enableGroundMirror = !!groundConfig.mirror;
  91879. if (groundConfig.texture) {
  91880. options.groundTexture = groundConfig.texture;
  91881. }
  91882. if (groundConfig.color) {
  91883. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91884. }
  91885. if (groundConfig.opacity !== undefined) {
  91886. options.groundOpacity = groundConfig.opacity;
  91887. }
  91888. if (groundConfig.mirror) {
  91889. options.enableGroundMirror = true;
  91890. if (typeof groundConfig.mirror === "object") {
  91891. if (groundConfig.mirror.amount !== undefined)
  91892. options.groundMirrorAmount = groundConfig.mirror.amount;
  91893. if (groundConfig.mirror.sizeRatio !== undefined)
  91894. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91895. if (groundConfig.mirror.blurKernel !== undefined)
  91896. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91897. if (groundConfig.mirror.fresnelWeight !== undefined)
  91898. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91899. if (groundConfig.mirror.fallOffDistance !== undefined)
  91900. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91901. if (this.defaultPipelineTextureType !== undefined)
  91902. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91903. }
  91904. }
  91905. }
  91906. var postInitSkyboxMaterial = false;
  91907. if (skyboxConifguration) {
  91908. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91909. if (conf.material && conf.material.imageProcessingConfiguration) {
  91910. options.setupImageProcessing = false;
  91911. }
  91912. var skyboxSize = conf.scale;
  91913. if (skyboxSize) {
  91914. options.skyboxSize = skyboxSize;
  91915. }
  91916. options.sizeAuto = !options.skyboxSize;
  91917. if (conf.color) {
  91918. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91919. }
  91920. if (conf.cubeTexture && conf.cubeTexture.url) {
  91921. if (typeof conf.cubeTexture.url === "string") {
  91922. options.skyboxTexture = conf.cubeTexture.url;
  91923. }
  91924. else {
  91925. postInitSkyboxMaterial = true;
  91926. }
  91927. }
  91928. if (conf.material && conf.material.imageProcessingConfiguration) {
  91929. postInitSkyboxMaterial = true;
  91930. }
  91931. }
  91932. options.setupImageProcessing = false;
  91933. if (!this.environmentHelper) {
  91934. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91935. }
  91936. else {
  91937. var scene = this.environmentHelper.rootMesh.getScene();
  91938. if (scene !== this.scene) {
  91939. this.environmentHelper.dispose();
  91940. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91941. }
  91942. else {
  91943. this.environmentHelper.updateOptions(options);
  91944. }
  91945. }
  91946. if (postInitSkyboxMaterial) {
  91947. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  91948. if (skyboxMaterial) {
  91949. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  91950. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  91951. }
  91952. }
  91953. }
  91954. };
  91955. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  91956. if (!this.scene) {
  91957. return;
  91958. }
  91959. if (sceneConfig.debug) {
  91960. this.scene.debugLayer.show();
  91961. }
  91962. else {
  91963. if (this.scene.debugLayer.isVisible()) {
  91964. this.scene.debugLayer.hide();
  91965. }
  91966. }
  91967. if (sceneConfig.clearColor) {
  91968. var cc = sceneConfig.clearColor;
  91969. var oldcc = this.scene.clearColor;
  91970. if (cc.r !== undefined) {
  91971. oldcc.r = cc.r;
  91972. }
  91973. if (cc.g !== undefined) {
  91974. oldcc.g = cc.g;
  91975. }
  91976. if (cc.b !== undefined) {
  91977. oldcc.b = cc.b;
  91978. }
  91979. if (cc.a !== undefined) {
  91980. oldcc.a = cc.a;
  91981. }
  91982. }
  91983. if (sceneConfig.imageProcessingConfiguration) {
  91984. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  91985. }
  91986. if (sceneConfig.environmentTexture) {
  91987. if (this.scene.environmentTexture) {
  91988. this.scene.environmentTexture.dispose();
  91989. }
  91990. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  91991. this.scene.environmentTexture = environmentTexture;
  91992. }
  91993. if (sceneConfig.autoRotate) {
  91994. this.camera.useAutoRotationBehavior = true;
  91995. }
  91996. };
  91997. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  91998. if (typeof optimizerConfig === 'boolean') {
  91999. if (this.sceneOptimizer) {
  92000. this.sceneOptimizer.stop();
  92001. this.sceneOptimizer.dispose();
  92002. delete this.sceneOptimizer;
  92003. }
  92004. if (optimizerConfig) {
  92005. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  92006. this.sceneOptimizer.start();
  92007. }
  92008. }
  92009. else {
  92010. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  92011. if (optimizerConfig.degradation) {
  92012. switch (optimizerConfig.degradation) {
  92013. case "low":
  92014. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  92015. break;
  92016. case "moderate":
  92017. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  92018. break;
  92019. case "hight":
  92020. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  92021. break;
  92022. }
  92023. }
  92024. if (this.sceneOptimizer) {
  92025. this.sceneOptimizer.stop();
  92026. this.sceneOptimizer.dispose();
  92027. }
  92028. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  92029. this.sceneOptimizer.start();
  92030. }
  92031. };
  92032. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  92033. if (observersConfiguration.onEngineInit) {
  92034. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  92035. }
  92036. else {
  92037. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  92038. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  92039. }
  92040. }
  92041. if (observersConfiguration.onSceneInit) {
  92042. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  92043. }
  92044. else {
  92045. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  92046. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  92047. }
  92048. }
  92049. if (observersConfiguration.onModelLoaded) {
  92050. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  92051. }
  92052. else {
  92053. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  92054. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  92055. }
  92056. }
  92057. };
  92058. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  92059. var _this = this;
  92060. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92061. if (!this.scene.activeCamera) {
  92062. this.scene.createDefaultCamera(true, true, true);
  92063. this.camera = this.scene.activeCamera;
  92064. }
  92065. if (cameraConfig.position) {
  92066. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  92067. }
  92068. if (cameraConfig.rotation) {
  92069. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  92070. }
  92071. this.extendClassWithConfig(this.camera, cameraConfig);
  92072. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  92073. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  92074. if (cameraConfig.behaviors) {
  92075. for (var name_1 in cameraConfig.behaviors) {
  92076. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  92077. }
  92078. }
  92079. ;
  92080. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  92081. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  92082. });
  92083. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92084. var sceneDiagonalLenght = sceneDiagonal.length();
  92085. if (isFinite(sceneDiagonalLenght))
  92086. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92087. };
  92088. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92089. var _this = this;
  92090. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92091. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92092. if (!Object.keys(lightsConfiguration).length)
  92093. return;
  92094. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92095. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92096. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92097. lightsAvailable.forEach(function (lName) {
  92098. if (lightsToConfigure.indexOf(lName) === -1) {
  92099. _this.scene.getLightByName(lName).dispose();
  92100. }
  92101. });
  92102. }
  92103. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92104. var lightConfig = { type: 0 };
  92105. if (typeof lightsConfiguration[name] === 'object') {
  92106. lightConfig = lightsConfiguration[name];
  92107. }
  92108. lightConfig.name = name;
  92109. var light;
  92110. if (lightsAvailable.indexOf(name) === -1) {
  92111. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92112. if (!constructor)
  92113. return;
  92114. light = constructor();
  92115. }
  92116. else {
  92117. light = _this.scene.getLightByName(name);
  92118. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92119. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92120. light.dispose();
  92121. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92122. if (!constructor)
  92123. return;
  92124. light = constructor();
  92125. }
  92126. }
  92127. if (lightsConfiguration[name] === false) {
  92128. light.dispose();
  92129. return;
  92130. }
  92131. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92132. light.setEnabled(enabled);
  92133. _this.extendClassWithConfig(light, lightConfig);
  92134. if (light instanceof babylonjs_1.ShadowLight) {
  92135. if (lightConfig.target) {
  92136. if (light.setDirectionToTarget) {
  92137. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92138. light.setDirectionToTarget(target);
  92139. }
  92140. }
  92141. else if (lightConfig.direction) {
  92142. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92143. light.direction = direction;
  92144. }
  92145. var shadowGenerator = light.getShadowGenerator();
  92146. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92147. if (!shadowGenerator) {
  92148. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92149. }
  92150. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92151. var shadownMap = shadowGenerator.getShadowMap();
  92152. if (!shadownMap)
  92153. return;
  92154. var renderList = shadownMap.renderList;
  92155. for (var index = 0; index < focusMeshes.length; index++) {
  92156. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92157. renderList && renderList.push(focusMeshes[index]);
  92158. }
  92159. }
  92160. }
  92161. else if (shadowGenerator) {
  92162. shadowGenerator.dispose();
  92163. }
  92164. }
  92165. });
  92166. };
  92167. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92168. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92169. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92170. var updateMeshesWithNoParent = function (variable, value, param) {
  92171. meshesWithNoParent.forEach(function (mesh) {
  92172. if (param) {
  92173. mesh[variable][param] = value;
  92174. }
  92175. else {
  92176. mesh[variable] = value;
  92177. }
  92178. });
  92179. };
  92180. var updateXYZ = function (variable, configValues) {
  92181. if (configValues.x !== undefined) {
  92182. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92183. }
  92184. if (configValues.y !== undefined) {
  92185. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92186. }
  92187. if (configValues.z !== undefined) {
  92188. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92189. }
  92190. if (configValues.w !== undefined) {
  92191. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92192. }
  92193. };
  92194. if (modelConfiguration.position) {
  92195. updateXYZ('position', modelConfiguration.position);
  92196. }
  92197. if (modelConfiguration.rotation) {
  92198. if (modelConfiguration.rotation.w) {
  92199. meshesWithNoParent.forEach(function (mesh) {
  92200. if (!mesh.rotationQuaternion) {
  92201. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92202. }
  92203. });
  92204. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92205. }
  92206. else {
  92207. updateXYZ('rotation', modelConfiguration.rotation);
  92208. }
  92209. }
  92210. if (modelConfiguration.scaling) {
  92211. updateXYZ('scaling', modelConfiguration.scaling);
  92212. }
  92213. if (modelConfiguration.castShadow) {
  92214. focusMeshes.forEach(function (mesh) {
  92215. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92216. });
  92217. }
  92218. if (modelConfiguration.normalize) {
  92219. var center = false;
  92220. var unitSize = false;
  92221. var parentIndex = void 0;
  92222. if (modelConfiguration.normalize === true) {
  92223. center = true;
  92224. unitSize = true;
  92225. parentIndex = 0;
  92226. }
  92227. else {
  92228. center = !!modelConfiguration.normalize.center;
  92229. unitSize = !!modelConfiguration.normalize.unitSize;
  92230. parentIndex = modelConfiguration.normalize.parentIndex;
  92231. }
  92232. var meshesToNormalize = [];
  92233. if (parentIndex !== undefined) {
  92234. meshesToNormalize.push(focusMeshes[parentIndex]);
  92235. }
  92236. else {
  92237. meshesToNormalize = meshesWithNoParent;
  92238. }
  92239. if (unitSize) {
  92240. meshesToNormalize.forEach(function (mesh) {
  92241. mesh.normalizeToUnitCube(true);
  92242. mesh.computeWorldMatrix(true);
  92243. });
  92244. }
  92245. if (center) {
  92246. meshesToNormalize.forEach(function (mesh) {
  92247. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92248. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92249. var halfSizeVec = sizeVec.scale(0.5);
  92250. var center = boundingInfo.min.add(halfSizeVec);
  92251. mesh.position = center.scale(-1);
  92252. mesh.position.y += halfSizeVec.y;
  92253. mesh.computeWorldMatrix(true);
  92254. });
  92255. }
  92256. }
  92257. };
  92258. AbstractViewer.prototype.dispose = function () {
  92259. window.removeEventListener('resize', this.resize);
  92260. if (this.sceneOptimizer) {
  92261. this.sceneOptimizer.stop();
  92262. this.sceneOptimizer.dispose();
  92263. }
  92264. if (this.scene.activeCamera) {
  92265. this.scene.activeCamera.detachControl(this.canvas);
  92266. }
  92267. this.scene.dispose();
  92268. this.engine.dispose();
  92269. this.templateManager.dispose();
  92270. };
  92271. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92272. return Promise.resolve(this);
  92273. };
  92274. AbstractViewer.prototype._onTemplateLoaded = function () {
  92275. var _this = this;
  92276. return this.onTemplatesLoaded().then(function () {
  92277. var autoLoadModel = !!_this.configuration.model;
  92278. return _this.initEngine().then(function (engine) {
  92279. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92280. }).then(function () {
  92281. if (autoLoadModel) {
  92282. return _this.loadModel().then(function () { return _this.scene; });
  92283. }
  92284. else {
  92285. return _this.scene || _this.initScene();
  92286. }
  92287. }).then(function (scene) {
  92288. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92289. }).then(function () {
  92290. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92291. });
  92292. });
  92293. };
  92294. AbstractViewer.prototype.initEngine = function () {
  92295. this.injectCustomShaders();
  92296. var canvasElement = this.templateManager.getCanvas();
  92297. if (!canvasElement) {
  92298. return Promise.reject('Canvas element not found!');
  92299. }
  92300. var config = this.configuration.engine || {};
  92301. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92302. babylonjs_1.Database.IDBStorageEnabled = false;
  92303. if (!config.disableResize) {
  92304. window.addEventListener('resize', this.resize);
  92305. }
  92306. this.engine.runRenderLoop(this.render);
  92307. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92308. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92309. this.engine.setHardwareScalingLevel(scale);
  92310. }
  92311. this.handleHardwareLimitations();
  92312. return Promise.resolve(this.engine);
  92313. };
  92314. AbstractViewer.prototype.initScene = function () {
  92315. if (this.scene) {
  92316. this.scene.dispose();
  92317. }
  92318. this.scene = new babylonjs_1.Scene(this.engine);
  92319. this.scene.createDefaultLight(true);
  92320. if (this.configuration.scene) {
  92321. this.configureScene(this.configuration.scene);
  92322. if (this.configuration.optimizer) {
  92323. this.configureOptimizer(this.configuration.optimizer);
  92324. }
  92325. }
  92326. return Promise.resolve(this.scene);
  92327. };
  92328. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92329. var _this = this;
  92330. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92331. if (clearScene === void 0) { clearScene = true; }
  92332. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92333. if (!modelUrl) {
  92334. return Promise.reject("no model configuration found");
  92335. }
  92336. if (this.isLoading) {
  92337. return Promise.reject("sanother model is curently being loaded.");
  92338. }
  92339. this.isLoading = true;
  92340. if ((typeof modelConfig === 'string')) {
  92341. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92342. this.configuration.model.url = modelConfig;
  92343. }
  92344. }
  92345. else {
  92346. if (this.configuration.model) {
  92347. deepmerge(this.configuration.model, modelConfig);
  92348. }
  92349. else {
  92350. this.configuration.model = modelConfig;
  92351. }
  92352. }
  92353. return Promise.resolve(this.scene).then(function (scene) {
  92354. if (!scene)
  92355. return _this.initScene();
  92356. if (clearScene) {
  92357. _this.models.forEach(function (m) { return m.dispose(); });
  92358. _this.models.length = 0;
  92359. }
  92360. return scene;
  92361. }).then(function () {
  92362. return new Promise(function (resolve, reject) {
  92363. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92364. _this.models.push(model);
  92365. _this.lastUsedLoader = model.loader;
  92366. model.onLoadedObservable.add(function (model) {
  92367. resolve(model);
  92368. });
  92369. model.onLoadErrorObservable.add(function (errorObject) {
  92370. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92371. reject(errorObject.exception);
  92372. });
  92373. });
  92374. model.onLoadProgressObservable.add(function (progressEvent) {
  92375. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92376. });
  92377. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92378. });
  92379. }).then(function (model) {
  92380. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92381. .then(function () {
  92382. _this.configureModel(_this.configuration.model || modelConfig, model);
  92383. _this.configureLights(_this.configuration.lights);
  92384. if (_this.configuration.camera) {
  92385. _this.configureCamera(_this.configuration.camera, model);
  92386. }
  92387. return _this.initEnvironment(model);
  92388. }).then(function () {
  92389. _this.isLoading = false;
  92390. return model;
  92391. });
  92392. });
  92393. };
  92394. AbstractViewer.prototype.initEnvironment = function (model) {
  92395. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92396. return Promise.resolve(this.scene);
  92397. };
  92398. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92399. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92400. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92401. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92402. this.maxShadows = 0;
  92403. }
  92404. else {
  92405. this.maxShadows = 3;
  92406. }
  92407. var caps = this.engine.getCaps();
  92408. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92409. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92410. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92411. if (linearHalfFloatTargets) {
  92412. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92413. this.shadowGeneratorBias = 0.002;
  92414. }
  92415. else if (linearFloatTargets) {
  92416. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92417. this.shadowGeneratorBias = 0.001;
  92418. }
  92419. else {
  92420. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92421. this.shadowGeneratorBias = 0.001;
  92422. }
  92423. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92424. };
  92425. AbstractViewer.prototype.injectCustomShaders = function () {
  92426. var customShaders = this.configuration.customShaders;
  92427. if (!customShaders) {
  92428. return;
  92429. }
  92430. if (customShaders.shaders) {
  92431. Object.keys(customShaders.shaders).forEach(function (key) {
  92432. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92433. });
  92434. }
  92435. if (customShaders.includes) {
  92436. Object.keys(customShaders.includes).forEach(function (key) {
  92437. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92438. });
  92439. }
  92440. };
  92441. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92442. var _this = this;
  92443. if (!config)
  92444. return;
  92445. Object.keys(config).forEach(function (key) {
  92446. if (key in object && typeof object[key] !== 'function') {
  92447. if (typeof object[key] === 'object') {
  92448. _this.extendClassWithConfig(object[key], config[key]);
  92449. }
  92450. else {
  92451. if (config[key] !== undefined) {
  92452. object[key] = config[key];
  92453. }
  92454. }
  92455. }
  92456. });
  92457. };
  92458. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92459. var behavior;
  92460. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92461. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92462. switch (type) {
  92463. case 0:
  92464. this.camera.useAutoRotationBehavior = true;
  92465. behavior = this.camera.autoRotationBehavior;
  92466. break;
  92467. case 1:
  92468. this.camera.useBouncingBehavior = true;
  92469. behavior = this.camera.bouncingBehavior;
  92470. break;
  92471. case 2:
  92472. this.camera.useFramingBehavior = true;
  92473. behavior = this.camera.framingBehavior;
  92474. break;
  92475. default:
  92476. behavior = null;
  92477. break;
  92478. }
  92479. if (behavior) {
  92480. if (typeof behaviorConfig === "object") {
  92481. this.extendClassWithConfig(behavior, behaviorConfig);
  92482. }
  92483. }
  92484. switch (type) {
  92485. case 0:
  92486. break;
  92487. case 1:
  92488. break;
  92489. case 2:
  92490. if (config.zoomOnBoundingInfo) {
  92491. var meshes = payload;
  92492. var bounding = meshes[0].getHierarchyBoundingVectors();
  92493. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92494. }
  92495. break;
  92496. }
  92497. };
  92498. return AbstractViewer;
  92499. }());
  92500. exports.AbstractViewer = AbstractViewer;
  92501. /***/ }),
  92502. /* 6 */
  92503. /***/ (function(module, exports) {
  92504. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92505. /***/ }),
  92506. /* 7 */
  92507. /***/ (function(module, exports) {
  92508. 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}}>";
  92509. /***/ }),
  92510. /* 8 */
  92511. /***/ (function(module, exports) {
  92512. 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=="
  92513. /***/ }),
  92514. /* 9 */
  92515. /***/ (function(module, exports) {
  92516. 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>";
  92517. /***/ }),
  92518. /* 10 */
  92519. /***/ (function(module, exports) {
  92520. 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>";
  92521. /***/ }),
  92522. /* 11 */
  92523. /***/ (function(module, exports) {
  92524. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92525. /***/ }),
  92526. /* 12 */
  92527. /***/ (function(module, exports) {
  92528. module.exports = "Error loading the model";
  92529. /***/ }),
  92530. /* 13 */
  92531. /***/ (function(module, exports, __webpack_require__) {
  92532. (function (global, factory) {
  92533. true ? module.exports = factory() :
  92534. typeof define === 'function' && define.amd ? define(factory) :
  92535. (global.deepmerge = factory());
  92536. }(this, (function () { 'use strict';
  92537. var isMergeableObject = function isMergeableObject(value) {
  92538. return isNonNullObject(value)
  92539. && !isSpecial(value)
  92540. };
  92541. function isNonNullObject(value) {
  92542. return !!value && typeof value === 'object'
  92543. }
  92544. function isSpecial(value) {
  92545. var stringValue = Object.prototype.toString.call(value);
  92546. return stringValue === '[object RegExp]'
  92547. || stringValue === '[object Date]'
  92548. || isReactElement(value)
  92549. }
  92550. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92551. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92552. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92553. function isReactElement(value) {
  92554. return value.$$typeof === REACT_ELEMENT_TYPE
  92555. }
  92556. function emptyTarget(val) {
  92557. return Array.isArray(val) ? [] : {}
  92558. }
  92559. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92560. var clone = !optionsArgument || optionsArgument.clone !== false;
  92561. return (clone && isMergeableObject(value))
  92562. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92563. : value
  92564. }
  92565. function defaultArrayMerge(target, source, optionsArgument) {
  92566. return target.concat(source).map(function(element) {
  92567. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92568. })
  92569. }
  92570. function mergeObject(target, source, optionsArgument) {
  92571. var destination = {};
  92572. if (isMergeableObject(target)) {
  92573. Object.keys(target).forEach(function(key) {
  92574. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92575. });
  92576. }
  92577. Object.keys(source).forEach(function(key) {
  92578. if (!isMergeableObject(source[key]) || !target[key]) {
  92579. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92580. } else {
  92581. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92582. }
  92583. });
  92584. return destination
  92585. }
  92586. function deepmerge(target, source, optionsArgument) {
  92587. var sourceIsArray = Array.isArray(source);
  92588. var targetIsArray = Array.isArray(target);
  92589. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92590. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92591. if (!sourceAndTargetTypesMatch) {
  92592. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92593. } else if (sourceIsArray) {
  92594. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92595. return arrayMerge(target, source, optionsArgument)
  92596. } else {
  92597. return mergeObject(target, source, optionsArgument)
  92598. }
  92599. }
  92600. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92601. if (!Array.isArray(array)) {
  92602. throw new Error('first argument should be an array')
  92603. }
  92604. return array.reduce(function(prev, next) {
  92605. return deepmerge(prev, next, optionsArgument)
  92606. }, {})
  92607. };
  92608. var deepmerge_1 = deepmerge;
  92609. return deepmerge_1;
  92610. })));
  92611. /***/ }),
  92612. /* 14 */
  92613. /***/ (function(module, exports, __webpack_require__) {
  92614. module.exports = __webpack_require__(15);
  92615. /***/ }),
  92616. /* 15 */
  92617. /***/ (function(module, exports, __webpack_require__) {
  92618. "use strict";
  92619. Object.defineProperty(exports, "__esModule", { value: true });
  92620. var mappers_1 = __webpack_require__(1);
  92621. exports.mapperManager = mappers_1.mapperManager;
  92622. var viewerManager_1 = __webpack_require__(3);
  92623. exports.viewerManager = viewerManager_1.viewerManager;
  92624. var defaultViewer_1 = __webpack_require__(4);
  92625. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92626. var viewer_1 = __webpack_require__(5);
  92627. exports.AbstractViewer = viewer_1.AbstractViewer;
  92628. var babylonjs_1 = __webpack_require__(0);
  92629. __webpack_require__(32);
  92630. __webpack_require__(33);
  92631. var initializer_1 = __webpack_require__(34);
  92632. exports.InitTags = initializer_1.InitTags;
  92633. babylonjs_1.PromisePolyfill.Apply();
  92634. exports.disableInit = false;
  92635. document.addEventListener("DOMContentLoaded", function (event) {
  92636. if (exports.disableInit)
  92637. return;
  92638. initializer_1.InitTags();
  92639. });
  92640. /***/ }),
  92641. /* 16 */
  92642. /***/ (function(module, exports) {
  92643. var g;
  92644. // This works in non-strict mode
  92645. g = (function() {
  92646. return this;
  92647. })();
  92648. try {
  92649. // This works if eval is allowed (see CSP)
  92650. g = g || Function("return this")() || (1,eval)("this");
  92651. } catch(e) {
  92652. // This works if the window reference is available
  92653. if(typeof window === "object")
  92654. g = window;
  92655. }
  92656. // g can still be undefined, but nothing to do about it...
  92657. // We return undefined, instead of nothing here, so it's
  92658. // easier to handle this case. if(!global) { ...}
  92659. module.exports = g;
  92660. /***/ }),
  92661. /* 17 */
  92662. /***/ (function(module, exports) {
  92663. module.exports = cannon;
  92664. /***/ }),
  92665. /* 18 */
  92666. /***/ (function(module, exports, __webpack_require__) {
  92667. /**
  92668. * from OimoPhysics DEV 1.1.0a AS3
  92669. * @author Saharan / http://el-ement.com/
  92670. *
  92671. * to Oimo.js 2015 JAVASCRIPT
  92672. * @author LoTh / http://lo-th.github.io/labs/
  92673. */
  92674. var OIMO = {
  92675. REVISION: "1.2",
  92676. // Global identification of next shape.
  92677. // This will be incremented every time a shape is created.
  92678. nextID: 0,
  92679. proxyID: 0,
  92680. // BroadPhase
  92681. BR_NULL: 0,
  92682. BR_BRUTE_FORCE: 1,
  92683. BR_SWEEP_AND_PRUNE: 2,
  92684. BR_BOUNDING_VOLUME_TREE: 3,
  92685. // body type
  92686. BODY_NULL: 0,
  92687. BODY_DYNAMIC: 1,
  92688. BODY_STATIC: 2,
  92689. // shape type
  92690. SHAPE_NULL: 0,
  92691. SHAPE_SPHERE: 1,
  92692. SHAPE_BOX: 2,
  92693. SHAPE_CYLINDER: 3,
  92694. SHAPE_TETRA: 4,
  92695. // joint type
  92696. JOINT_NULL: 0,
  92697. JOINT_DISTANCE: 1,
  92698. JOINT_BALL_AND_SOCKET: 2,
  92699. JOINT_HINGE: 3,
  92700. JOINT_WHEEL: 4,
  92701. JOINT_SLIDER: 5,
  92702. JOINT_PRISMATIC: 6,
  92703. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92704. // scale all by 100 so object is between 10 to 10000 three unit.
  92705. WORLD_SCALE: 100,
  92706. INV_SCALE: 0.01,
  92707. // AABB aproximation
  92708. AABB_PROX: 0.005,
  92709. // Math function
  92710. sqrt: Math.sqrt,
  92711. abs: Math.abs,
  92712. floor: Math.floor,
  92713. cos: Math.cos,
  92714. sin: Math.sin,
  92715. acos: Math.acos,
  92716. asin: Math.asin,
  92717. atan2: Math.atan2,
  92718. round: Math.round,
  92719. pow: Math.pow,
  92720. max: Math.max,
  92721. min: Math.min,
  92722. random: Math.random,
  92723. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92724. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92725. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92726. int: function (x) { return ~~x; },
  92727. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92728. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92729. degtorad: 0.0174532925199432957,
  92730. radtodeg: 57.295779513082320876,
  92731. PI: 3.141592653589793,
  92732. TwoPI: 6.283185307179586,
  92733. PI90: 1.570796326794896,
  92734. PI270: 4.712388980384689,
  92735. CustomError: null,
  92736. Error: function (Class, Msg) {
  92737. if (OIMO.CustomError == null) console.error(Class, Msg);
  92738. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92739. }
  92740. };
  92741. var OIMO_ARRAY_TYPE;
  92742. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92743. try {
  92744. (function (w) {
  92745. var perfNow;
  92746. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92747. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92748. var n = perfNowNames[i];
  92749. if (!!w['performance'][n]) {
  92750. perfNow = function () { return w['performance'][n]() };
  92751. break;
  92752. }
  92753. }
  92754. if (!perfNow) perfNow = Date.now;
  92755. //w.perfNow = perfNow;
  92756. OIMO.now = perfNow;
  92757. })(window);
  92758. } catch (e) { OIMO.now = function () { return 0; }; }
  92759. /**
  92760. * The class of physical computing world.
  92761. * You must be added to the world physical all computing objects
  92762. * @author saharan
  92763. * @author lo-th
  92764. */
  92765. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92766. // The time between each step
  92767. this.timeStep = TimeStep || 0.01666; // 1/60;
  92768. // The number of iterations for constraint solvers.
  92769. this.numIterations = Iterations || 8;
  92770. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92771. switch (BroadPhaseType || 2) {
  92772. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92773. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92774. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92775. }
  92776. // This is the detailed information of the performance.
  92777. this.performance = null;
  92778. this.isNoStat = NoStat || false;
  92779. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92780. // Whether the constraints randomizer is enabled or not.
  92781. this.enableRandomizer = true;
  92782. // The rigid body list
  92783. this.rigidBodies = null;
  92784. // number of rigid body
  92785. this.numRigidBodies = 0;
  92786. // The contact list
  92787. this.contacts = null;
  92788. this.unusedContacts = null;
  92789. // The number of contact
  92790. this.numContacts = 0;
  92791. // The number of contact points
  92792. this.numContactPoints = 0;
  92793. // The joint list
  92794. this.joints = null;
  92795. // The number of joints.
  92796. this.numJoints = 0;
  92797. // The number of simulation islands.
  92798. this.numIslands = 0;
  92799. // The gravity in the world.
  92800. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92801. var numShapeTypes = 5;//4;//3;
  92802. this.detectors = [];
  92803. this.detectors.length = numShapeTypes;
  92804. var i = numShapeTypes;
  92805. while (i--) {
  92806. this.detectors[i] = [];
  92807. this.detectors[i].length = numShapeTypes;
  92808. }
  92809. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92810. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92811. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92812. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92813. // CYLINDER add
  92814. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92815. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92816. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92817. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92818. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92819. // TETRA add
  92820. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92821. this.randX = 65535;
  92822. this.randA = 98765;
  92823. this.randB = 123456789;
  92824. //this.maxIslandRigidBodies = 64;
  92825. this.islandRigidBodies = [];
  92826. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92827. this.islandStack = [];
  92828. //this.islandStack.length = this.maxIslandRigidBodies;
  92829. //this.maxIslandConstraints = 128;
  92830. this.islandConstraints = [];
  92831. //this.islandConstraints.length = this.maxIslandConstraints;
  92832. };
  92833. OIMO.World.prototype = {
  92834. constructor: OIMO.World,
  92835. /**
  92836. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92837. */
  92838. clear: function () {
  92839. this.randX = 65535;
  92840. while (this.joints !== null) {
  92841. this.removeJoint(this.joints);
  92842. }
  92843. while (this.contacts !== null) {
  92844. this.removeContact(this.contacts);
  92845. }
  92846. while (this.rigidBodies !== null) {
  92847. this.removeRigidBody(this.rigidBodies);
  92848. }
  92849. OIMO.nextID = 0;
  92850. OIMO.proxyID = 0;
  92851. },
  92852. /**
  92853. * I'll add a rigid body to the world.
  92854. * Rigid body that has been added will be the operands of each step.
  92855. * @param rigidBody Rigid body that you want to add
  92856. */
  92857. addRigidBody: function (rigidBody) {
  92858. if (rigidBody.parent) {
  92859. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92860. }
  92861. rigidBody.parent = this;
  92862. rigidBody.awake();
  92863. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92864. this.addShape(shape);
  92865. }
  92866. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92867. this.rigidBodies = rigidBody;
  92868. this.numRigidBodies++;
  92869. },
  92870. /**
  92871. * I will remove the rigid body from the world.
  92872. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92873. * @param rigidBody Rigid body to be removed
  92874. */
  92875. removeRigidBody: function (rigidBody) {
  92876. var remove = rigidBody;
  92877. if (remove.parent !== this) return;
  92878. remove.awake();
  92879. var js = remove.jointLink;
  92880. while (js != null) {
  92881. var joint = js.joint;
  92882. js = js.next;
  92883. this.removeJoint(joint);
  92884. }
  92885. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92886. this.removeShape(shape);
  92887. }
  92888. var prev = remove.prev;
  92889. var next = remove.next;
  92890. if (prev !== null) prev.next = next;
  92891. if (next !== null) next.prev = prev;
  92892. if (this.rigidBodies == remove) this.rigidBodies = next;
  92893. remove.prev = null;
  92894. remove.next = null;
  92895. remove.parent = null;
  92896. this.numRigidBodies--;
  92897. },
  92898. getByName: function (name) {
  92899. var result = null;
  92900. var body = this.rigidBodies;
  92901. while (body !== null) {
  92902. if (body.name !== " " && body.name === name) result = body;
  92903. body = body.next;
  92904. }
  92905. var joint = this.joints;
  92906. while (joint !== null) {
  92907. if (joint.name !== "" && joint.name === name) result = joint;
  92908. joint = joint.next;
  92909. }
  92910. return result;
  92911. },
  92912. /**
  92913. * I'll add a shape to the world..
  92914. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92915. * Shape will be added to the world automatically, please do not call from outside this method.
  92916. * @param shape Shape you want to add
  92917. */
  92918. addShape: function (shape) {
  92919. if (!shape.parent || !shape.parent.parent) {
  92920. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92921. }
  92922. shape.proxy = this.broadPhase.createProxy(shape);
  92923. shape.updateProxy();
  92924. this.broadPhase.addProxy(shape.proxy);
  92925. },
  92926. /**
  92927. * I will remove the shape from the world.
  92928. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92929. * Shape will be added to the world automatically, please do not call from outside this method.
  92930. * @param shape Shape you want to delete
  92931. */
  92932. removeShape: function (shape) {
  92933. this.broadPhase.removeProxy(shape.proxy);
  92934. shape.proxy = null;
  92935. },
  92936. /**
  92937. * I'll add a joint to the world.
  92938. * Joint that has been added will be the operands of each step.
  92939. * @param shape Joint to be added
  92940. */
  92941. addJoint: function (joint) {
  92942. if (joint.parent) {
  92943. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92944. }
  92945. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  92946. this.joints = joint;
  92947. joint.parent = this;
  92948. this.numJoints++;
  92949. joint.awake();
  92950. joint.attach();
  92951. },
  92952. /**
  92953. * I will remove the joint from the world.
  92954. * Joint that has been added will be the operands of each step.
  92955. * @param shape Joint to be deleted
  92956. */
  92957. removeJoint: function (joint) {
  92958. var remove = joint;
  92959. var prev = remove.prev;
  92960. var next = remove.next;
  92961. if (prev !== null) prev.next = next;
  92962. if (next !== null) next.prev = prev;
  92963. if (this.joints == remove) this.joints = next;
  92964. remove.prev = null;
  92965. remove.next = null;
  92966. this.numJoints--;
  92967. remove.awake();
  92968. remove.detach();
  92969. remove.parent = null;
  92970. },
  92971. worldscale: function (scale) {
  92972. OIMO.WORLD_SCALE = scale || 100;
  92973. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  92974. },
  92975. addContact: function (s1, s2) {
  92976. var newContact;
  92977. if (this.unusedContacts !== null) {
  92978. newContact = this.unusedContacts;
  92979. this.unusedContacts = this.unusedContacts.next;
  92980. } else {
  92981. newContact = new OIMO.Contact();
  92982. }
  92983. newContact.attach(s1, s2);
  92984. newContact.detector = this.detectors[s1.type][s2.type];
  92985. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  92986. this.contacts = newContact;
  92987. this.numContacts++;
  92988. },
  92989. removeContact: function (contact) {
  92990. var prev = contact.prev;
  92991. var next = contact.next;
  92992. if (next) next.prev = prev;
  92993. if (prev) prev.next = next;
  92994. if (this.contacts == contact) this.contacts = next;
  92995. contact.prev = null;
  92996. contact.next = null;
  92997. contact.detach();
  92998. contact.next = this.unusedContacts;
  92999. this.unusedContacts = contact;
  93000. this.numContacts--;
  93001. },
  93002. checkContact: function (name1, name2) {
  93003. var n1, n2;
  93004. var contact = this.contacts;
  93005. while (contact !== null) {
  93006. n1 = contact.body1.name || ' ';
  93007. n2 = contact.body2.name || ' ';
  93008. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  93009. else contact = contact.next;
  93010. }
  93011. return false;
  93012. },
  93013. callSleep: function (body) {
  93014. if (!body.allowSleep) return false;
  93015. if (body.linearVelocity.lengthSq() > 0.04) return false;
  93016. if (body.angularVelocity.lengthSq() > 0.25) return false;
  93017. return true;
  93018. },
  93019. /**
  93020. * I will proceed only time step seconds time of World.
  93021. */
  93022. step: function () {
  93023. var time0, time1, time2, time3;
  93024. var stat = !this.isNoStat ? true : false;
  93025. if (stat) time0 = OIMO.now();
  93026. var body = this.rigidBodies;
  93027. while (body !== null) {
  93028. body.addedToIsland = false;
  93029. if (body.sleeping) {
  93030. if (
  93031. body.linearVelocity.testZero() ||
  93032. body.angularVelocity.testZero() ||
  93033. body.position.testDiff(body.sleepPosition) ||
  93034. body.orientation.testDiff(body.sleepOrientation)
  93035. ) body.awake(); // awake the body
  93036. }
  93037. body = body.next;
  93038. }
  93039. //------------------------------------------------------
  93040. // UPDATE CONTACT
  93041. //------------------------------------------------------
  93042. // broad phase
  93043. if (stat) time1 = OIMO.now();
  93044. this.broadPhase.detectPairs();
  93045. var pairs = this.broadPhase.pairs;
  93046. var i = this.broadPhase.numPairs;
  93047. //do{
  93048. while (i--) {
  93049. //for(var i=0, l=numPairs; i<l; i++){
  93050. var pair = pairs[i];
  93051. var s1;
  93052. var s2;
  93053. if (pair.shape1.id < pair.shape2.id) {
  93054. s1 = pair.shape1;
  93055. s2 = pair.shape2;
  93056. } else {
  93057. s1 = pair.shape2;
  93058. s2 = pair.shape1;
  93059. }
  93060. var link;
  93061. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  93062. else link = s2.contactLink;
  93063. var exists = false;
  93064. while (link) {
  93065. var contact = link.contact;
  93066. if (contact.shape1 == s1 && contact.shape2 == s2) {
  93067. contact.persisting = true;
  93068. exists = true;// contact already exists
  93069. break;
  93070. }
  93071. link = link.next;
  93072. }
  93073. if (!exists) {
  93074. this.addContact(s1, s2);
  93075. }
  93076. }// while(i-- >0);
  93077. if (stat) {
  93078. time2 = OIMO.now();
  93079. this.performance.broadPhaseTime = time2 - time1;
  93080. }
  93081. // update & narrow phase
  93082. this.numContactPoints = 0;
  93083. contact = this.contacts;
  93084. while (contact !== null) {
  93085. if (!contact.persisting) {
  93086. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93087. /*var aabb1=contact.shape1.aabb;
  93088. var aabb2=contact.shape2.aabb;
  93089. if(
  93090. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93091. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93092. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93093. ){*/
  93094. var next = contact.next;
  93095. this.removeContact(contact);
  93096. contact = next;
  93097. continue;
  93098. }
  93099. }
  93100. var b1 = contact.body1;
  93101. var b2 = contact.body2;
  93102. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93103. contact.updateManifold();
  93104. }
  93105. this.numContactPoints += contact.manifold.numPoints;
  93106. contact.persisting = false;
  93107. contact.constraint.addedToIsland = false;
  93108. contact = contact.next;
  93109. }
  93110. if (stat) {
  93111. time3 = OIMO.now();
  93112. this.performance.narrowPhaseTime = time3 - time2;
  93113. }
  93114. //------------------------------------------------------
  93115. // SOLVE ISLANDS
  93116. //------------------------------------------------------
  93117. var invTimeStep = 1 / this.timeStep;
  93118. //var body;
  93119. var joint;
  93120. var constraint;
  93121. //var num;
  93122. for (joint = this.joints; joint !== null; joint = joint.next) {
  93123. joint.addedToIsland = false;
  93124. }
  93125. // clear old island array
  93126. this.islandRigidBodies = [];
  93127. this.islandConstraints = [];
  93128. this.islandStack = [];
  93129. // expand island buffers
  93130. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93131. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93132. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93133. this.islandRigidBodies=[];
  93134. this.islandStack=[];
  93135. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93136. this.islandStack.length = this.maxIslandRigidBodies;
  93137. }
  93138. var numConstraints=this.numJoints+this.numContacts;
  93139. if(this.maxIslandConstraints<numConstraints){
  93140. this.maxIslandConstraints=numConstraints<<1;
  93141. //this.maxIslandConstraints=numConstraints*2;
  93142. this.islandConstraints=[];
  93143. this.islandConstraints.length = this.maxIslandConstraints;
  93144. }*/
  93145. time1 = OIMO.now();
  93146. this.numIslands = 0;
  93147. // build and solve simulation islands
  93148. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93149. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93150. if (base.isLonely()) {// update single body
  93151. if (base.isDynamic) {
  93152. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93153. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93154. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93155. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93156. }
  93157. if (this.callSleep(base)) {
  93158. base.sleepTime += this.timeStep;
  93159. if (base.sleepTime > 0.5) base.sleep();
  93160. else base.updatePosition(this.timeStep);
  93161. } else {
  93162. base.sleepTime = 0;
  93163. base.updatePosition(this.timeStep);
  93164. }
  93165. this.numIslands++;
  93166. continue;
  93167. }
  93168. var islandNumRigidBodies = 0;
  93169. var islandNumConstraints = 0;
  93170. var stackCount = 1;
  93171. // add rigid body to stack
  93172. this.islandStack[0] = base;
  93173. base.addedToIsland = true;
  93174. // build an island
  93175. do {
  93176. // get rigid body from stack
  93177. body = this.islandStack[--stackCount];
  93178. this.islandStack[stackCount] = null;
  93179. body.sleeping = false;
  93180. // add rigid body to the island
  93181. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93182. if (body.isStatic) continue;
  93183. // search connections
  93184. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93185. var contact = cs.contact;
  93186. constraint = contact.constraint;
  93187. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93188. // add constraint to the island
  93189. this.islandConstraints[islandNumConstraints++] = constraint;
  93190. constraint.addedToIsland = true;
  93191. var next = cs.body;
  93192. if (next.addedToIsland) continue;
  93193. // add rigid body to stack
  93194. this.islandStack[stackCount++] = next;
  93195. next.addedToIsland = true;
  93196. }
  93197. for (var js = body.jointLink; js !== null; js = js.next) {
  93198. constraint = js.joint;
  93199. if (constraint.addedToIsland) continue;// ignore
  93200. // add constraint to the island
  93201. this.islandConstraints[islandNumConstraints++] = constraint;
  93202. constraint.addedToIsland = true;
  93203. next = js.body;
  93204. if (next.addedToIsland || !next.isDynamic) continue;
  93205. // add rigid body to stack
  93206. this.islandStack[stackCount++] = next;
  93207. next.addedToIsland = true;
  93208. }
  93209. } while (stackCount != 0);
  93210. // update velocities
  93211. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93212. /*var gx=this.gravity.x*this.timeStep;
  93213. var gy=this.gravity.y*this.timeStep;
  93214. var gz=this.gravity.z*this.timeStep;*/
  93215. var j = islandNumRigidBodies;
  93216. while (j--) {
  93217. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93218. body = this.islandRigidBodies[j];
  93219. if (body.isDynamic) {
  93220. body.linearVelocity.addEqual(gVel);
  93221. /*body.linearVelocity.x+=gx;
  93222. body.linearVelocity.y+=gy;
  93223. body.linearVelocity.z+=gz;*/
  93224. }
  93225. }
  93226. // randomizing order
  93227. if (this.enableRandomizer) {
  93228. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93229. j = islandNumConstraints;
  93230. while (j--) {
  93231. if (j !== 0) {
  93232. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93233. constraint = this.islandConstraints[j];
  93234. this.islandConstraints[j] = this.islandConstraints[swap];
  93235. this.islandConstraints[swap] = constraint;
  93236. }
  93237. }
  93238. }
  93239. // solve contraints
  93240. j = islandNumConstraints;
  93241. while (j--) {
  93242. //for(j=0, l=islandNumConstraints; j<l; j++){
  93243. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93244. }
  93245. var k = this.numIterations;
  93246. while (k--) {
  93247. //for(var k=0, l=this.numIterations; k<l; k++){
  93248. j = islandNumConstraints;
  93249. while (j--) {
  93250. //for(j=0, m=islandNumConstraints; j<m; j++){
  93251. this.islandConstraints[j].solve();// main-solve
  93252. }
  93253. }
  93254. j = islandNumConstraints;
  93255. while (j--) {
  93256. //for(j=0, l=islandNumConstraints; j<l; j++){
  93257. this.islandConstraints[j].postSolve();// post-solve
  93258. this.islandConstraints[j] = null;// gc
  93259. }
  93260. // sleeping check
  93261. var sleepTime = 10;
  93262. j = islandNumRigidBodies;
  93263. while (j--) {
  93264. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93265. body = this.islandRigidBodies[j];
  93266. if (this.callSleep(body)) {
  93267. body.sleepTime += this.timeStep;
  93268. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93269. } else {
  93270. body.sleepTime = 0;
  93271. sleepTime = 0;
  93272. continue;
  93273. }
  93274. }
  93275. if (sleepTime > 0.5) {
  93276. // sleep the island
  93277. j = islandNumRigidBodies;
  93278. while (j--) {
  93279. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93280. this.islandRigidBodies[j].sleep();
  93281. this.islandRigidBodies[j] = null;// gc
  93282. }
  93283. } else {
  93284. // update positions
  93285. j = islandNumRigidBodies;
  93286. while (j--) {
  93287. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93288. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93289. this.islandRigidBodies[j] = null;// gc
  93290. }
  93291. }
  93292. this.numIslands++;
  93293. }
  93294. if (stat) {
  93295. time2 = OIMO.now();
  93296. this.performance.solvingTime = time2 - time1;
  93297. //------------------------------------------------------
  93298. // END SIMULATION
  93299. //------------------------------------------------------
  93300. time2 = OIMO.now();
  93301. // fps update
  93302. this.performance.upfps();
  93303. this.performance.totalTime = time2 - time0;
  93304. }
  93305. }
  93306. }
  93307. /**
  93308. * The class of rigid body.
  93309. * Rigid body has the shape of a single or multiple collision processing,
  93310. * I can set the parameters individually.
  93311. * @author saharan
  93312. */
  93313. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93314. this.name = " ";
  93315. // The maximum number of shapes that can be added to a one rigid.
  93316. this.MAX_SHAPES = 64;//64;
  93317. this.prev = null;
  93318. this.next = null;
  93319. // I represent the kind of rigid body.
  93320. // Please do not change from the outside this variable.
  93321. // If you want to change the type of rigid body, always
  93322. // Please specify the type you want to set the arguments of setupMass method.
  93323. this.type = OIMO.BODY_NULL;
  93324. this.massInfo = new OIMO.MassInfo();
  93325. // It is the world coordinate of the center of gravity.
  93326. this.position = new OIMO.Vec3(x, y, z);
  93327. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93328. this.newPosition = new OIMO.Vec3();
  93329. this.controlPos = false;
  93330. this.newOrientation = new OIMO.Quat();
  93331. this.newRotation = new OIMO.Vec3();
  93332. this.currentRotation = new OIMO.Vec3();
  93333. this.controlRot = false;
  93334. this.controlRotInTime = false;
  93335. // Is the translational velocity.
  93336. this.linearVelocity = new OIMO.Vec3();
  93337. // Is the angular velocity.
  93338. this.angularVelocity = new OIMO.Vec3();
  93339. // return matrix for three.js
  93340. this.matrix = new OIMO.Mat44();
  93341. //--------------------------------------------
  93342. // Please do not change from the outside this variables.
  93343. //--------------------------------------------
  93344. // It is a world that rigid body has been added.
  93345. this.parent = null;
  93346. this.contactLink = null;
  93347. this.numContacts = 0;
  93348. // An array of shapes that are included in the rigid body.
  93349. this.shapes = null;
  93350. // The number of shapes that are included in the rigid body.
  93351. this.numShapes = 0;
  93352. // It is the link array of joint that is connected to the rigid body.
  93353. this.jointLink = null;
  93354. // The number of joints that are connected to the rigid body.
  93355. this.numJoints = 0;
  93356. // It is the world coordinate of the center of gravity in the sleep just before.
  93357. this.sleepPosition = new OIMO.Vec3();
  93358. // It is a quaternion that represents the attitude of sleep just before.
  93359. this.sleepOrientation = new OIMO.Quat();
  93360. // I will show this rigid body to determine whether it is a rigid body static.
  93361. this.isStatic = false;
  93362. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93363. this.isDynamic = false;
  93364. // It is a rotation matrix representing the orientation.
  93365. this.rotation = new OIMO.Mat33();
  93366. //--------------------------------------------
  93367. // It will be recalculated automatically from the shape, which is included.
  93368. //--------------------------------------------
  93369. // This is the weight.
  93370. this.mass = NaN;
  93371. // It is the reciprocal of the mass.
  93372. this.inverseMass = NaN;
  93373. // It is the inverse of the inertia tensor in the world system.
  93374. this.inverseInertia = new OIMO.Mat33();
  93375. // It is the inertia tensor in the initial state.
  93376. this.localInertia = new OIMO.Mat33();
  93377. // It is the inverse of the inertia tensor in the initial state.
  93378. this.inverseLocalInertia = new OIMO.Mat33();
  93379. // I indicates rigid body whether it has been added to the simulation Island.
  93380. this.addedToIsland = false;
  93381. // It shows how to sleep rigid body.
  93382. this.allowSleep = true;
  93383. // This is the time from when the rigid body at rest.
  93384. this.sleepTime = 0;
  93385. // I shows rigid body to determine whether it is a sleep state.
  93386. this.sleeping = false;
  93387. };
  93388. OIMO.RigidBody.prototype = {
  93389. constructor: OIMO.RigidBody,
  93390. /**
  93391. * I'll add a shape to rigid body.
  93392. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93393. * @param shape shape to Add
  93394. */
  93395. addShape: function (shape) {
  93396. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93397. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93398. this.shapes = shape;
  93399. shape.parent = this;
  93400. if (this.parent) this.parent.addShape(shape);
  93401. this.numShapes++;
  93402. },
  93403. /**
  93404. * I will delete the shape from the rigid body.
  93405. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93406. * @param shape shape to Delete
  93407. */
  93408. removeShape: function (shape) {
  93409. var remove = shape;
  93410. if (remove.parent != this) return;
  93411. var prev = remove.prev;
  93412. var next = remove.next;
  93413. if (prev != null) prev.next = next;
  93414. if (next != null) next.prev = prev;
  93415. if (this.shapes == remove) this.shapes = next;
  93416. remove.prev = null;
  93417. remove.next = null;
  93418. remove.parent = null;
  93419. if (this.parent) this.parent.removeShape(remove);
  93420. this.numShapes--;
  93421. },
  93422. remove: function () {
  93423. this.dispose();
  93424. },
  93425. dispose: function () {
  93426. this.parent.removeRigidBody(this);
  93427. },
  93428. checkContact: function (name) {
  93429. this.parent.checkContact(this.name, name);
  93430. },
  93431. /**
  93432. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93433. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93434. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93435. * the rigid body's position will be adjusted to the center of gravity.
  93436. * @param type
  93437. * @param adjustPosition
  93438. */
  93439. setupMass: function (type, AdjustPosition) {
  93440. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93441. this.type = type || OIMO.BODY_DYNAMIC;
  93442. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93443. this.isStatic = this.type == OIMO.BODY_STATIC;
  93444. this.mass = 0;
  93445. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93446. var te = this.localInertia.elements;
  93447. //
  93448. var tmpM = new OIMO.Mat33();
  93449. var tmpV = new OIMO.Vec3();
  93450. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93451. shape.calculateMassInfo(this.massInfo);
  93452. var shapeMass = this.massInfo.mass;
  93453. var relX = shape.relativePosition.x;
  93454. var relY = shape.relativePosition.y;
  93455. var relZ = shape.relativePosition.z;
  93456. /*tmpV.x+=relX*shapeMass;
  93457. tmpV.y+=relY*shapeMass;
  93458. tmpV.z+=relZ*shapeMass;*/
  93459. tmpV.addScale(shape.relativePosition, shapeMass);
  93460. this.mass += shapeMass;
  93461. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93462. this.localInertia.addEqual(tmpM);
  93463. // add offset inertia
  93464. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93465. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93466. te[8] += shapeMass * (relX * relX + relY * relY);
  93467. var xy = shapeMass * relX * relY;
  93468. var yz = shapeMass * relY * relZ;
  93469. var zx = shapeMass * relZ * relX;
  93470. te[1] -= xy;
  93471. te[3] -= xy;
  93472. te[2] -= yz;
  93473. te[6] -= yz;
  93474. te[5] -= zx;
  93475. te[7] -= zx;
  93476. }
  93477. this.inverseMass = 1 / this.mass;
  93478. tmpV.scaleEqual(this.inverseMass);
  93479. if (adjustPosition) {
  93480. this.position.addEqual(tmpV);
  93481. for (shape = this.shapes; shape != null; shape = shape.next) {
  93482. shape.relativePosition.subEqual(tmpV);
  93483. }
  93484. // subtract offset inertia
  93485. relX = tmpV.x;
  93486. relY = tmpV.y;
  93487. relZ = tmpV.z;
  93488. //var te = this.localInertia.elements;
  93489. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93490. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93491. te[8] -= this.mass * (relX * relX + relY * relY);
  93492. xy = this.mass * relX * relY;
  93493. yz = this.mass * relY * relZ;
  93494. zx = this.mass * relZ * relX;
  93495. te[1] += xy;
  93496. te[3] += xy;
  93497. te[2] += yz;
  93498. te[6] += yz;
  93499. te[5] += zx;
  93500. te[7] += zx;
  93501. }
  93502. this.inverseLocalInertia.invert(this.localInertia);
  93503. if (this.type == OIMO.BODY_STATIC) {
  93504. this.inverseMass = 0;
  93505. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93506. }
  93507. this.syncShapes();
  93508. this.awake();
  93509. },
  93510. /**
  93511. * Awake the rigid body.
  93512. */
  93513. awake: function () {
  93514. if (!this.allowSleep || !this.sleeping) return;
  93515. this.sleeping = false;
  93516. this.sleepTime = 0;
  93517. // awake connected constraints
  93518. var cs = this.contactLink;
  93519. while (cs != null) {
  93520. cs.body.sleepTime = 0;
  93521. cs.body.sleeping = false;
  93522. cs = cs.next;
  93523. }
  93524. var js = this.jointLink;
  93525. while (js != null) {
  93526. js.body.sleepTime = 0;
  93527. js.body.sleeping = false;
  93528. js = js.next;
  93529. }
  93530. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93531. shape.updateProxy();
  93532. }
  93533. },
  93534. /**
  93535. * Sleep the rigid body.
  93536. */
  93537. sleep: function () {
  93538. if (!this.allowSleep || this.sleeping) return;
  93539. this.linearVelocity.set(0, 0, 0);
  93540. this.angularVelocity.set(0, 0, 0);
  93541. this.sleepPosition.copy(this.position);
  93542. this.sleepOrientation.copy(this.orientation);
  93543. /*this.linearVelocity.x=0;
  93544. this.linearVelocity.y=0;
  93545. this.linearVelocity.z=0;
  93546. this.angularVelocity.x=0;
  93547. this.angularVelocity.y=0;
  93548. this.angularVelocity.z=0;
  93549. this.sleepPosition.x=this.position.x;
  93550. this.sleepPosition.y=this.position.y;
  93551. this.sleepPosition.z=this.position.z;*/
  93552. /*this.sleepOrientation.s=this.orientation.s;
  93553. this.sleepOrientation.x=this.orientation.x;
  93554. this.sleepOrientation.y=this.orientation.y;
  93555. this.sleepOrientation.z=this.orientation.z;*/
  93556. this.sleepTime = 0;
  93557. this.sleeping = true;
  93558. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93559. shape.updateProxy();
  93560. }
  93561. },
  93562. /**
  93563. * Get whether the rigid body has not any connection with others.
  93564. * @return
  93565. */
  93566. isLonely: function () {
  93567. return this.numJoints == 0 && this.numContacts == 0;
  93568. },
  93569. /**
  93570. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93571. * This method is invoked automatically when calling the step of the World,
  93572. * There is no need to call from outside usually.
  93573. * @param timeStep time
  93574. */
  93575. updatePosition: function (timeStep) {
  93576. switch (this.type) {
  93577. case OIMO.BODY_STATIC:
  93578. this.linearVelocity.set(0, 0, 0);
  93579. this.angularVelocity.set(0, 0, 0);
  93580. // ONLY FOR TEST
  93581. if (this.controlPos) {
  93582. this.position.copy(this.newPosition);
  93583. this.controlPos = false;
  93584. }
  93585. if (this.controlRot) {
  93586. this.orientation.copy(this.newOrientation);
  93587. this.controlRot = false;
  93588. }
  93589. /*this.linearVelocity.x=0;
  93590. this.linearVelocity.y=0;
  93591. this.linearVelocity.z=0;
  93592. this.angularVelocity.x=0;
  93593. this.angularVelocity.y=0;
  93594. this.angularVelocity.z=0;*/
  93595. break;
  93596. case OIMO.BODY_DYNAMIC:
  93597. if (this.controlPos) {
  93598. this.angularVelocity.set(0, 0, 0);
  93599. this.linearVelocity.set(0, 0, 0);
  93600. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93601. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93602. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93603. this.controlPos = false;
  93604. }
  93605. if (this.controlRot) {
  93606. this.angularVelocity.set(0, 0, 0);
  93607. this.orientation.copy(this.newOrientation);
  93608. //var t=timeStep//*0.5;
  93609. //var q = new OIMO.Quat();
  93610. //q.sub(this.newOrientation, this.orientation);
  93611. //q.normalize(q);
  93612. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93613. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93614. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93615. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93616. //this.angularVelocity.applyQuaternion(q);
  93617. //this.angularVelocity.x = this.angularVelocity.x/t;
  93618. //this.angularVelocity.y = this.angularVelocity.y/t;
  93619. //this.angularVelocity.z = this.angularVelocity.z/t;
  93620. this.controlRot = false;
  93621. }
  93622. this.position.addTime(this.linearVelocity, timeStep);
  93623. this.orientation.addTime(this.angularVelocity, timeStep);
  93624. break;
  93625. default: OIMO.Error("RigidBody", "Invalid type.");
  93626. }
  93627. this.syncShapes();
  93628. },
  93629. rotateInertia: function (rot, inertia, out) {
  93630. var tm1 = rot.elements;
  93631. var tm2 = inertia.elements;
  93632. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93633. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93634. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93635. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93636. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93637. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93638. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93639. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93640. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93641. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93642. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93643. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93644. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93645. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93646. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93647. var oe = out.elements;
  93648. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93649. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93650. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93651. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93652. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93653. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93654. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93655. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93656. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93657. },
  93658. syncShapes: function () {
  93659. var s = this.orientation.s;
  93660. var x = this.orientation.x;
  93661. var y = this.orientation.y;
  93662. var z = this.orientation.z;
  93663. var x2 = 2 * x;
  93664. var y2 = 2 * y;
  93665. var z2 = 2 * z;
  93666. var xx = x * x2;
  93667. var yy = y * y2;
  93668. var zz = z * z2;
  93669. var xy = x * y2;
  93670. var yz = y * z2;
  93671. var xz = x * z2;
  93672. var sx = s * x2;
  93673. var sy = s * y2;
  93674. var sz = s * z2;
  93675. var tr = this.rotation.elements;
  93676. tr[0] = 1 - yy - zz;
  93677. tr[1] = xy - sz;
  93678. tr[2] = xz + sy;
  93679. tr[3] = xy + sz;
  93680. tr[4] = 1 - xx - zz;
  93681. tr[5] = yz - sx;
  93682. tr[6] = xz - sy;
  93683. tr[7] = yz + sx;
  93684. tr[8] = 1 - xx - yy;
  93685. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93686. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93687. //var relPos=shape.relativePosition;
  93688. //var relRot=shape.relativeRotation;
  93689. //var rot=shape.rotation;
  93690. /*var lx=relPos.x;
  93691. var ly=relPos.y;
  93692. var lz=relPos.z;
  93693. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93694. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93695. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93696. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93697. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93698. // add by QuaziKb
  93699. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93700. shape.updateProxy();
  93701. }
  93702. },
  93703. applyImpulse: function (position, force) {
  93704. this.linearVelocity.addScale(force, this.inverseMass);
  93705. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93706. this.linearVelocity.y+=force.y*this.inverseMass;
  93707. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93708. var rel = new OIMO.Vec3();
  93709. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93710. this.angularVelocity.addEqual(rel);
  93711. /*this.angularVelocity.x+=rel.x;
  93712. this.angularVelocity.y+=rel.y;
  93713. this.angularVelocity.z+=rel.z;*/
  93714. },
  93715. //---------------------------------------------
  93716. //
  93717. // FOR THREE JS
  93718. //
  93719. //---------------------------------------------
  93720. rotationVectToQuad: function (rot) {
  93721. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93722. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93723. },
  93724. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93725. var len = ax * ax + ay * ay + az * az;
  93726. if (len > 0) {
  93727. len = 1 / OIMO.sqrt(len);
  93728. ax *= len;
  93729. ay *= len;
  93730. az *= len;
  93731. }
  93732. var sin = OIMO.sin(rad * 0.5);
  93733. var cos = OIMO.cos(rad * 0.5);
  93734. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93735. },
  93736. //---------------------------------------------
  93737. // SET DYNAMIQUE POSITION AND ROTATION
  93738. //---------------------------------------------
  93739. setPosition: function (pos) {
  93740. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93741. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93742. this.controlPos = true;
  93743. },
  93744. setQuaternion: function (q) {
  93745. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93746. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93747. this.controlRot = true;
  93748. },
  93749. setRotation: function (rot) {
  93750. this.newOrientation = this.rotationVectToQuad(rot);
  93751. this.controlRot = true;
  93752. },
  93753. //---------------------------------------------
  93754. // RESET DYNAMIQUE POSITION AND ROTATION
  93755. //---------------------------------------------
  93756. resetPosition: function (x, y, z) {
  93757. this.linearVelocity.set(0, 0, 0);
  93758. this.angularVelocity.set(0, 0, 0);
  93759. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93760. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93761. this.awake();
  93762. },
  93763. resetQuaternion: function (q) {
  93764. this.angularVelocity.set(0, 0, 0);
  93765. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93766. this.awake();
  93767. },
  93768. resetRotation: function (x, y, z) {
  93769. this.angularVelocity.set(0, 0, 0);
  93770. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93771. this.awake();
  93772. },
  93773. //---------------------------------------------
  93774. // GET POSITION AND ROTATION
  93775. //---------------------------------------------
  93776. getPosition: function () {
  93777. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93778. },
  93779. getRotation: function () {
  93780. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93781. },
  93782. getQuaternion: function () {
  93783. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93784. },
  93785. getMatrix: function () {
  93786. var m = this.matrix.elements;
  93787. var r, p;
  93788. if (!this.sleeping) {
  93789. // rotation matrix
  93790. r = this.rotation.elements;
  93791. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93792. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93793. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93794. // position matrix
  93795. p = this.position;
  93796. m[12] = p.x * OIMO.WORLD_SCALE;
  93797. m[13] = p.y * OIMO.WORLD_SCALE;
  93798. m[14] = p.z * OIMO.WORLD_SCALE;
  93799. // sleep or not ?
  93800. m[15] = 0;
  93801. } else {
  93802. m[15] = 1;
  93803. }
  93804. return m;
  93805. }
  93806. };
  93807. /**
  93808. * The main class of body.
  93809. * is for simplify creation process and data access of rigidRody
  93810. * Rigid body has the shape of a single or multiple collision processing,
  93811. * all setting in object
  93812. *
  93813. * @author loth
  93814. */
  93815. OIMO.Body = function (Obj) {
  93816. var obj = Obj || {};
  93817. if (!obj.world) return;
  93818. if (obj.type === undefined) obj.type = "box";
  93819. this.name = obj.name || '';
  93820. // obsolete use world.add(obj)
  93821. this.body = obj.world.add(obj);
  93822. /*
  93823. // the world where i am
  93824. this.parent = obj.world;
  93825. // Yep my name
  93826. this.name = obj.name || '';
  93827. // I'm dynamique or not
  93828. var move = obj.move || false;
  93829. // I can sleep or not
  93830. var noSleep = obj.noSleep || false;
  93831. // My start position
  93832. var p = obj.pos || [0,0,0];
  93833. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93834. // My size
  93835. var s = obj.size || [1,1,1];
  93836. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93837. // My rotation in degre
  93838. var rot = obj.rot || [0,0,0];
  93839. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93840. var r = [];
  93841. for (var i=0; i<rot.length/3; i++){
  93842. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93843. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93844. }
  93845. // My physics setting
  93846. var sc = obj.sc || new OIMO.ShapeConfig();
  93847. if(obj.config){
  93848. // The density of the shape.
  93849. sc.density = obj.config[0] || 1;
  93850. // The coefficient of friction of the shape.
  93851. sc.friction = obj.config[1] || 0.4;
  93852. // The coefficient of restitution of the shape.
  93853. sc.restitution = obj.config[2] || 0.2;
  93854. // The bits of the collision groups to which the shape belongs.
  93855. sc.belongsTo = obj.config[3] || 1;
  93856. // The bits of the collision groups with which the shape collides.
  93857. sc.collidesWith = obj.config[4] || 0xffffffff;
  93858. }
  93859. if(obj.massPos){
  93860. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93861. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93862. }
  93863. if(obj.massRot){
  93864. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93865. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93866. }
  93867. // My rigidbody
  93868. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93869. // My shapes
  93870. var shapes = [];
  93871. var type = obj.type || "box";
  93872. if( typeof type === 'string' ) type = [type];// single shape
  93873. var n, n2;
  93874. for(var i=0; i<type.length; i++){
  93875. n = i*3;
  93876. n2 = i*4;
  93877. switch(type[i]){
  93878. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93879. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93880. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93881. }
  93882. this.body.addShape(shapes[i]);
  93883. if(i>0){
  93884. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93885. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93886. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93887. }
  93888. }
  93889. // I'm static or i move
  93890. if(move){
  93891. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93892. else this.body.setupMass(0x1, true);
  93893. if(noSleep) this.body.allowSleep = false;
  93894. else this.body.allowSleep = true;
  93895. } else {
  93896. this.body.setupMass(0x2);
  93897. }
  93898. this.body.name = this.name;
  93899. this.sleeping = this.body.sleeping;
  93900. // finaly add to physics world
  93901. this.parent.addRigidBody(this.body);*/
  93902. }
  93903. OIMO.Body.prototype = {
  93904. constructor: OIMO.Body,
  93905. // SET
  93906. setPosition: function (pos) {
  93907. this.body.setPosition(pos);
  93908. },
  93909. setQuaternion: function (q) {
  93910. this.body.setQuaternion(q);
  93911. },
  93912. setRotation: function (rot) {
  93913. this.body.setRotation(rot);
  93914. },
  93915. // GET
  93916. getPosition: function () {
  93917. return this.body.getPosition();
  93918. },
  93919. getRotation: function () {
  93920. return this.body.getRotation();
  93921. },
  93922. getQuaternion: function () {
  93923. return this.body.getQuaternion();
  93924. },
  93925. getMatrix: function () {
  93926. return this.body.getMatrix();
  93927. },
  93928. getSleep: function () {
  93929. return this.body.sleeping;
  93930. },
  93931. // RESET
  93932. resetPosition: function (x, y, z) {
  93933. this.body.resetPosition(x, y, z);
  93934. },
  93935. resetRotation: function (x, y, z) {
  93936. this.body.resetRotation(x, y, z);
  93937. },
  93938. // force wakeup
  93939. awake: function () {
  93940. this.body.awake();
  93941. },
  93942. // remove rigidbody
  93943. remove: function () {
  93944. this.body.dispose();
  93945. //this.parent.removeRigidBody(this.body);
  93946. },
  93947. // test if this object hit another
  93948. checkContact: function (name) {
  93949. this.body.checkContact(name);
  93950. //this.parent.checkContact(this.name, name);
  93951. }
  93952. }
  93953. /**
  93954. * The main class of link.
  93955. * is for simplify creation process and data access of Joint
  93956. * all setting in object
  93957. *
  93958. * @author loth
  93959. */
  93960. OIMO.Link = function (Obj) {
  93961. var obj = Obj || {};
  93962. if (!obj.world) return;
  93963. if (obj.type === undefined) obj.type = "jointHinge";
  93964. this.name = obj.name || '';
  93965. // obsolete use world.add(obj)
  93966. this.joint = obj.world.add(obj);
  93967. // the world where i am
  93968. /*this.parent = obj.world;
  93969. this.name = obj.name || '';
  93970. var type = obj.type || "jointHinge";
  93971. var axe1 = obj.axe1 || [1,0,0];
  93972. var axe2 = obj.axe2 || [1,0,0];
  93973. var pos1 = obj.pos1 || [0,0,0];
  93974. var pos2 = obj.pos2 || [0,0,0];
  93975. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  93976. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  93977. var min, max;
  93978. if(type==="jointDistance"){
  93979. min = obj.min || 0;
  93980. max = obj.max || 10;
  93981. min = min*OIMO.INV_SCALE;
  93982. max = max*OIMO.INV_SCALE;
  93983. }else{
  93984. min = obj.min || 57.29578;
  93985. max = obj.max || 0;
  93986. min = min*OIMO.TO_RAD;
  93987. max = max*OIMO.TO_RAD;
  93988. }
  93989. var limit = obj.limit || null;
  93990. var spring = obj.spring || null;
  93991. var motor = obj.motor || null;
  93992. // joint setting
  93993. var jc = new OIMO.JointConfig();
  93994. jc.allowCollision = obj.collision || false;;
  93995. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  93996. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  93997. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  93998. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  93999. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  94000. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  94001. jc.body1 = obj.body1;
  94002. jc.body2 = obj.body2;
  94003. switch(type){
  94004. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  94005. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  94006. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94007. break;
  94008. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  94009. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  94010. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94011. break;
  94012. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  94013. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  94014. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  94015. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  94016. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  94017. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  94018. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  94019. break;
  94020. }
  94021. this.joint.name = this.name;
  94022. // finaly add to physics world
  94023. this.parent.addJoint(this.joint);*/
  94024. }
  94025. OIMO.Link.prototype = {
  94026. constructor: OIMO.Link,
  94027. getPosition: function () {
  94028. // array of two vect3 [point1, point2]
  94029. return this.joint.getPosition();
  94030. },
  94031. getMatrix: function () {
  94032. return this.joint.getMatrix();
  94033. },
  94034. // remove joint
  94035. remove: function () {
  94036. this.joint.dispose();
  94037. //this.parent.removeJoint(this.joint);
  94038. },
  94039. // force wakeup linked body
  94040. awake: function () {
  94041. this.joint.awake();
  94042. }
  94043. }
  94044. /**
  94045. * The Dictionary class for testing
  94046. * @author lo-th
  94047. */
  94048. OIMO.Dictionary = function () {
  94049. this.data = {};
  94050. this.keys = [];
  94051. };
  94052. OIMO.Dictionary.prototype = {
  94053. constructor: OIMO.Dictionary,
  94054. set: function (value) {
  94055. var key = value.id;
  94056. if (!this.get[key]) this.keys.push(key);
  94057. this.data[key] = value;
  94058. },
  94059. get: function (id) {
  94060. return this.data[id];
  94061. },
  94062. del: function (value) {
  94063. var k = this.keys;
  94064. var n = k.indexOf(value.id);
  94065. if (n > -1) {
  94066. delete this.data[k[n]];
  94067. k.splice(n, 1);
  94068. }
  94069. },
  94070. reset: function () {
  94071. var data = this.data, keys = this.keys, key;
  94072. while (keys.length > 0) {
  94073. key = keys.pop();
  94074. delete data[key];
  94075. }
  94076. }
  94077. };
  94078. OIMO.Performance = function (world) {
  94079. this.parent = world;
  94080. this.infos = new OIMO_ARRAY_TYPE(13);
  94081. this.f = [0, 0, 0];
  94082. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94083. this.broadPhase = this.types[this.parent.broadPhase.types];
  94084. this.version = OIMO.REVISION;
  94085. this.fps = 0;
  94086. this.broadPhaseTime = 0;
  94087. this.narrowPhaseTime = 0;
  94088. this.solvingTime = 0;
  94089. //this.updatingTime = 0;
  94090. this.totalTime = 0;
  94091. };
  94092. OIMO.Performance.prototype = {
  94093. upfps: function () {
  94094. this.f[1] = Date.now();
  94095. 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]++;
  94096. },
  94097. updatingTime: function () {
  94098. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94099. },
  94100. show: function () {
  94101. var info = [
  94102. "Oimo.js " + this.version + "<br>",
  94103. this.broadPhase + "<br><br>",
  94104. "FPS: " + this.fps + " fps<br><br>",
  94105. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94106. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94107. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94108. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94109. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94110. "Time in milliseconde<br><br>",
  94111. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94112. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94113. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94114. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94115. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94116. ].join("\n");
  94117. return info;
  94118. },
  94119. toArray: function () {
  94120. this.infos[0] = this.parent.broadPhase.types;
  94121. this.infos[1] = this.parent.numRigidBodies;
  94122. this.infos[2] = this.parent.numContacts;
  94123. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94124. this.infos[4] = this.parent.numContactPoints;
  94125. this.infos[5] = this.parent.numIslands;
  94126. this.infos[6] = this.broadPhaseTime;
  94127. this.infos[7] = this.narrowPhaseTime;
  94128. this.infos[8] = this.solvingTime;
  94129. this.infos[9] = this.updatingTime();
  94130. this.infos[10] = this.totalTime;
  94131. this.infos[11] = this.fps;
  94132. return this.infos;
  94133. }
  94134. };
  94135. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94136. this.elements = new OIMO_ARRAY_TYPE(16);
  94137. var te = this.elements;
  94138. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94139. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94140. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94141. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94142. };
  94143. OIMO.Mat44.prototype = {
  94144. constructor: OIMO.Mat44,
  94145. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94146. var te = this.elements;
  94147. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94148. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94149. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94150. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94151. return this;
  94152. }/*,
  94153. extractRotation: function () {
  94154. var v1 = new THREE.Vector3();
  94155. return function ( m ) {
  94156. var te = this.elements;
  94157. var me = m.elements;
  94158. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94159. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94160. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94161. te[ 0 ] = me[ 0 ] * scaleX;
  94162. te[ 1 ] = me[ 1 ] * scaleX;
  94163. te[ 2 ] = me[ 2 ] * scaleX;
  94164. te[ 4 ] = me[ 4 ] * scaleY;
  94165. te[ 5 ] = me[ 5 ] * scaleY;
  94166. te[ 6 ] = me[ 6 ] * scaleY;
  94167. te[ 8 ] = me[ 8 ] * scaleZ;
  94168. te[ 9 ] = me[ 9 ] * scaleZ;
  94169. te[ 10 ] = me[ 10 ] * scaleZ;
  94170. return this;
  94171. };
  94172. }() */
  94173. }
  94174. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94175. this.elements = new OIMO_ARRAY_TYPE(9);
  94176. var te = this.elements;
  94177. this.init(
  94178. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94179. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94180. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94181. );
  94182. };
  94183. OIMO.Mat33.prototype = {
  94184. constructor: OIMO.Mat33,
  94185. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94186. var te = this.elements;
  94187. te[0] = e00; te[1] = e01; te[2] = e02;
  94188. te[3] = e10; te[4] = e11; te[5] = e12;
  94189. te[6] = e20; te[7] = e21; te[8] = e22;
  94190. return this;
  94191. },
  94192. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94193. var te = this.elements;
  94194. te[0] = e00; te[1] = e01; te[2] = e02;
  94195. te[3] = e10; te[4] = e11; te[5] = e12;
  94196. te[6] = e20; te[7] = e21; te[8] = e22;
  94197. return this;
  94198. },
  94199. multiply: function (s) {
  94200. var te = this.elements;
  94201. te[0] *= s; te[1] *= s; te[2] *= s;
  94202. te[3] *= s; te[4] *= s; te[5] *= s;
  94203. te[6] *= s; te[7] *= s; te[8] *= s;
  94204. return this;
  94205. },
  94206. add: function (m1, m2) {
  94207. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94208. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94209. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94210. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94211. return this;
  94212. },
  94213. addEqual: function (m) {
  94214. var te = this.elements, tem = m.elements;
  94215. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94216. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94217. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94218. return this;
  94219. },
  94220. sub: function (m1, m2) {
  94221. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94222. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94223. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94224. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94225. return this;
  94226. },
  94227. subEqual: function (m) {
  94228. var te = this.elements, tem = m.elements;
  94229. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94230. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94231. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94232. return this;
  94233. },
  94234. scale: function (m, s) {
  94235. var te = this.elements, tm = m.elements;
  94236. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94237. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94238. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94239. return this;
  94240. },
  94241. scaleEqual: function (s) {
  94242. var te = this.elements;
  94243. te[0] *= s; te[1] *= s; te[2] *= s;
  94244. te[3] *= s; te[4] *= s; te[5] *= s;
  94245. te[6] *= s; te[7] *= s; te[8] *= s;
  94246. return this;
  94247. },
  94248. mul: function (m1, m2) {
  94249. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94250. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94251. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94252. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94253. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94254. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94255. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94256. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94257. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94258. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94259. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94260. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94261. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94262. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94263. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94264. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94265. return this;
  94266. },
  94267. mulScale: function (m, sx, sy, sz, Prepend) {
  94268. var prepend = Prepend || false;
  94269. var te = this.elements, tm = m.elements;
  94270. if (prepend) {
  94271. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94272. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94273. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94274. } else {
  94275. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94276. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94277. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94278. }
  94279. return this;
  94280. },
  94281. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94282. var prepend = Prepend || false;
  94283. var s = OIMO.sin(rad);
  94284. var c = OIMO.cos(rad);
  94285. var c1 = 1 - c;
  94286. var r00 = ax * ax * c1 + c;
  94287. var r01 = ax * ay * c1 - az * s;
  94288. var r02 = ax * az * c1 + ay * s;
  94289. var r10 = ay * ax * c1 + az * s;
  94290. var r11 = ay * ay * c1 + c;
  94291. var r12 = ay * az * c1 - ax * s;
  94292. var r20 = az * ax * c1 - ay * s;
  94293. var r21 = az * ay * c1 + ax * s;
  94294. var r22 = az * az * c1 + c;
  94295. var tm = m.elements;
  94296. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94297. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94298. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94299. var te = this.elements;
  94300. if (prepend) {
  94301. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94302. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94303. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94304. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94305. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94306. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94307. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94308. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94309. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94310. } else {
  94311. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94312. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94313. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94314. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94315. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94316. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94317. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94318. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94319. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94320. }
  94321. return this;
  94322. },
  94323. transpose: function (m) {
  94324. var te = this.elements, tm = m.elements;
  94325. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94326. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94327. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94328. return this;
  94329. },
  94330. setQuat: function (q) {
  94331. var te = this.elements,
  94332. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94333. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94334. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94335. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94336. te[0] = 1 - yy - zz;
  94337. te[1] = xy - sz;
  94338. te[2] = xz + sy;
  94339. te[3] = xy + sz;
  94340. te[4] = 1 - xx - zz;
  94341. te[5] = yz - sx;
  94342. te[6] = xz - sy;
  94343. te[7] = yz + sx;
  94344. te[8] = 1 - xx - yy;
  94345. return this;
  94346. },
  94347. invert: function (m) {
  94348. var te = this.elements, tm = m.elements,
  94349. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94350. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94351. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94352. b01 = a4 * a8 - a7 * a5,
  94353. b11 = a7 * a2 - a1 * a8,
  94354. b21 = a1 * a5 - a4 * a2,
  94355. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94356. if (dt != 0) { dt = 1.0 / dt; }
  94357. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94358. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94359. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94360. te[3] = dt * (a5 * a6 - a3 * a8);
  94361. te[4] = dt * (a0 * a8 - a2 * a6);
  94362. te[5] = dt * (a2 * a3 - a0 * a5);
  94363. te[6] = dt * (a3 * a7 - a4 * a6);
  94364. te[7] = dt * (a1 * a6 - a0 * a7);
  94365. te[8] = dt * (a0 * a4 - a1 * a3);
  94366. return this;
  94367. },
  94368. /*copy: function(m){
  94369. var te = this.elements, tem = m.elements;
  94370. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94371. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94372. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94373. return this;
  94374. },*/
  94375. toEuler: function () { // not work !!
  94376. function clamp(x) {
  94377. return OIMO.min(OIMO.max(x, -1), 1);
  94378. }
  94379. var te = this.elements;
  94380. var m11 = te[0], m12 = te[3], m13 = te[6];
  94381. var m21 = te[1], m22 = te[4], m23 = te[7];
  94382. var m31 = te[2], m32 = te[5], m33 = te[8];
  94383. var p = new OIMO.Vec3();
  94384. var d = new OIMO.Quat();
  94385. var s;
  94386. p.y = OIMO.asin(clamp(m13));
  94387. if (OIMO.abs(m13) < 0.99999) {
  94388. p.x = OIMO.atan2(-m23, m33);
  94389. p.z = OIMO.atan2(-m12, m11);
  94390. } else {
  94391. p.x = OIMO.atan2(m32, m22);
  94392. p.z = 0;
  94393. }
  94394. return p;
  94395. },
  94396. /*clone: function(){
  94397. var te = this.elements;
  94398. return new OIMO.Mat33(
  94399. te[0], te[1], te[2],
  94400. te[3], te[4], te[5],
  94401. te[6], te[7], te[8]
  94402. );
  94403. },*/
  94404. toString: function () {
  94405. var te = this.elements;
  94406. var text =
  94407. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94408. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94409. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94410. return text;
  94411. },
  94412. // OK
  94413. multiplyScalar: function (s) {
  94414. var te = this.elements;
  94415. te[0] *= s; te[3] *= s; te[6] *= s;
  94416. te[1] *= s; te[4] *= s; te[7] *= s;
  94417. te[2] *= s; te[5] *= s; te[8] *= s;
  94418. return this;
  94419. },
  94420. identity: function () {
  94421. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94422. return this;
  94423. },
  94424. clone: function () {
  94425. return new this.constructor().fromArray(this.elements);
  94426. },
  94427. copy: function (m) {
  94428. var me = m.elements;
  94429. this.set(
  94430. me[0], me[3], me[6],
  94431. me[1], me[4], me[7],
  94432. me[2], me[5], me[8]
  94433. );
  94434. return this;
  94435. },
  94436. fromArray: function (array) {
  94437. this.elements.set(array);
  94438. return this;
  94439. },
  94440. toArray: function () {
  94441. var te = this.elements;
  94442. return [
  94443. te[0], te[1], te[2],
  94444. te[3], te[4], te[5],
  94445. te[6], te[7], te[8]
  94446. ];
  94447. }
  94448. };
  94449. OIMO.Quat = function (s, x, y, z) {
  94450. this.s = (s !== undefined) ? s : 1;
  94451. this.x = x || 0;
  94452. this.y = y || 0;
  94453. this.z = z || 0;
  94454. };
  94455. OIMO.Quat.prototype = {
  94456. constructor: OIMO.Quat,
  94457. set: function (x, y, z, w) {
  94458. this.x = x;
  94459. this.y = y;
  94460. this.z = z;
  94461. this.s = w;
  94462. return this;
  94463. },
  94464. init: function (s, x, y, z) {
  94465. this.s = (s !== undefined) ? s : 1;
  94466. this.x = x || 0;
  94467. this.y = y || 0;
  94468. this.z = z || 0;
  94469. return this;
  94470. },
  94471. add: function (q1, q2) {
  94472. this.s = q1.s + q2.s;
  94473. this.x = q1.x + q2.x;
  94474. this.y = q1.y + q2.y;
  94475. this.z = q1.z + q2.z;
  94476. return this;
  94477. },
  94478. addTime: function (v, t) {
  94479. var x = v.x;
  94480. var y = v.y;
  94481. var z = v.z;
  94482. var qs = this.s;
  94483. var qx = this.x;
  94484. var qy = this.y;
  94485. var qz = this.z;
  94486. t *= 0.5;
  94487. var ns = (-x * qx - y * qy - z * qz) * t;
  94488. var nx = (x * qs + y * qz - z * qy) * t;
  94489. var ny = (-x * qz + y * qs + z * qx) * t;
  94490. var nz = (x * qy - y * qx + z * qs) * t;
  94491. qs += ns;
  94492. qx += nx;
  94493. qy += ny;
  94494. qz += nz;
  94495. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94496. this.s = qs * s;
  94497. this.x = qx * s;
  94498. this.y = qy * s;
  94499. this.z = qz * s;
  94500. return this;
  94501. },
  94502. sub: function (q1, q2) {
  94503. this.s = q1.s - q2.s;
  94504. this.x = q1.x - q2.x;
  94505. this.y = q1.y - q2.y;
  94506. this.z = q1.z - q2.z;
  94507. return this;
  94508. },
  94509. scale: function (q, s) {
  94510. this.s = q.s * s;
  94511. this.x = q.x * s;
  94512. this.y = q.y * s;
  94513. this.z = q.z * s;
  94514. return this;
  94515. },
  94516. mul: function (q1, q2) {
  94517. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94518. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94519. this.x = ax * bs + as * bx + ay * bz - az * by;
  94520. this.y = ay * bs + as * by + az * bx - ax * bz;
  94521. this.z = az * bs + as * bz + ax * by - ay * bx;
  94522. this.s = as * bs - ax * bx - ay * by - az * bz;
  94523. return this;
  94524. },
  94525. arc: function (v1, v2) {
  94526. var x1 = v1.x;
  94527. var y1 = v1.y;
  94528. var z1 = v1.z;
  94529. var x2 = v2.x;
  94530. var y2 = v2.y;
  94531. var z2 = v2.z;
  94532. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94533. if (d == -1) {
  94534. x2 = y1 * x1 - z1 * z1;
  94535. y2 = -z1 * y1 - x1 * x1;
  94536. z2 = x1 * z1 + y1 * y1;
  94537. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94538. this.s = 0;
  94539. this.x = x2 * d;
  94540. this.y = y2 * d;
  94541. this.z = z2 * d;
  94542. return this;
  94543. }
  94544. var cx = y1 * z2 - z1 * y2;
  94545. var cy = z1 * x2 - x1 * z2;
  94546. var cz = x1 * y2 - y1 * x2;
  94547. this.s = OIMO.sqrt((1 + d) * 0.5);
  94548. d = 0.5 / this.s;
  94549. this.x = cx * d;
  94550. this.y = cy * d;
  94551. this.z = cz * d;
  94552. return this;
  94553. },
  94554. normalize: function (q) {
  94555. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94556. if (len > 0) { len = 1 / len; }
  94557. this.s = q.s * len;
  94558. this.x = q.x * len;
  94559. this.y = q.y * len;
  94560. this.z = q.z * len;
  94561. return this;
  94562. },
  94563. invert: function (q) {
  94564. this.s = q.s;
  94565. this.x = -q.x;
  94566. this.y = -q.y;
  94567. this.z = -q.z;
  94568. return this;
  94569. },
  94570. length: function () {
  94571. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94572. },
  94573. copy: function (q) {
  94574. this.s = q.s;
  94575. this.x = q.x;
  94576. this.y = q.y;
  94577. this.z = q.z;
  94578. return this;
  94579. },
  94580. testDiff: function (q) {
  94581. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94582. else return false;
  94583. },
  94584. clone: function (q) {
  94585. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94586. },
  94587. toString: function () {
  94588. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94589. }
  94590. }
  94591. // for three easy export
  94592. OIMO.Quaternion = function (x, y, z, w) {
  94593. this.x = x || 0;
  94594. this.y = y || 0;
  94595. this.z = z || 0;
  94596. this.w = (w !== undefined) ? w : 1;
  94597. };
  94598. OIMO.Quaternion.prototype = {
  94599. constructor: OIMO.Quaternion,
  94600. setFromRotationMatrix: function (m) {
  94601. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94602. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94603. var te = m.elements,
  94604. m11 = te[0], m12 = te[1], m13 = te[2],
  94605. m21 = te[3], m22 = te[4], m23 = te[5],
  94606. m31 = te[6], m32 = te[7], m33 = te[8],
  94607. trace = m11 + m22 + m33,
  94608. s;
  94609. if (trace > 0) {
  94610. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94611. this.w = 0.25 / s;
  94612. this.x = (m32 - m23) * s;
  94613. this.y = (m13 - m31) * s;
  94614. this.z = (m21 - m12) * s;
  94615. } else if (m11 > m22 && m11 > m33) {
  94616. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94617. this.w = (m32 - m23) / s;
  94618. this.x = 0.25 * s;
  94619. this.y = (m12 + m21) / s;
  94620. this.z = (m13 + m31) / s;
  94621. } else if (m22 > m33) {
  94622. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94623. this.w = (m13 - m31) / s;
  94624. this.x = (m12 + m21) / s;
  94625. this.y = 0.25 * s;
  94626. this.z = (m23 + m32) / s;
  94627. } else {
  94628. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94629. this.w = (m21 - m12) / s;
  94630. this.x = (m13 + m31) / s;
  94631. this.y = (m23 + m32) / s;
  94632. this.z = 0.25 * s;
  94633. }
  94634. //this.onChangeCallback();
  94635. return this;
  94636. }
  94637. }
  94638. OIMO.Vec3 = function (x, y, z) {
  94639. this.x = x || 0;
  94640. this.y = y || 0;
  94641. this.z = z || 0;
  94642. };
  94643. OIMO.Vec3.prototype = {
  94644. constructor: OIMO.Vec3,
  94645. init: function (x, y, z) {
  94646. this.x = x || 0;
  94647. this.y = y || 0;
  94648. this.z = z || 0;
  94649. return this;
  94650. },
  94651. set: function (x, y, z) {
  94652. this.x = x;
  94653. this.y = y;
  94654. this.z = z;
  94655. return this;
  94656. },
  94657. add: function (v1, v2) {
  94658. this.x = v1.x + v2.x;
  94659. this.y = v1.y + v2.y;
  94660. this.z = v1.z + v2.z;
  94661. return this;
  94662. },
  94663. addEqual: function (v) {
  94664. this.x += v.x;
  94665. this.y += v.y;
  94666. this.z += v.z;
  94667. return this;
  94668. },
  94669. addTime: function (v, t) {
  94670. this.x += v.x * t;
  94671. this.y += v.y * t;
  94672. this.z += v.z * t;
  94673. return this;
  94674. },
  94675. sub: function (v1, v2) {
  94676. this.x = v1.x - v2.x;
  94677. this.y = v1.y - v2.y;
  94678. this.z = v1.z - v2.z;
  94679. return this;
  94680. },
  94681. subEqual: function (v) {
  94682. this.x -= v.x;
  94683. this.y -= v.y;
  94684. this.z -= v.z;
  94685. return this;
  94686. },
  94687. addScale: function (v, s) {
  94688. this.x += v.x * s;
  94689. this.y += v.y * s;
  94690. this.z += v.z * s;
  94691. return this;
  94692. },
  94693. scale: function (v, s) {
  94694. this.x = v.x * s;
  94695. this.y = v.y * s;
  94696. this.z = v.z * s;
  94697. return this;
  94698. },
  94699. scaleEqual: function (s) {
  94700. this.x *= s;
  94701. this.y *= s;
  94702. this.z *= s;
  94703. return this;
  94704. },
  94705. /*dot: function(v){
  94706. return this.x*v.x+this.y*v.y+this.z*v.z;
  94707. },*/
  94708. cross: function (v1, v2) {
  94709. var ax = v1.x, ay = v1.y, az = v1.z,
  94710. bx = v2.x, by = v2.y, bz = v2.z;
  94711. this.x = ay * bz - az * by;
  94712. this.y = az * bx - ax * bz;
  94713. this.z = ax * by - ay * bx;
  94714. return this;
  94715. },
  94716. mul: function (o, v, m) {
  94717. var te = m.elements;
  94718. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94719. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94720. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94721. return this;
  94722. },
  94723. mulMat: function (m, v) {
  94724. var te = m.elements;
  94725. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94726. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94727. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94728. return this;
  94729. },
  94730. normalize: function (v) {
  94731. var x = v.x, y = v.y, z = v.z;
  94732. var l = x * x + y * y + z * z;
  94733. if (l > 0) {
  94734. l = 1 / OIMO.sqrt(l);
  94735. this.x = x * l;
  94736. this.y = y * l;
  94737. this.z = z * l;
  94738. }
  94739. return this;
  94740. },
  94741. /*norm: function(){
  94742. var x = this.x, y = this.y, z = this.z;
  94743. var l = x*x + y*y + z*z;
  94744. if (l > 0) {
  94745. l = 1 / OIMO.sqrt(l);
  94746. this.x = x*l;
  94747. this.y = y*l;
  94748. this.z = z*l;
  94749. }
  94750. return this;
  94751. },*/
  94752. invert: function (v) {
  94753. this.x = -v.x;
  94754. this.y = -v.y;
  94755. this.z = -v.z;
  94756. return this;
  94757. },
  94758. /*length: function(){
  94759. var x = this.x, y = this.y, z = this.z;
  94760. return OIMO.sqrt(x*x + y*y + z*z);
  94761. },*/
  94762. negate: function () {
  94763. this.x = -this.x;
  94764. this.y = -this.y;
  94765. this.z = -this.z;
  94766. return this;
  94767. },
  94768. dot: function (v) {
  94769. return this.x * v.x + this.y * v.y + this.z * v.z;
  94770. },
  94771. lengthSq: function () {
  94772. return this.x * this.x + this.y * this.y + this.z * this.z;
  94773. },
  94774. length: function () {
  94775. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94776. },
  94777. /*len: function(){
  94778. var x = this.x, y = this.y, z = this.z;
  94779. return x*x + y*y + z*z;
  94780. },*/
  94781. copy: function (v) {
  94782. this.x = v.x;
  94783. this.y = v.y;
  94784. this.z = v.z;
  94785. return this;
  94786. },
  94787. applyQuaternion: function (q) {
  94788. var x = this.x;
  94789. var y = this.y;
  94790. var z = this.z;
  94791. var qx = q.x;
  94792. var qy = q.y;
  94793. var qz = q.z;
  94794. var qs = q.s;
  94795. // calculate quat * vector
  94796. var ix = qs * x + qy * z - qz * y;
  94797. var iy = qs * y + qz * x - qx * z;
  94798. var iz = qs * z + qx * y - qy * x;
  94799. var iw = -qx * x - qy * y - qz * z;
  94800. // calculate result * inverse quat
  94801. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94802. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94803. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94804. return this;
  94805. },
  94806. testZero: function () {
  94807. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94808. else return false;
  94809. },
  94810. testDiff: function (v) {
  94811. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94812. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94813. //else return false;
  94814. },
  94815. equals: function (v) {
  94816. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94817. },
  94818. clone: function () {
  94819. return new this.constructor(this.x, this.y, this.z);
  94820. },
  94821. toString: function () {
  94822. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94823. },
  94824. multiplyScalar: function (scalar) {
  94825. if (isFinite(scalar)) {
  94826. this.x *= scalar;
  94827. this.y *= scalar;
  94828. this.z *= scalar;
  94829. } else {
  94830. this.x = 0;
  94831. this.y = 0;
  94832. this.z = 0;
  94833. }
  94834. return this;
  94835. },
  94836. divideScalar: function (scalar) {
  94837. return this.multiplyScalar(1 / scalar);
  94838. },
  94839. // TODO rename to normalize
  94840. norm: function () {
  94841. return this.divideScalar(this.length());
  94842. },
  94843. }
  94844. OIMO.Euler = function (x, y, z, order) {
  94845. this._x = x || 0;
  94846. this._y = y || 0;
  94847. this._z = z || 0;
  94848. this._order = order || OIMO.Euler.DefaultOrder;
  94849. };
  94850. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94851. OIMO.Euler.DefaultOrder = 'XYZ';
  94852. OIMO.clamp = function (x, a, b) {
  94853. return (x < a) ? a : ((x > b) ? b : x);
  94854. }
  94855. OIMO.Euler.prototype = {
  94856. constructor: OIMO.Euler,
  94857. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94858. get x() {
  94859. return this._x;
  94860. },
  94861. set x(value) {
  94862. this._x = value;
  94863. this.onChangeCallback();
  94864. },
  94865. get y() {
  94866. return this._y;
  94867. },
  94868. set y(value) {
  94869. this._y = value;
  94870. this.onChangeCallback();
  94871. },
  94872. get z() {
  94873. return this._z;
  94874. },
  94875. set z(value) {
  94876. this._z = value;
  94877. this.onChangeCallback();
  94878. },
  94879. get order() {
  94880. return this._order;
  94881. },
  94882. set order(value) {
  94883. this._order = value;
  94884. this.onChangeCallback();
  94885. },
  94886. set: function (x, y, z, order) {
  94887. this._x = x;
  94888. this._y = y;
  94889. this._z = z;
  94890. this._order = order || this._order;
  94891. this.onChangeCallback();
  94892. return this;
  94893. },
  94894. copy: function (euler) {
  94895. this._x = euler._x;
  94896. this._y = euler._y;
  94897. this._z = euler._z;
  94898. this._order = euler._order;
  94899. this.onChangeCallback();
  94900. return this;
  94901. },
  94902. setFromRotationMatrix: function (m, order) {
  94903. var clamp = OIMO.clamp;
  94904. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94905. var te = m.elements;
  94906. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94907. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94908. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94909. var m11 = te[0], m12 = te[1], m13 = te[2],
  94910. m21 = te[3], m22 = te[4], m23 = te[5],
  94911. m31 = te[6], m32 = te[7], m33 = te[8];
  94912. order = order || this._order;
  94913. if (order === 'XYZ') {
  94914. this._y = OIMO.asin(clamp(m13, -1, 1));
  94915. if (OIMO.abs(m13) < 0.99999) {
  94916. this._x = OIMO.atan2(-m23, m33);
  94917. this._z = OIMO.atan2(-m12, m11);
  94918. } else {
  94919. this._x = OIMO.atan2(m32, m22);
  94920. this._z = 0;
  94921. }
  94922. } else if (order === 'YXZ') {
  94923. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94924. if (OIMO.abs(m23) < 0.99999) {
  94925. this._y = OIMO.atan2(m13, m33);
  94926. this._z = OIMO.atan2(m21, m22);
  94927. } else {
  94928. this._y = OIMO.atan2(-m31, m11);
  94929. this._z = 0;
  94930. }
  94931. } else if (order === 'ZXY') {
  94932. this._x = OIMO.asin(clamp(m32, -1, 1));
  94933. if (OIMO.abs(m32) < 0.99999) {
  94934. this._y = OIMO.atan2(-m31, m33);
  94935. this._z = OIMO.atan2(-m12, m22);
  94936. } else {
  94937. this._y = 0;
  94938. this._z = OIMO.atan2(m21, m11);
  94939. }
  94940. } else if (order === 'ZYX') {
  94941. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94942. if (OIMO.abs(m31) < 0.99999) {
  94943. this._x = OIMO.atan2(m32, m33);
  94944. this._z = OIMO.atan2(m21, m11);
  94945. } else {
  94946. this._x = 0;
  94947. this._z = OIMO.atan2(-m12, m22);
  94948. }
  94949. } else if (order === 'YZX') {
  94950. this._z = OIMO.asin(clamp(m21, -1, 1));
  94951. if (OIMO.abs(m21) < 0.99999) {
  94952. this._x = OIMO.atan2(-m23, m22);
  94953. this._y = OIMO.atan2(-m31, m11);
  94954. } else {
  94955. this._x = 0;
  94956. this._y = OIMO.atan2(m13, m33);
  94957. }
  94958. } else if (order === 'XZY') {
  94959. this._z = OIMO.asin(-clamp(m12, -1, 1));
  94960. if (OIMO.abs(m12) < 0.99999) {
  94961. this._x = OIMO.atan2(m32, m22);
  94962. this._y = OIMO.atan2(m13, m11);
  94963. } else {
  94964. this._x = OIMO.atan2(-m23, m33);
  94965. this._y = 0;
  94966. }
  94967. } else {
  94968. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  94969. }
  94970. this._order = order;
  94971. this.onChangeCallback();
  94972. return this;
  94973. },
  94974. setFromQuaternion: function (q, order, update) {
  94975. var clamp = OIMO.clamp;
  94976. // q is assumed to be normalized
  94977. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  94978. var sqx = q.x * q.x;
  94979. var sqy = q.y * q.y;
  94980. var sqz = q.z * q.z;
  94981. var sqw = q.s * q.s;
  94982. order = order || this._order;
  94983. if (order === 'XYZ') {
  94984. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  94985. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  94986. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  94987. } else if (order === 'YXZ') {
  94988. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  94989. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  94990. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  94991. } else if (order === 'ZXY') {
  94992. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  94993. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  94994. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  94995. } else if (order === 'ZYX') {
  94996. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  94997. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  94998. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  94999. } else if (order === 'YZX') {
  95000. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  95001. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  95002. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  95003. } else if (order === 'XZY') {
  95004. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  95005. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  95006. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  95007. } else {
  95008. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  95009. }
  95010. this._order = order;
  95011. if (update !== false) this.onChangeCallback();
  95012. return this;
  95013. },
  95014. reorder: function () {
  95015. // WARNING: this discards revolution information -bhouston
  95016. var q = new OIMO.Quat();
  95017. return function (newOrder) {
  95018. q.setFromEuler(this);
  95019. this.setFromQuaternion(q, newOrder);
  95020. };
  95021. }(),
  95022. equals: function (euler) {
  95023. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  95024. },
  95025. fromArray: function (array) {
  95026. this._x = array[0];
  95027. this._y = array[1];
  95028. this._z = array[2];
  95029. if (array[3] !== undefined) this._order = array[3];
  95030. this.onChangeCallback();
  95031. return this;
  95032. },
  95033. toArray: function () {
  95034. return [this._x, this._y, this._z, this._order];
  95035. },
  95036. onChange: function (callback) {
  95037. this.onChangeCallback = callback;
  95038. return this;
  95039. },
  95040. onChangeCallback: function () { },
  95041. clone: function () {
  95042. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  95043. }
  95044. };
  95045. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  95046. var c1 = OIMO.cos(oy * 0.5);//heading
  95047. var s1 = OIMO.sin(oy * 0.5);
  95048. var c2 = OIMO.cos(oz * 0.5);//altitude
  95049. var s2 = OIMO.sin(oz * 0.5);
  95050. var c3 = OIMO.cos(ox * 0.5);//bank
  95051. var s3 = OIMO.sin(ox * 0.5);
  95052. var c1c2 = c1 * c2;
  95053. var s1s2 = s1 * s2;
  95054. var w = c1c2 * c3 - s1s2 * s3;
  95055. var x = c1c2 * s3 + s1s2 * c3;
  95056. var y = s1 * c2 * c3 + c1 * s2 * s3;
  95057. var z = c1 * s2 * c3 - s1 * c2 * s3;
  95058. var angle = 2 * OIMO.acos(w);
  95059. var norm = x * x + y * y + z * z;
  95060. if (norm < 0.001) {
  95061. x = 1;
  95062. y = z = 0;
  95063. } else {
  95064. norm = OIMO.sqrt(norm);
  95065. x /= norm;
  95066. y /= norm;
  95067. z /= norm;
  95068. }
  95069. return [angle, x, y, z];
  95070. }
  95071. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  95072. var ch = OIMO.cos(oy);//heading
  95073. var sh = OIMO.sin(oy);
  95074. var ca = OIMO.cos(oz);//altitude
  95075. var sa = OIMO.sin(oz);
  95076. var cb = OIMO.cos(ox);//bank
  95077. var sb = OIMO.sin(ox);
  95078. var mtx = new OIMO.Mat33();
  95079. var te = mtx.elements;
  95080. te[0] = ch * ca;
  95081. te[1] = sh * sb - ch * sa * cb;
  95082. te[2] = ch * sa * sb + sh * cb;
  95083. te[3] = sa;
  95084. te[4] = ca * cb;
  95085. te[5] = -ca * sb;
  95086. te[6] = -sh * ca;
  95087. te[7] = sh * sa * cb + ch * sb;
  95088. te[8] = -sh * sa * sb + ch * cb;
  95089. return mtx;
  95090. }
  95091. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95092. var te = mtx.elements;
  95093. var x, y, z;
  95094. if (te[3] > 0.998) { // singularity at north pole
  95095. y = OIMO.atan2(te[2], te[8]);
  95096. z = OIMO.PI / 2;
  95097. x = 0;
  95098. } else if (te[3] < -0.998) { // singularity at south pole
  95099. y = OIMO.atan2(te[2], te[8]);
  95100. z = -OIMO.PI / 2;
  95101. x = 0;
  95102. } else {
  95103. y = OIMO.atan2(-te[6], te[0]);
  95104. x = OIMO.atan2(-te[5], te[4]);
  95105. z = OIMO.asin(te[3]);
  95106. }
  95107. return [x, y, z];
  95108. }
  95109. OIMO.unwrapDegrees = function (r) {
  95110. r = r % 360;
  95111. if (r > 180) r -= 360;
  95112. if (r < -180) r += 360;
  95113. return r;
  95114. }
  95115. OIMO.unwrapRadian = function (r) {
  95116. r = r % OIMO.TwoPI;
  95117. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95118. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95119. return r;
  95120. }
  95121. OIMO.Distance3d = function (p1, p2) {
  95122. var xd = p2[0] - p1[0];
  95123. var yd = p2[1] - p1[1];
  95124. var zd = p2[2] - p1[2];
  95125. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95126. }
  95127. /**
  95128. * The base class of all type of the constraints.
  95129. * @author saharan
  95130. */
  95131. OIMO.Constraint = function () {
  95132. // The parent world of the constraint.
  95133. this.parent = null;
  95134. // The first body of the constraint.
  95135. this.body1 = null;
  95136. // The second body of the constraint.
  95137. this.body2 = null;
  95138. // Internal
  95139. this.addedToIsland = false;
  95140. }
  95141. OIMO.Constraint.prototype = {
  95142. constructor: OIMO.Constraint,
  95143. /**
  95144. * Prepare for solving the constraint.
  95145. * @param timeStep
  95146. * @param invTimeStep
  95147. */
  95148. preSolve: function (timeStep, invTimeStep) {
  95149. OIMO.Error("Constraint", "Inheritance error.");
  95150. },
  95151. /**
  95152. * Solve the constraint.
  95153. * This is usually called iteratively.
  95154. */
  95155. solve: function () {
  95156. OIMO.Error("Constraint", "Inheritance error.");
  95157. },
  95158. /**
  95159. * Do the post-processing.
  95160. */
  95161. postSolve: function () {
  95162. OIMO.Error("Constraint", "Inheritance error.");
  95163. }
  95164. }
  95165. /**
  95166. * Joints are used to constrain the motion between two rigid bodies.
  95167. * @author saharan
  95168. * @author lo-th
  95169. */
  95170. OIMO.Joint = function (config) {
  95171. OIMO.Constraint.call(this);
  95172. // joint name
  95173. this.name = "";
  95174. // The type of the joint.
  95175. this.type = OIMO.JOINT_NULL;
  95176. // The previous joint in the world.
  95177. this.prev = null;
  95178. // The next joint in the world.
  95179. this.next = null;
  95180. this.body1 = config.body1;
  95181. this.body2 = config.body2;
  95182. // The anchor point on the first rigid body in local coordinate system.
  95183. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95184. // The anchor point on the second rigid body in local coordinate system.
  95185. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95186. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95187. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95188. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95189. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95190. // The anchor point on the first rigid body in world coordinate system.
  95191. this.anchorPoint1 = new OIMO.Vec3();
  95192. // The anchor point on the second rigid body in world coordinate system.
  95193. this.anchorPoint2 = new OIMO.Vec3();
  95194. // Whether allow collision between connected rigid bodies or not.
  95195. this.allowCollision = config.allowCollision;
  95196. this.b1Link = new OIMO.JointLink(this);
  95197. this.b2Link = new OIMO.JointLink(this);
  95198. this.matrix = new OIMO.Mat44();
  95199. };
  95200. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95201. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95202. // Update all the anchor points.
  95203. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95204. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95205. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95206. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95207. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95208. };
  95209. // Attach the joint from the bodies.
  95210. OIMO.Joint.prototype.attach = function () {
  95211. this.b1Link.body = this.body2;
  95212. this.b2Link.body = this.body1;
  95213. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95214. else this.b1Link.next = null;
  95215. this.body1.jointLink = this.b1Link;
  95216. this.body1.numJoints++;
  95217. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95218. else this.b2Link.next = null;
  95219. this.body2.jointLink = this.b2Link;
  95220. this.body2.numJoints++;
  95221. };
  95222. // Detach the joint from the bodies.
  95223. OIMO.Joint.prototype.detach = function () {
  95224. var prev = this.b1Link.prev;
  95225. var next = this.b1Link.next;
  95226. if (prev != null) prev.next = next;
  95227. if (next != null) next.prev = prev;
  95228. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95229. this.b1Link.prev = null;
  95230. this.b1Link.next = null;
  95231. this.b1Link.body = null;
  95232. this.body1.numJoints--;
  95233. prev = this.b2Link.prev;
  95234. next = this.b2Link.next;
  95235. if (prev != null) prev.next = next;
  95236. if (next != null) next.prev = prev;
  95237. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95238. this.b2Link.prev = null;
  95239. this.b2Link.next = null;
  95240. this.b2Link.body = null;
  95241. this.body2.numJoints--;
  95242. this.b1Link.body = null;
  95243. this.b2Link.body = null;
  95244. };
  95245. // Awake the bodies.
  95246. OIMO.Joint.prototype.awake = function () {
  95247. this.body1.awake();
  95248. this.body2.awake();
  95249. };
  95250. // calculation function
  95251. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95252. };
  95253. OIMO.Joint.prototype.solve = function () {
  95254. };
  95255. OIMO.Joint.prototype.postSolve = function () {
  95256. };
  95257. // Delete process
  95258. OIMO.Joint.prototype.remove = function () {
  95259. this.dispose();
  95260. };
  95261. OIMO.Joint.prototype.dispose = function () {
  95262. this.parent.removeJoint(this);
  95263. };
  95264. // Three js add
  95265. OIMO.Joint.prototype.getPosition = function () {
  95266. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95267. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95268. return [p1, p2];
  95269. };
  95270. OIMO.Joint.prototype.getMatrix = function () {
  95271. var m = this.matrix.elements;
  95272. var p1 = this.anchorPoint1;
  95273. var p2 = this.anchorPoint2;
  95274. m[0] = p1.x * OIMO.WORLD_SCALE;
  95275. m[1] = p1.y * OIMO.WORLD_SCALE;
  95276. m[2] = p1.z * OIMO.WORLD_SCALE;
  95277. m[3] = 0;
  95278. m[4] = p2.x * OIMO.WORLD_SCALE;
  95279. m[5] = p2.y * OIMO.WORLD_SCALE;
  95280. m[6] = p2.z * OIMO.WORLD_SCALE;
  95281. m[7] = 0;
  95282. return m;
  95283. };
  95284. /**
  95285. * A joint configuration holds all configuration data for constructing a joint.
  95286. * Joint configurations can be reused safely.
  95287. * @author saharan
  95288. */
  95289. OIMO.JointConfig = function () {
  95290. // The first rigid body of the joint.
  95291. this.body1 = null;
  95292. // The second rigid body of the joint.
  95293. this.body2 = null;
  95294. // The anchor point on the first rigid body in local coordinate system.
  95295. this.localAnchorPoint1 = new OIMO.Vec3();
  95296. // The anchor point on the second rigid body in local coordinate system.
  95297. this.localAnchorPoint2 = new OIMO.Vec3();
  95298. // The axis in the first body's coordinate system.
  95299. // his property is available in some joints.
  95300. this.localAxis1 = new OIMO.Vec3();
  95301. // The axis in the second body's coordinate system.
  95302. // This property is available in some joints.
  95303. this.localAxis2 = new OIMO.Vec3();
  95304. // Whether allow collision between connected rigid bodies or not.
  95305. this.allowCollision = false;
  95306. };
  95307. /**
  95308. * A link list of joints.
  95309. * @author saharan
  95310. */
  95311. OIMO.JointLink = function (joint) {
  95312. // The previous joint link.
  95313. this.prev = null;
  95314. // The next joint link.
  95315. this.next = null;
  95316. // The other rigid body connected to the joint.
  95317. this.body = null;
  95318. // The joint of the link.
  95319. this.joint = joint;
  95320. };
  95321. /**
  95322. * An information of limit and motor.
  95323. * @author saharan
  95324. */
  95325. OIMO.LimitMotor = function (axis, fixed) {
  95326. fixed = fixed || false;
  95327. // The axis of the constraint.
  95328. this.axis = axis;
  95329. // The current angle for rotational constraints.
  95330. this.angle = 0;
  95331. // The lower limit. Set lower > upper to disable
  95332. this.lowerLimit = fixed ? 0 : 1;
  95333. //if(fixed)this.lowerLimit = 0;
  95334. //else this.lowerLimit = 1;
  95335. // The upper limit. Set lower > upper to disable.
  95336. this.upperLimit = 0;
  95337. // The target motor speed.
  95338. this.motorSpeed = 0;
  95339. // The maximum motor force or torque. Set 0 to disable.
  95340. this.maxMotorForce = 0;
  95341. // The frequency of the spring. Set 0 to disable.
  95342. this.frequency = 0;
  95343. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95344. this.dampingRatio = 0;
  95345. };
  95346. OIMO.LimitMotor.prototype = {
  95347. constructor: OIMO.LimitMotor,
  95348. /**
  95349. * Set limit data into this constraint.
  95350. * @param lowerLimit
  95351. * @param upperLimit
  95352. */
  95353. setLimit: function (lowerLimit, upperLimit) {
  95354. this.lowerLimit = lowerLimit;
  95355. this.upperLimit = upperLimit;
  95356. },
  95357. /**
  95358. * Set motor data into this constraint.
  95359. * @param motorSpeed
  95360. * @param maxMotorForce
  95361. */
  95362. setMotor: function (motorSpeed, maxMotorForce) {
  95363. this.motorSpeed = motorSpeed;
  95364. this.maxMotorForce = maxMotorForce;
  95365. },
  95366. /**
  95367. * Set spring data into this constraint.
  95368. * @param frequency
  95369. * @param dampingRatio
  95370. */
  95371. setSpring: function (frequency, dampingRatio) {
  95372. this.frequency = frequency;
  95373. this.dampingRatio = dampingRatio;
  95374. }
  95375. };
  95376. /**
  95377. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95378. * @author saharan
  95379. * @author lo-th
  95380. */
  95381. OIMO.BallAndSocketJoint = function (config) {
  95382. OIMO.Joint.call(this, config);
  95383. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95384. this.lc = new OIMO.LinearConstraint(this);
  95385. };
  95386. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95387. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95388. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95389. this.updateAnchorPoints();
  95390. this.lc.preSolve(timeStep, invTimeStep);
  95391. };
  95392. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95393. this.lc.solve();
  95394. };
  95395. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95396. };
  95397. /**
  95398. * A distance joint limits the distance between two anchor points on rigid bodies.
  95399. * @author saharan
  95400. * @author lo-th
  95401. */
  95402. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95403. OIMO.Joint.call(this, config);
  95404. this.type = OIMO.JOINT_DISTANCE;
  95405. this.normal = new OIMO.Vec3();
  95406. this.nr = new OIMO.Vec3();
  95407. // The limit and motor information of the joint.
  95408. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95409. this.limitMotor.lowerLimit = minDistance;
  95410. this.limitMotor.upperLimit = maxDistance;
  95411. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95412. };
  95413. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95414. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95415. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95416. this.updateAnchorPoints();
  95417. //var nr = this.nr;
  95418. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95419. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95420. //if(len>0) len = 1/len;
  95421. //this.normal.scale( nr, len );
  95422. this.normal.normalize(this.nr);
  95423. this.t.preSolve(timeStep, invTimeStep);
  95424. };
  95425. OIMO.DistanceJoint.prototype.solve = function () {
  95426. this.t.solve();
  95427. };
  95428. OIMO.DistanceJoint.prototype.postSolve = function () {
  95429. };
  95430. /**
  95431. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95432. * @author saharan
  95433. * @author lo-th
  95434. */
  95435. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95436. OIMO.Joint.call(this, config);
  95437. this.type = OIMO.JOINT_HINGE;
  95438. // The axis in the first body's coordinate system.
  95439. this.localAxis1 = config.localAxis1.clone().norm();
  95440. // The axis in the second body's coordinate system.
  95441. this.localAxis2 = config.localAxis2.clone().norm();
  95442. // make angle axis 1
  95443. this.localAngle1 = new OIMO.Vec3(
  95444. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95445. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95446. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95447. ).norm();
  95448. // make angle axis 2
  95449. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95450. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95451. this.nor = new OIMO.Vec3();
  95452. this.tan = new OIMO.Vec3();
  95453. this.bin = new OIMO.Vec3();
  95454. this.ax1 = new OIMO.Vec3();
  95455. this.ax2 = new OIMO.Vec3();
  95456. this.an1 = new OIMO.Vec3();
  95457. this.an2 = new OIMO.Vec3();
  95458. // The rotational limit and motor information of the joint.
  95459. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95460. this.limitMotor.lowerLimit = lowerAngleLimit;
  95461. this.limitMotor.upperLimit = upperAngleLimit;
  95462. this.lc = new OIMO.LinearConstraint(this);
  95463. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95464. };
  95465. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95466. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95467. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95468. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95469. this.updateAnchorPoints();
  95470. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95471. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95472. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95473. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95474. this.nor.set(
  95475. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95476. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95477. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95478. ).norm();
  95479. this.tan.set(
  95480. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95481. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95482. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95483. ).norm();
  95484. this.bin.set(
  95485. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95486. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95487. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95488. );
  95489. // calculate hinge angle
  95490. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95491. if (
  95492. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95493. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95494. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95495. ) {
  95496. this.limitMotor.angle = -limite;
  95497. } else {
  95498. this.limitMotor.angle = limite;
  95499. }
  95500. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95501. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95502. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95503. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95504. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95505. this.r3.preSolve(timeStep, invTimeStep);
  95506. this.lc.preSolve(timeStep, invTimeStep);
  95507. };
  95508. OIMO.HingeJoint.prototype.solve = function () {
  95509. this.r3.solve();
  95510. this.lc.solve();
  95511. };
  95512. OIMO.HingeJoint.prototype.postSolve = function () {
  95513. };
  95514. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95515. if (cos > 1) return 0;
  95516. else if (cos < -1) return OIMO.PI;
  95517. else return OIMO.acos(cos);
  95518. };
  95519. /**
  95520. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95521. * @author saharan
  95522. * @author lo-th
  95523. */
  95524. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95525. OIMO.Joint.call(this, config);
  95526. this.type = OIMO.JOINT_PRISMATIC;
  95527. // The axis in the first body's coordinate system.
  95528. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95529. // The axis in the second body's coordinate system.
  95530. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95531. this.localAxis1X = this.localAxis1.x;
  95532. this.localAxis1Y = this.localAxis1.y;
  95533. this.localAxis1Z = this.localAxis1.z;
  95534. this.localAxis2X = this.localAxis2.x;
  95535. this.localAxis2Y = this.localAxis2.y;
  95536. this.localAxis2Z = this.localAxis2.z;
  95537. this.nor = new OIMO.Vec3();
  95538. this.tan = new OIMO.Vec3();
  95539. this.bin = new OIMO.Vec3();
  95540. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95541. // The translational limit and motor information of the joint.
  95542. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95543. this.limitMotor.lowerLimit = lowerTranslation;
  95544. this.limitMotor.upperLimit = upperTranslation;
  95545. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95546. };
  95547. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95548. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95549. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95550. var tmpM;
  95551. var tmp1X;
  95552. var tmp1Y;
  95553. var tmp1Z;
  95554. this.updateAnchorPoints();
  95555. tmpM = this.body1.rotation.elements;
  95556. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95557. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95558. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95559. tmpM = this.body2.rotation.elements;
  95560. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95561. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95562. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95563. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95564. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95565. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95566. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95567. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95568. nx *= tmp1X;
  95569. ny *= tmp1X;
  95570. nz *= tmp1X;
  95571. var tx = ny * nx - nz * nz;
  95572. var ty = -nz * ny - nx * nx;
  95573. var tz = nx * nz + ny * ny;
  95574. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95575. tx *= tmp1X;
  95576. ty *= tmp1X;
  95577. tz *= tmp1X;
  95578. var bx = ny * tz - nz * ty;
  95579. var by = nz * tx - nx * tz;
  95580. var bz = nx * ty - ny * tx;
  95581. this.nor.init(nx, ny, nz);
  95582. this.tan.init(tx, ty, tz);
  95583. this.bin.init(bx, by, bz);
  95584. this.ac.preSolve(timeStep, invTimeStep);
  95585. this.t3.preSolve(timeStep, invTimeStep);
  95586. };
  95587. OIMO.PrismaticJoint.prototype.solve = function () {
  95588. this.ac.solve();
  95589. this.t3.solve();
  95590. };
  95591. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95592. };
  95593. /**
  95594. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95595. * @author saharan
  95596. * @author lo-th
  95597. */
  95598. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95599. OIMO.Joint.call(this, config);
  95600. this.type = OIMO.JOINT_SLIDER;
  95601. // The first axis in local coordinate system.
  95602. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95603. // The second axis in local coordinate system.
  95604. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95605. var len;
  95606. this.localAxis1X = this.localAxis1.x;
  95607. this.localAxis1Y = this.localAxis1.y;
  95608. this.localAxis1Z = this.localAxis1.z;
  95609. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95610. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95611. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95612. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95613. this.localAngAxis1X *= len;
  95614. this.localAngAxis1Y *= len;
  95615. this.localAngAxis1Z *= len;
  95616. this.localAxis2X = this.localAxis2.x;
  95617. this.localAxis2Y = this.localAxis2.y;
  95618. this.localAxis2Z = this.localAxis2.z;
  95619. // make angle axis 2
  95620. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95621. var tarc = arc.elements;
  95622. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95623. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95624. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95625. this.nor = new OIMO.Vec3();
  95626. this.tan = new OIMO.Vec3();
  95627. this.bin = new OIMO.Vec3();
  95628. // The limit and motor for the rotation
  95629. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95630. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95631. // The limit and motor for the translation.
  95632. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95633. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95634. this.translationalLimitMotor.upperLimit = upperTranslation;
  95635. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95636. };
  95637. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95638. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95639. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95640. var tmpM;
  95641. var tmp1X;
  95642. var tmp1Y;
  95643. var tmp1Z;
  95644. this.updateAnchorPoints();
  95645. tmpM = this.body1.rotation.elements;
  95646. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95647. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95648. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95649. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95650. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95651. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95652. tmpM = this.body2.rotation.elements;
  95653. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95654. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95655. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95656. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95657. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95658. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95659. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95660. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95661. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95662. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95663. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95664. nx *= tmp1X;
  95665. ny *= tmp1X;
  95666. nz *= tmp1X;
  95667. var tx = ny * nx - nz * nz;
  95668. var ty = -nz * ny - nx * nx;
  95669. var tz = nx * nz + ny * ny;
  95670. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95671. tx *= tmp1X;
  95672. ty *= tmp1X;
  95673. tz *= tmp1X;
  95674. var bx = ny * tz - nz * ty;
  95675. var by = nz * tx - nx * tz;
  95676. var bz = nx * ty - ny * tx;
  95677. this.nor.init(nx, ny, nz);
  95678. this.tan.init(tx, ty, tz);
  95679. this.bin.init(bx, by, bz);
  95680. // ----------------------------------------------
  95681. // calculate hinge angle
  95682. // ----------------------------------------------
  95683. if (
  95684. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95685. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95686. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95687. ) {
  95688. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95689. } else {
  95690. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95691. }
  95692. // angular error
  95693. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95694. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95695. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95696. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95697. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95698. this.r3.preSolve(timeStep, invTimeStep);
  95699. this.t3.preSolve(timeStep, invTimeStep);
  95700. };
  95701. OIMO.SliderJoint.prototype.solve = function () {
  95702. this.r3.solve();
  95703. this.t3.solve();
  95704. };
  95705. OIMO.SliderJoint.prototype.postSolve = function () {
  95706. };
  95707. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95708. if (cos > 1) return 0;
  95709. else if (cos < -1) return OIMO.PI;
  95710. else return OIMO.acos(cos);
  95711. };
  95712. /**
  95713. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95714. * The wheel joint also allows for relative translation for the suspension.
  95715. * @author saharan
  95716. * @author lo-th
  95717. */
  95718. OIMO.WheelJoint = function (config) {
  95719. OIMO.Joint.call(this, config);
  95720. this.type = OIMO.JOINT_WHEEL;
  95721. // The first axis in local coordinate system.
  95722. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95723. // The second axis in local coordinate system.
  95724. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95725. var len;
  95726. this.localAxis1X = this.localAxis1.x;
  95727. this.localAxis1Y = this.localAxis1.y;
  95728. this.localAxis1Z = this.localAxis1.z;
  95729. this.localAxis2X = this.localAxis2.x;
  95730. this.localAxis2Y = this.localAxis2.y;
  95731. this.localAxis2Z = this.localAxis2.z;
  95732. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95733. if (dot > -1 && dot < 1) {
  95734. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95735. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95736. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95737. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95738. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95739. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95740. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95741. this.localAngAxis1X *= len;
  95742. this.localAngAxis1Y *= len;
  95743. this.localAngAxis1Z *= len;
  95744. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95745. this.localAngAxis2X *= len;
  95746. this.localAngAxis2Y *= len;
  95747. this.localAngAxis2Z *= len;
  95748. } else {
  95749. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95750. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95751. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95752. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95753. this.localAngAxis1X *= len;
  95754. this.localAngAxis1Y *= len;
  95755. this.localAngAxis1Z *= len;
  95756. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95757. var tarc = arc.elements;
  95758. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95759. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95760. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95761. }
  95762. this.nor = new OIMO.Vec3();
  95763. this.tan = new OIMO.Vec3();
  95764. this.bin = new OIMO.Vec3();
  95765. // The translational limit and motor information of the joint.
  95766. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95767. this.translationalLimitMotor.frequency = 8;
  95768. this.translationalLimitMotor.dampingRatio = 1;
  95769. // The first rotational limit and motor information of the joint.
  95770. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95771. // The second rotational limit and motor information of the joint.
  95772. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95773. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95774. this.t3.weight = 1;
  95775. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95776. };
  95777. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95778. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95779. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95780. var tmpM;
  95781. var tmp1X;
  95782. var tmp1Y;
  95783. var tmp1Z;
  95784. this.updateAnchorPoints();
  95785. tmpM = this.body1.rotation.elements;
  95786. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95787. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95788. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95789. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95790. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95791. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95792. tmpM = this.body2.rotation.elements;
  95793. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95794. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95795. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95796. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95797. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95798. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95799. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95800. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95801. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95802. } else {
  95803. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95804. }
  95805. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95806. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95807. } else {
  95808. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95809. }
  95810. var nx = y2 * z1 - z2 * y1;
  95811. var ny = z2 * x1 - x2 * z1;
  95812. var nz = x2 * y1 - y2 * x1;
  95813. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95814. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95815. nx *= tmp1X;
  95816. ny *= tmp1X;
  95817. nz *= tmp1X;
  95818. var tx = ny * z2 - nz * y2;
  95819. var ty = nz * x2 - nx * z2;
  95820. var tz = nx * y2 - ny * x2;
  95821. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95822. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95823. tx *= tmp1X;
  95824. ty *= tmp1X;
  95825. tz *= tmp1X;
  95826. var bx = y1 * nz - z1 * ny;
  95827. var by = z1 * nx - x1 * nz;
  95828. var bz = x1 * ny - y1 * nx;
  95829. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95830. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95831. bx *= tmp1X;
  95832. by *= tmp1X;
  95833. bz *= tmp1X;
  95834. this.nor.init(nx, ny, nz);
  95835. this.tan.init(tx, ty, tz);
  95836. this.bin.init(bx, by, bz);
  95837. this.r3.preSolve(timeStep, invTimeStep);
  95838. this.t3.preSolve(timeStep, invTimeStep);
  95839. };
  95840. OIMO.WheelJoint.prototype.solve = function () {
  95841. this.r3.solve();
  95842. this.t3.solve();
  95843. };
  95844. OIMO.WheelJoint.prototype.postSolve = function () {
  95845. };
  95846. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95847. if (cos > 1) return 0;
  95848. else if (cos < -1) return OIMO.PI;
  95849. else return OIMO.acos(cos);
  95850. };
  95851. /**
  95852. * An angular constraint for all axes for various joints.
  95853. * @author saharan
  95854. */
  95855. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95856. this.joint = joint;
  95857. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95858. this.relativeOrientation = new OIMO.Quat();
  95859. this.ii1 = null;
  95860. this.ii2 = null;
  95861. this.dd = null;
  95862. this.vel = new OIMO.Vec3();
  95863. this.imp = new OIMO.Vec3();
  95864. this.rn0 = new OIMO.Vec3();
  95865. this.rn1 = new OIMO.Vec3();
  95866. this.rn2 = new OIMO.Vec3();
  95867. this.b1 = joint.body1;
  95868. this.b2 = joint.body2;
  95869. this.a1 = this.b1.angularVelocity;
  95870. this.a2 = this.b2.angularVelocity;
  95871. this.i1 = this.b1.inverseInertia;
  95872. this.i2 = this.b2.inverseInertia;
  95873. };
  95874. OIMO.AngularConstraint.prototype = {
  95875. constructor: OIMO.AngularConstraint,
  95876. preSolve: function (timeStep, invTimeStep) {
  95877. var inv, len, v, vv;
  95878. this.ii1 = this.i1.clone();
  95879. this.ii2 = this.i2.clone();
  95880. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95881. 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]));
  95882. this.dd = new OIMO.Mat33(
  95883. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95884. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95885. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95886. ).multiply(inv);
  95887. this.relativeOrientation.invert(this.b1.orientation);
  95888. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95889. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95890. inv = this.relativeOrientation.s * 2;
  95891. this.vel.scale(this.relativeOrientation, inv);
  95892. len = this.vel.length();
  95893. if (len > 0.02) {
  95894. len = (0.02 - len) / len * invTimeStep * 0.05;
  95895. this.vel.scaleEqual(len);
  95896. } else {
  95897. this.vel.init();
  95898. }
  95899. this.rn1.mulMat(this.ii1, this.imp);
  95900. this.rn2.mulMat(this.ii2, this.imp);
  95901. this.a1.addEqual(this.rn1);
  95902. this.a2.subEqual(this.rn2);
  95903. },
  95904. solve: function () {
  95905. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95906. this.rn0.mulMat(this.dd, r);
  95907. this.rn1.mulMat(this.ii1, this.rn0);
  95908. this.rn2.mulMat(this.ii2, this.rn0);
  95909. this.imp.addEqual(this.rn0);
  95910. this.a1.addEqual(this.rn1);
  95911. this.a2.subEqual(this.rn2);
  95912. }
  95913. };
  95914. /**
  95915. * A linear constraint for all axes for various joints.
  95916. * @author saharan
  95917. */
  95918. OIMO.LinearConstraint = function (joint) {
  95919. this.m1 = NaN;
  95920. this.m2 = NaN;
  95921. this.ii1 = null;
  95922. this.ii2 = null;
  95923. this.dd = null;
  95924. this.r1x = NaN;
  95925. this.r1y = NaN;
  95926. this.r1z = NaN;
  95927. this.r2x = NaN;
  95928. this.r2y = NaN;
  95929. this.r2z = NaN;
  95930. this.ax1x = NaN;
  95931. this.ax1y = NaN;
  95932. this.ax1z = NaN;
  95933. this.ay1x = NaN;
  95934. this.ay1y = NaN;
  95935. this.ay1z = NaN;
  95936. this.az1x = NaN;
  95937. this.az1y = NaN;
  95938. this.az1z = NaN;
  95939. this.ax2x = NaN;
  95940. this.ax2y = NaN;
  95941. this.ax2z = NaN;
  95942. this.ay2x = NaN;
  95943. this.ay2y = NaN;
  95944. this.ay2z = NaN;
  95945. this.az2x = NaN;
  95946. this.az2y = NaN;
  95947. this.az2z = NaN;
  95948. this.vel = NaN;
  95949. this.velx = NaN;
  95950. this.vely = NaN;
  95951. this.velz = NaN;
  95952. this.joint = joint;
  95953. this.r1 = joint.relativeAnchorPoint1;
  95954. this.r2 = joint.relativeAnchorPoint2;
  95955. this.p1 = joint.anchorPoint1;
  95956. this.p2 = joint.anchorPoint2;
  95957. this.b1 = joint.body1;
  95958. this.b2 = joint.body2;
  95959. this.l1 = this.b1.linearVelocity;
  95960. this.l2 = this.b2.linearVelocity;
  95961. this.a1 = this.b1.angularVelocity;
  95962. this.a2 = this.b2.angularVelocity;
  95963. this.i1 = this.b1.inverseInertia;
  95964. this.i2 = this.b2.inverseInertia;
  95965. this.impx = 0;
  95966. this.impy = 0;
  95967. this.impz = 0;
  95968. }
  95969. OIMO.LinearConstraint.prototype = {
  95970. constructor: OIMO.LinearConstraint,
  95971. preSolve: function (timeStep, invTimeStep) {
  95972. this.r1x = this.r1.x;
  95973. this.r1y = this.r1.y;
  95974. this.r1z = this.r1.z;
  95975. this.r2x = this.r2.x;
  95976. this.r2y = this.r2.y;
  95977. this.r2z = this.r2.z;
  95978. this.m1 = this.b1.inverseMass;
  95979. this.m2 = this.b2.inverseMass;
  95980. this.ii1 = this.i1.clone();
  95981. this.ii2 = this.i2.clone();
  95982. var ii1 = this.ii1.elements;
  95983. var ii2 = this.ii2.elements;
  95984. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  95985. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  95986. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  95987. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  95988. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  95989. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  95990. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  95991. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  95992. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  95993. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  95994. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  95995. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  95996. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  95997. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  95998. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  95999. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  96000. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  96001. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  96002. // calculate point-to-point mass matrix
  96003. // from impulse equation
  96004. //
  96005. // M = ([/m] - [r^][/I][r^]) ^ -1
  96006. //
  96007. // where
  96008. //
  96009. // [/m] = |1/m, 0, 0|
  96010. // |0, 1/m, 0|
  96011. // |0, 0, 1/m|
  96012. //
  96013. // [r^] = |0, -rz, ry|
  96014. // |rz, 0, -rx|
  96015. // |-ry, rx, 0|
  96016. //
  96017. // [/I] = Inverted moment inertia
  96018. var rxx = this.m1 + this.m2;
  96019. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  96020. var k = kk.elements;
  96021. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  96022. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96023. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  96024. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96025. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  96026. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  96027. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  96028. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  96029. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  96030. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  96031. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96032. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  96033. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96034. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  96035. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  96036. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  96037. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  96038. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  96039. 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]));
  96040. this.dd = new OIMO.Mat33(
  96041. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  96042. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  96043. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  96044. ).multiply(inv);
  96045. this.velx = this.p2.x - this.p1.x;
  96046. this.vely = this.p2.y - this.p1.y;
  96047. this.velz = this.p2.z - this.p1.z;
  96048. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  96049. if (len > 0.005) {
  96050. len = (0.005 - len) / len * invTimeStep * 0.05;
  96051. this.velx *= len;
  96052. this.vely *= len;
  96053. this.velz *= len;
  96054. } else {
  96055. this.velx = 0;
  96056. this.vely = 0;
  96057. this.velz = 0;
  96058. }
  96059. this.impx *= 0.95;
  96060. this.impy *= 0.95;
  96061. this.impz *= 0.95;
  96062. this.l1.x += this.impx * this.m1;
  96063. this.l1.y += this.impy * this.m1;
  96064. this.l1.z += this.impz * this.m1;
  96065. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  96066. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  96067. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  96068. this.l2.x -= this.impx * this.m2;
  96069. this.l2.y -= this.impy * this.m2;
  96070. this.l2.z -= this.impz * this.m2;
  96071. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  96072. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  96073. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  96074. },
  96075. solve: function () {
  96076. var d = this.dd.elements;
  96077. 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;
  96078. 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;
  96079. 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;
  96080. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  96081. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  96082. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96083. this.impx += nimpx;
  96084. this.impy += nimpy;
  96085. this.impz += nimpz;
  96086. this.l1.x += nimpx * this.m1;
  96087. this.l1.y += nimpy * this.m1;
  96088. this.l1.z += nimpz * this.m1;
  96089. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96090. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96091. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96092. this.l2.x -= nimpx * this.m2;
  96093. this.l2.y -= nimpy * this.m2;
  96094. this.l2.z -= nimpz * this.m2;
  96095. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96096. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96097. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96098. }
  96099. }
  96100. /**
  96101. * A three-axis rotational constraint for various joints.
  96102. * @author saharan
  96103. */
  96104. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96105. this.cfm1 = NaN;
  96106. this.cfm2 = NaN;
  96107. this.cfm3 = NaN;
  96108. this.i1e00 = NaN;
  96109. this.i1e01 = NaN;
  96110. this.i1e02 = NaN;
  96111. this.i1e10 = NaN;
  96112. this.i1e11 = NaN;
  96113. this.i1e12 = NaN;
  96114. this.i1e20 = NaN;
  96115. this.i1e21 = NaN;
  96116. this.i1e22 = NaN;
  96117. this.i2e00 = NaN;
  96118. this.i2e01 = NaN;
  96119. this.i2e02 = NaN;
  96120. this.i2e10 = NaN;
  96121. this.i2e11 = NaN;
  96122. this.i2e12 = NaN;
  96123. this.i2e20 = NaN;
  96124. this.i2e21 = NaN;
  96125. this.i2e22 = NaN;
  96126. this.ax1 = NaN;
  96127. this.ay1 = NaN;
  96128. this.az1 = NaN;
  96129. this.ax2 = NaN;
  96130. this.ay2 = NaN;
  96131. this.az2 = NaN;
  96132. this.ax3 = NaN;
  96133. this.ay3 = NaN;
  96134. this.az3 = NaN;
  96135. this.a1x1 = NaN; // jacoians
  96136. this.a1y1 = NaN;
  96137. this.a1z1 = NaN;
  96138. this.a2x1 = NaN;
  96139. this.a2y1 = NaN;
  96140. this.a2z1 = NaN;
  96141. this.a1x2 = NaN;
  96142. this.a1y2 = NaN;
  96143. this.a1z2 = NaN;
  96144. this.a2x2 = NaN;
  96145. this.a2y2 = NaN;
  96146. this.a2z2 = NaN;
  96147. this.a1x3 = NaN;
  96148. this.a1y3 = NaN;
  96149. this.a1z3 = NaN;
  96150. this.a2x3 = NaN;
  96151. this.a2y3 = NaN;
  96152. this.a2z3 = NaN;
  96153. this.lowerLimit1 = NaN;
  96154. this.upperLimit1 = NaN;
  96155. this.limitVelocity1 = NaN;
  96156. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96157. this.enableMotor1 = false;
  96158. this.motorSpeed1 = NaN;
  96159. this.maxMotorForce1 = NaN;
  96160. this.maxMotorImpulse1 = NaN;
  96161. this.lowerLimit2 = NaN;
  96162. this.upperLimit2 = NaN;
  96163. this.limitVelocity2 = NaN;
  96164. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96165. this.enableMotor2 = false;
  96166. this.motorSpeed2 = NaN;
  96167. this.maxMotorForce2 = NaN;
  96168. this.maxMotorImpulse2 = NaN;
  96169. this.lowerLimit3 = NaN;
  96170. this.upperLimit3 = NaN;
  96171. this.limitVelocity3 = NaN;
  96172. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96173. this.enableMotor3 = false;
  96174. this.motorSpeed3 = NaN;
  96175. this.maxMotorForce3 = NaN;
  96176. this.maxMotorImpulse3 = NaN;
  96177. this.k00 = NaN; // K = J*M*JT
  96178. this.k01 = NaN;
  96179. this.k02 = NaN;
  96180. this.k10 = NaN;
  96181. this.k11 = NaN;
  96182. this.k12 = NaN;
  96183. this.k20 = NaN;
  96184. this.k21 = NaN;
  96185. this.k22 = NaN;
  96186. this.kv00 = NaN; // diagonals without CFMs
  96187. this.kv11 = NaN;
  96188. this.kv22 = NaN;
  96189. this.dv00 = NaN; // ...inverted
  96190. this.dv11 = NaN;
  96191. this.dv22 = NaN;
  96192. this.d00 = NaN; // K^-1
  96193. this.d01 = NaN;
  96194. this.d02 = NaN;
  96195. this.d10 = NaN;
  96196. this.d11 = NaN;
  96197. this.d12 = NaN;
  96198. this.d20 = NaN;
  96199. this.d21 = NaN;
  96200. this.d22 = NaN;
  96201. this.limitMotor1 = limitMotor1;
  96202. this.limitMotor2 = limitMotor2;
  96203. this.limitMotor3 = limitMotor3;
  96204. this.b1 = joint.body1;
  96205. this.b2 = joint.body2;
  96206. this.a1 = this.b1.angularVelocity;
  96207. this.a2 = this.b2.angularVelocity;
  96208. this.i1 = this.b1.inverseInertia;
  96209. this.i2 = this.b2.inverseInertia;
  96210. this.limitImpulse1 = 0;
  96211. this.motorImpulse1 = 0;
  96212. this.limitImpulse2 = 0;
  96213. this.motorImpulse2 = 0;
  96214. this.limitImpulse3 = 0;
  96215. this.motorImpulse3 = 0;
  96216. }
  96217. OIMO.Rotational3Constraint.prototype = {
  96218. constructor: OIMO.Rotational3Constraint,
  96219. preSolve: function (timeStep, invTimeStep) {
  96220. this.ax1 = this.limitMotor1.axis.x;
  96221. this.ay1 = this.limitMotor1.axis.y;
  96222. this.az1 = this.limitMotor1.axis.z;
  96223. this.ax2 = this.limitMotor2.axis.x;
  96224. this.ay2 = this.limitMotor2.axis.y;
  96225. this.az2 = this.limitMotor2.axis.z;
  96226. this.ax3 = this.limitMotor3.axis.x;
  96227. this.ay3 = this.limitMotor3.axis.y;
  96228. this.az3 = this.limitMotor3.axis.z;
  96229. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96230. this.upperLimit1 = this.limitMotor1.upperLimit;
  96231. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96232. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96233. this.enableMotor1 = this.maxMotorForce1 > 0;
  96234. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96235. this.upperLimit2 = this.limitMotor2.upperLimit;
  96236. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96237. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96238. this.enableMotor2 = this.maxMotorForce2 > 0;
  96239. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96240. this.upperLimit3 = this.limitMotor3.upperLimit;
  96241. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96242. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96243. this.enableMotor3 = this.maxMotorForce3 > 0;
  96244. var ti1 = this.i1.elements;
  96245. var ti2 = this.i2.elements;
  96246. this.i1e00 = ti1[0];
  96247. this.i1e01 = ti1[1];
  96248. this.i1e02 = ti1[2];
  96249. this.i1e10 = ti1[3];
  96250. this.i1e11 = ti1[4];
  96251. this.i1e12 = ti1[5];
  96252. this.i1e20 = ti1[6];
  96253. this.i1e21 = ti1[7];
  96254. this.i1e22 = ti1[8];
  96255. this.i2e00 = ti2[0];
  96256. this.i2e01 = ti2[1];
  96257. this.i2e02 = ti2[2];
  96258. this.i2e10 = ti2[3];
  96259. this.i2e11 = ti2[4];
  96260. this.i2e12 = ti2[5];
  96261. this.i2e20 = ti2[6];
  96262. this.i2e21 = ti2[7];
  96263. this.i2e22 = ti2[8];
  96264. var frequency1 = this.limitMotor1.frequency;
  96265. var frequency2 = this.limitMotor2.frequency;
  96266. var frequency3 = this.limitMotor3.frequency;
  96267. var enableSpring1 = frequency1 > 0;
  96268. var enableSpring2 = frequency2 > 0;
  96269. var enableSpring3 = frequency3 > 0;
  96270. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96271. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96272. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96273. var angle1 = this.limitMotor1.angle;
  96274. if (enableLimit1) {
  96275. if (this.lowerLimit1 == this.upperLimit1) {
  96276. if (this.limitState1 != 0) {
  96277. this.limitState1 = 0;
  96278. this.limitImpulse1 = 0;
  96279. }
  96280. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96281. } else if (angle1 < this.lowerLimit1) {
  96282. if (this.limitState1 != -1) {
  96283. this.limitState1 = -1;
  96284. this.limitImpulse1 = 0;
  96285. }
  96286. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96287. } else if (angle1 > this.upperLimit1) {
  96288. if (this.limitState1 != 1) {
  96289. this.limitState1 = 1;
  96290. this.limitImpulse1 = 0;
  96291. }
  96292. this.limitVelocity1 = this.upperLimit1 - angle1;
  96293. } else {
  96294. this.limitState1 = 2;
  96295. this.limitImpulse1 = 0;
  96296. this.limitVelocity1 = 0;
  96297. }
  96298. if (!enableSpring1) {
  96299. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96300. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96301. else this.limitVelocity1 = 0;
  96302. }
  96303. } else {
  96304. this.limitState1 = 2;
  96305. this.limitImpulse1 = 0;
  96306. }
  96307. var angle2 = this.limitMotor2.angle;
  96308. if (enableLimit2) {
  96309. if (this.lowerLimit2 == this.upperLimit2) {
  96310. if (this.limitState2 != 0) {
  96311. this.limitState2 = 0;
  96312. this.limitImpulse2 = 0;
  96313. }
  96314. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96315. } else if (angle2 < this.lowerLimit2) {
  96316. if (this.limitState2 != -1) {
  96317. this.limitState2 = -1;
  96318. this.limitImpulse2 = 0;
  96319. }
  96320. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96321. } else if (angle2 > this.upperLimit2) {
  96322. if (this.limitState2 != 1) {
  96323. this.limitState2 = 1;
  96324. this.limitImpulse2 = 0;
  96325. }
  96326. this.limitVelocity2 = this.upperLimit2 - angle2;
  96327. } else {
  96328. this.limitState2 = 2;
  96329. this.limitImpulse2 = 0;
  96330. this.limitVelocity2 = 0;
  96331. }
  96332. if (!enableSpring2) {
  96333. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96334. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96335. else this.limitVelocity2 = 0;
  96336. }
  96337. } else {
  96338. this.limitState2 = 2;
  96339. this.limitImpulse2 = 0;
  96340. }
  96341. var angle3 = this.limitMotor3.angle;
  96342. if (enableLimit3) {
  96343. if (this.lowerLimit3 == this.upperLimit3) {
  96344. if (this.limitState3 != 0) {
  96345. this.limitState3 = 0;
  96346. this.limitImpulse3 = 0;
  96347. }
  96348. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96349. } else if (angle3 < this.lowerLimit3) {
  96350. if (this.limitState3 != -1) {
  96351. this.limitState3 = -1;
  96352. this.limitImpulse3 = 0;
  96353. }
  96354. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96355. } else if (angle3 > this.upperLimit3) {
  96356. if (this.limitState3 != 1) {
  96357. this.limitState3 = 1;
  96358. this.limitImpulse3 = 0;
  96359. }
  96360. this.limitVelocity3 = this.upperLimit3 - angle3;
  96361. } else {
  96362. this.limitState3 = 2;
  96363. this.limitImpulse3 = 0;
  96364. this.limitVelocity3 = 0;
  96365. }
  96366. if (!enableSpring3) {
  96367. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96368. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96369. else this.limitVelocity3 = 0;
  96370. }
  96371. } else {
  96372. this.limitState3 = 2;
  96373. this.limitImpulse3 = 0;
  96374. }
  96375. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96376. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96377. } else {
  96378. this.motorImpulse1 = 0;
  96379. this.maxMotorImpulse1 = 0;
  96380. }
  96381. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96382. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96383. } else {
  96384. this.motorImpulse2 = 0;
  96385. this.maxMotorImpulse2 = 0;
  96386. }
  96387. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96388. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96389. } else {
  96390. this.motorImpulse3 = 0;
  96391. this.maxMotorImpulse3 = 0;
  96392. }
  96393. // build jacobians
  96394. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96395. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96396. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96397. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96398. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96399. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96400. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96401. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96402. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96403. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96404. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96405. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96406. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96407. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96408. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96409. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96410. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96411. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96412. // build an impulse matrix
  96413. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96414. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96415. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96416. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96417. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96418. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96419. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96420. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96421. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96422. this.kv00 = this.k00;
  96423. this.kv11 = this.k11;
  96424. this.kv22 = this.k22;
  96425. this.dv00 = 1 / this.kv00;
  96426. this.dv11 = 1 / this.kv11;
  96427. this.dv22 = 1 / this.kv22;
  96428. if (enableSpring1 && this.limitState1 != 2) {
  96429. var omega = 6.2831853 * frequency1;
  96430. var k = omega * omega * timeStep;
  96431. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96432. this.cfm1 = this.kv00 * dmp;
  96433. this.limitVelocity1 *= k * dmp;
  96434. } else {
  96435. this.cfm1 = 0;
  96436. this.limitVelocity1 *= invTimeStep * 0.05;
  96437. }
  96438. if (enableSpring2 && this.limitState2 != 2) {
  96439. omega = 6.2831853 * frequency2;
  96440. k = omega * omega * timeStep;
  96441. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96442. this.cfm2 = this.kv11 * dmp;
  96443. this.limitVelocity2 *= k * dmp;
  96444. } else {
  96445. this.cfm2 = 0;
  96446. this.limitVelocity2 *= invTimeStep * 0.05;
  96447. }
  96448. if (enableSpring3 && this.limitState3 != 2) {
  96449. omega = 6.2831853 * frequency3;
  96450. k = omega * omega * timeStep;
  96451. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96452. this.cfm3 = this.kv22 * dmp;
  96453. this.limitVelocity3 *= k * dmp;
  96454. } else {
  96455. this.cfm3 = 0;
  96456. this.limitVelocity3 *= invTimeStep * 0.05;
  96457. }
  96458. this.k00 += this.cfm1;
  96459. this.k11 += this.cfm2;
  96460. this.k22 += this.cfm3;
  96461. var inv = 1 / (
  96462. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96463. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96464. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96465. );
  96466. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96467. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96468. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96469. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96470. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96471. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96472. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96473. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96474. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96475. this.limitImpulse1 *= 0.95;
  96476. this.motorImpulse1 *= 0.95;
  96477. this.limitImpulse2 *= 0.95;
  96478. this.motorImpulse2 *= 0.95;
  96479. this.limitImpulse3 *= 0.95;
  96480. this.motorImpulse3 *= 0.95;
  96481. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96482. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96483. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96484. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96485. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96486. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96487. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96488. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96489. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96490. },
  96491. solve_: function () {
  96492. var rvx = this.a2.x - this.a1.x;
  96493. var rvy = this.a2.y - this.a1.y;
  96494. var rvz = this.a2.z - this.a1.z;
  96495. this.limitVelocity3 = 30;
  96496. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96497. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96498. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96499. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96500. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96501. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96502. this.limitImpulse1 += dLimitImpulse1;
  96503. this.limitImpulse2 += dLimitImpulse2;
  96504. this.limitImpulse3 += dLimitImpulse3;
  96505. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96506. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96507. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96508. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96509. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96510. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96511. },
  96512. solve: function () {
  96513. var rvx = this.a2.x - this.a1.x;
  96514. var rvy = this.a2.y - this.a1.y;
  96515. var rvz = this.a2.z - this.a1.z;
  96516. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96517. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96518. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96519. var oldMotorImpulse1 = this.motorImpulse1;
  96520. var oldMotorImpulse2 = this.motorImpulse2;
  96521. var oldMotorImpulse3 = this.motorImpulse3;
  96522. var dMotorImpulse1 = 0;
  96523. var dMotorImpulse2 = 0;
  96524. var dMotorImpulse3 = 0;
  96525. if (this.enableMotor1) {
  96526. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96527. this.motorImpulse1 += dMotorImpulse1;
  96528. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96529. this.motorImpulse1 = this.maxMotorImpulse1;
  96530. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96531. this.motorImpulse1 = -this.maxMotorImpulse1;
  96532. }
  96533. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96534. }
  96535. if (this.enableMotor2) {
  96536. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96537. this.motorImpulse2 += dMotorImpulse2;
  96538. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96539. this.motorImpulse2 = this.maxMotorImpulse2;
  96540. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96541. this.motorImpulse2 = -this.maxMotorImpulse2;
  96542. }
  96543. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96544. }
  96545. if (this.enableMotor3) {
  96546. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96547. this.motorImpulse3 += dMotorImpulse3;
  96548. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96549. this.motorImpulse3 = this.maxMotorImpulse3;
  96550. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96551. this.motorImpulse3 = -this.maxMotorImpulse3;
  96552. }
  96553. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96554. }
  96555. // apply motor impulse to relative velocity
  96556. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96557. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96558. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96559. // subtract target velocity and applied impulse
  96560. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96561. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96562. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96563. var oldLimitImpulse1 = this.limitImpulse1;
  96564. var oldLimitImpulse2 = this.limitImpulse2;
  96565. var oldLimitImpulse3 = this.limitImpulse3;
  96566. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96567. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96568. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96569. this.limitImpulse1 += dLimitImpulse1;
  96570. this.limitImpulse2 += dLimitImpulse2;
  96571. this.limitImpulse3 += dLimitImpulse3;
  96572. // clamp
  96573. var clampState = 0;
  96574. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96575. dLimitImpulse1 = -oldLimitImpulse1;
  96576. rvn2 += dLimitImpulse1 * this.k10;
  96577. rvn3 += dLimitImpulse1 * this.k20;
  96578. clampState |= 1;
  96579. }
  96580. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96581. dLimitImpulse2 = -oldLimitImpulse2;
  96582. rvn1 += dLimitImpulse2 * this.k01;
  96583. rvn3 += dLimitImpulse2 * this.k21;
  96584. clampState |= 2;
  96585. }
  96586. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96587. dLimitImpulse3 = -oldLimitImpulse3;
  96588. rvn1 += dLimitImpulse3 * this.k02;
  96589. rvn2 += dLimitImpulse3 * this.k12;
  96590. clampState |= 4;
  96591. }
  96592. // update un-clamped impulse
  96593. // TODO: isolate division
  96594. var det;
  96595. switch (clampState) {
  96596. case 1: // update 2 3
  96597. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96598. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96599. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96600. break;
  96601. case 2: // update 1 3
  96602. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96603. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96604. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96605. break;
  96606. case 3: // update 3
  96607. dLimitImpulse3 = rvn3 / this.k22;
  96608. break;
  96609. case 4: // update 1 2
  96610. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96611. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96612. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96613. break;
  96614. case 5: // update 2
  96615. dLimitImpulse2 = rvn2 / this.k11;
  96616. break;
  96617. case 6: // update 1
  96618. dLimitImpulse1 = rvn1 / this.k00;
  96619. break;
  96620. }
  96621. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96622. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96623. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96624. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96625. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96626. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96627. // apply impulse
  96628. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96629. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96630. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96631. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96632. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96633. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96634. rvx = this.a2.x - this.a1.x;
  96635. rvy = this.a2.y - this.a1.y;
  96636. rvz = this.a2.z - this.a1.z;
  96637. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96638. }
  96639. }
  96640. /**
  96641. * A rotational constraint for various joints.
  96642. * @author saharan
  96643. */
  96644. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96645. this.cfm = NaN;
  96646. this.i1e00 = NaN;
  96647. this.i1e01 = NaN;
  96648. this.i1e02 = NaN;
  96649. this.i1e10 = NaN;
  96650. this.i1e11 = NaN;
  96651. this.i1e12 = NaN;
  96652. this.i1e20 = NaN;
  96653. this.i1e21 = NaN;
  96654. this.i1e22 = NaN;
  96655. this.i2e00 = NaN;
  96656. this.i2e01 = NaN;
  96657. this.i2e02 = NaN;
  96658. this.i2e10 = NaN;
  96659. this.i2e11 = NaN;
  96660. this.i2e12 = NaN;
  96661. this.i2e20 = NaN;
  96662. this.i2e21 = NaN;
  96663. this.i2e22 = NaN;
  96664. this.motorDenom = NaN;
  96665. this.invMotorDenom = NaN;
  96666. this.invDenom = NaN;
  96667. this.ax = NaN;
  96668. this.ay = NaN;
  96669. this.az = NaN;
  96670. this.a1x = NaN;
  96671. this.a1y = NaN;
  96672. this.a1z = NaN;
  96673. this.a2x = NaN;
  96674. this.a2y = NaN;
  96675. this.a2z = NaN;
  96676. this.enableLimit = false;
  96677. this.lowerLimit = NaN;
  96678. this.upperLimit = NaN;
  96679. this.limitVelocity = NaN;
  96680. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96681. this.enableMotor = false;
  96682. this.motorSpeed = NaN;
  96683. this.maxMotorForce = NaN;
  96684. this.maxMotorImpulse = NaN;
  96685. this.limitMotor = limitMotor;
  96686. this.b1 = joint.body1;
  96687. this.b2 = joint.body2;
  96688. this.a1 = this.b1.angularVelocity;
  96689. this.a2 = this.b2.angularVelocity;
  96690. this.i1 = this.b1.inverseInertia;
  96691. this.i2 = this.b2.inverseInertia;
  96692. this.limitImpulse = 0;
  96693. this.motorImpulse = 0;
  96694. }
  96695. OIMO.RotationalConstraint.prototype = {
  96696. constructor: OIMO.RotationalConstraint,
  96697. preSolve: function (timeStep, invTimeStep) {
  96698. this.ax = this.limitMotor.axis.x;
  96699. this.ay = this.limitMotor.axis.y;
  96700. this.az = this.limitMotor.axis.z;
  96701. this.lowerLimit = this.limitMotor.lowerLimit;
  96702. this.upperLimit = this.limitMotor.upperLimit;
  96703. this.motorSpeed = this.limitMotor.motorSpeed;
  96704. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96705. this.enableMotor = this.maxMotorForce > 0;
  96706. var ti1 = this.i1.elements;
  96707. var ti2 = this.i2.elements;
  96708. this.i1e00 = ti1[0];
  96709. this.i1e01 = ti1[1];
  96710. this.i1e02 = ti1[2];
  96711. this.i1e10 = ti1[3];
  96712. this.i1e11 = ti1[4];
  96713. this.i1e12 = ti1[5];
  96714. this.i1e20 = ti1[6];
  96715. this.i1e21 = ti1[7];
  96716. this.i1e22 = ti1[8];
  96717. this.i2e00 = ti2[0];
  96718. this.i2e01 = ti2[1];
  96719. this.i2e02 = ti2[2];
  96720. this.i2e10 = ti2[3];
  96721. this.i2e11 = ti2[4];
  96722. this.i2e12 = ti2[5];
  96723. this.i2e20 = ti2[6];
  96724. this.i2e21 = ti2[7];
  96725. this.i2e22 = ti2[8];
  96726. var frequency = this.limitMotor.frequency;
  96727. var enableSpring = frequency > 0;
  96728. var enableLimit = this.lowerLimit <= this.upperLimit;
  96729. var angle = this.limitMotor.angle;
  96730. if (enableLimit) {
  96731. if (this.lowerLimit == this.upperLimit) {
  96732. if (this.limitState != 0) {
  96733. this.limitState = 0;
  96734. this.limitImpulse = 0;
  96735. }
  96736. this.limitVelocity = this.lowerLimit - angle;
  96737. } else if (angle < this.lowerLimit) {
  96738. if (this.limitState != -1) {
  96739. this.limitState = -1;
  96740. this.limitImpulse = 0;
  96741. }
  96742. this.limitVelocity = this.lowerLimit - angle;
  96743. } else if (angle > this.upperLimit) {
  96744. if (this.limitState != 1) {
  96745. this.limitState = 1;
  96746. this.limitImpulse = 0;
  96747. }
  96748. this.limitVelocity = this.upperLimit - angle;
  96749. } else {
  96750. this.limitState = 2;
  96751. this.limitImpulse = 0;
  96752. this.limitVelocity = 0;
  96753. }
  96754. if (!enableSpring) {
  96755. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96756. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96757. else this.limitVelocity = 0;
  96758. }
  96759. } else {
  96760. this.limitState = 2;
  96761. this.limitImpulse = 0;
  96762. }
  96763. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96764. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96765. } else {
  96766. this.motorImpulse = 0;
  96767. this.maxMotorImpulse = 0;
  96768. }
  96769. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96770. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96771. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96772. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96773. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96774. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96775. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96776. this.invMotorDenom = 1 / this.motorDenom;
  96777. if (enableSpring && this.limitState != 2) {
  96778. var omega = 6.2831853 * frequency;
  96779. var k = omega * omega * timeStep;
  96780. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96781. this.cfm = this.motorDenom * dmp;
  96782. this.limitVelocity *= k * dmp;
  96783. } else {
  96784. this.cfm = 0;
  96785. this.limitVelocity *= invTimeStep * 0.05;
  96786. }
  96787. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96788. this.limitImpulse *= 0.95;
  96789. this.motorImpulse *= 0.95;
  96790. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96791. this.a1.x += totalImpulse * this.a1x;
  96792. this.a1.y += totalImpulse * this.a1y;
  96793. this.a1.z += totalImpulse * this.a1z;
  96794. this.a2.x -= totalImpulse * this.a2x;
  96795. this.a2.y -= totalImpulse * this.a2y;
  96796. this.a2.z -= totalImpulse * this.a2z;
  96797. },
  96798. solve: function () {
  96799. 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);
  96800. // motor part
  96801. var newMotorImpulse;
  96802. if (this.enableMotor) {
  96803. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96804. var oldMotorImpulse = this.motorImpulse;
  96805. this.motorImpulse += newMotorImpulse;
  96806. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96807. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96808. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96809. rvn -= newMotorImpulse * this.motorDenom;
  96810. } else newMotorImpulse = 0;
  96811. // limit part
  96812. var newLimitImpulse;
  96813. if (this.limitState != 2) {
  96814. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96815. var oldLimitImpulse = this.limitImpulse;
  96816. this.limitImpulse += newLimitImpulse;
  96817. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96818. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96819. } else newLimitImpulse = 0;
  96820. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96821. this.a1.x += totalImpulse * this.a1x;
  96822. this.a1.y += totalImpulse * this.a1y;
  96823. this.a1.z += totalImpulse * this.a1z;
  96824. this.a2.x -= totalImpulse * this.a2x;
  96825. this.a2.y -= totalImpulse * this.a2y;
  96826. this.a2.z -= totalImpulse * this.a2z;
  96827. }
  96828. }
  96829. /**
  96830. * A three-axis translational constraint for various joints.
  96831. * @author saharan
  96832. */
  96833. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96834. this.m1 = NaN;
  96835. this.m2 = NaN;
  96836. this.i1e00 = NaN;
  96837. this.i1e01 = NaN;
  96838. this.i1e02 = NaN;
  96839. this.i1e10 = NaN;
  96840. this.i1e11 = NaN;
  96841. this.i1e12 = NaN;
  96842. this.i1e20 = NaN;
  96843. this.i1e21 = NaN;
  96844. this.i1e22 = NaN;
  96845. this.i2e00 = NaN;
  96846. this.i2e01 = NaN;
  96847. this.i2e02 = NaN;
  96848. this.i2e10 = NaN;
  96849. this.i2e11 = NaN;
  96850. this.i2e12 = NaN;
  96851. this.i2e20 = NaN;
  96852. this.i2e21 = NaN;
  96853. this.i2e22 = NaN;
  96854. this.ax1 = NaN;
  96855. this.ay1 = NaN;
  96856. this.az1 = NaN;
  96857. this.ax2 = NaN;
  96858. this.ay2 = NaN;
  96859. this.az2 = NaN;
  96860. this.ax3 = NaN;
  96861. this.ay3 = NaN;
  96862. this.az3 = NaN;
  96863. this.r1x = NaN;
  96864. this.r1y = NaN;
  96865. this.r1z = NaN;
  96866. this.r2x = NaN;
  96867. this.r2y = NaN;
  96868. this.r2z = NaN;
  96869. this.t1x1 = NaN;// jacobians
  96870. this.t1y1 = NaN;
  96871. this.t1z1 = NaN;
  96872. this.t2x1 = NaN;
  96873. this.t2y1 = NaN;
  96874. this.t2z1 = NaN;
  96875. this.l1x1 = NaN;
  96876. this.l1y1 = NaN;
  96877. this.l1z1 = NaN;
  96878. this.l2x1 = NaN;
  96879. this.l2y1 = NaN;
  96880. this.l2z1 = NaN;
  96881. this.a1x1 = NaN;
  96882. this.a1y1 = NaN;
  96883. this.a1z1 = NaN;
  96884. this.a2x1 = NaN;
  96885. this.a2y1 = NaN;
  96886. this.a2z1 = NaN;
  96887. this.t1x2 = NaN;
  96888. this.t1y2 = NaN;
  96889. this.t1z2 = NaN;
  96890. this.t2x2 = NaN;
  96891. this.t2y2 = NaN;
  96892. this.t2z2 = NaN;
  96893. this.l1x2 = NaN;
  96894. this.l1y2 = NaN;
  96895. this.l1z2 = NaN;
  96896. this.l2x2 = NaN;
  96897. this.l2y2 = NaN;
  96898. this.l2z2 = NaN;
  96899. this.a1x2 = NaN;
  96900. this.a1y2 = NaN;
  96901. this.a1z2 = NaN;
  96902. this.a2x2 = NaN;
  96903. this.a2y2 = NaN;
  96904. this.a2z2 = NaN;
  96905. this.t1x3 = NaN;
  96906. this.t1y3 = NaN;
  96907. this.t1z3 = NaN;
  96908. this.t2x3 = NaN;
  96909. this.t2y3 = NaN;
  96910. this.t2z3 = NaN;
  96911. this.l1x3 = NaN;
  96912. this.l1y3 = NaN;
  96913. this.l1z3 = NaN;
  96914. this.l2x3 = NaN;
  96915. this.l2y3 = NaN;
  96916. this.l2z3 = NaN;
  96917. this.a1x3 = NaN;
  96918. this.a1y3 = NaN;
  96919. this.a1z3 = NaN;
  96920. this.a2x3 = NaN;
  96921. this.a2y3 = NaN;
  96922. this.a2z3 = NaN;
  96923. this.lowerLimit1 = NaN;
  96924. this.upperLimit1 = NaN;
  96925. this.limitVelocity1 = NaN;
  96926. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96927. this.enableMotor1 = false;
  96928. this.motorSpeed1 = NaN;
  96929. this.maxMotorForce1 = NaN;
  96930. this.maxMotorImpulse1 = NaN;
  96931. this.lowerLimit2 = NaN;
  96932. this.upperLimit2 = NaN;
  96933. this.limitVelocity2 = NaN;
  96934. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96935. this.enableMotor2 = false;
  96936. this.motorSpeed2 = NaN;
  96937. this.maxMotorForce2 = NaN;
  96938. this.maxMotorImpulse2 = NaN;
  96939. this.lowerLimit3 = NaN;
  96940. this.upperLimit3 = NaN;
  96941. this.limitVelocity3 = NaN;
  96942. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96943. this.enableMotor3 = false;
  96944. this.motorSpeed3 = NaN;
  96945. this.maxMotorForce3 = NaN;
  96946. this.maxMotorImpulse3 = NaN;
  96947. this.k00 = NaN; // K = J*M*JT
  96948. this.k01 = NaN;
  96949. this.k02 = NaN;
  96950. this.k10 = NaN;
  96951. this.k11 = NaN;
  96952. this.k12 = NaN;
  96953. this.k20 = NaN;
  96954. this.k21 = NaN;
  96955. this.k22 = NaN;
  96956. this.kv00 = NaN; // diagonals without CFMs
  96957. this.kv11 = NaN;
  96958. this.kv22 = NaN;
  96959. this.dv00 = NaN; // ...inverted
  96960. this.dv11 = NaN;
  96961. this.dv22 = NaN;
  96962. this.d00 = NaN; // K^-1
  96963. this.d01 = NaN;
  96964. this.d02 = NaN;
  96965. this.d10 = NaN;
  96966. this.d11 = NaN;
  96967. this.d12 = NaN;
  96968. this.d20 = NaN;
  96969. this.d21 = NaN;
  96970. this.d22 = NaN;
  96971. this.limitMotor1 = limitMotor1;
  96972. this.limitMotor2 = limitMotor2;
  96973. this.limitMotor3 = limitMotor3;
  96974. this.b1 = joint.body1;
  96975. this.b2 = joint.body2;
  96976. this.p1 = joint.anchorPoint1;
  96977. this.p2 = joint.anchorPoint2;
  96978. this.r1 = joint.relativeAnchorPoint1;
  96979. this.r2 = joint.relativeAnchorPoint2;
  96980. this.l1 = this.b1.linearVelocity;
  96981. this.l2 = this.b2.linearVelocity;
  96982. this.a1 = this.b1.angularVelocity;
  96983. this.a2 = this.b2.angularVelocity;
  96984. this.i1 = this.b1.inverseInertia;
  96985. this.i2 = this.b2.inverseInertia;
  96986. this.limitImpulse1 = 0;
  96987. this.motorImpulse1 = 0;
  96988. this.limitImpulse2 = 0;
  96989. this.motorImpulse2 = 0;
  96990. this.limitImpulse3 = 0;
  96991. this.motorImpulse3 = 0;
  96992. this.cfm1 = 0;// Constraint Force Mixing
  96993. this.cfm2 = 0;
  96994. this.cfm3 = 0;
  96995. this.weight = -1;
  96996. }
  96997. OIMO.Translational3Constraint.prototype = {
  96998. constructor: OIMO.Translational3Constraint,
  96999. preSolve: function (timeStep, invTimeStep) {
  97000. this.ax1 = this.limitMotor1.axis.x;
  97001. this.ay1 = this.limitMotor1.axis.y;
  97002. this.az1 = this.limitMotor1.axis.z;
  97003. this.ax2 = this.limitMotor2.axis.x;
  97004. this.ay2 = this.limitMotor2.axis.y;
  97005. this.az2 = this.limitMotor2.axis.z;
  97006. this.ax3 = this.limitMotor3.axis.x;
  97007. this.ay3 = this.limitMotor3.axis.y;
  97008. this.az3 = this.limitMotor3.axis.z;
  97009. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97010. this.upperLimit1 = this.limitMotor1.upperLimit;
  97011. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97012. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97013. this.enableMotor1 = this.maxMotorForce1 > 0;
  97014. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97015. this.upperLimit2 = this.limitMotor2.upperLimit;
  97016. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97017. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97018. this.enableMotor2 = this.maxMotorForce2 > 0;
  97019. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97020. this.upperLimit3 = this.limitMotor3.upperLimit;
  97021. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97022. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97023. this.enableMotor3 = this.maxMotorForce3 > 0;
  97024. this.m1 = this.b1.inverseMass;
  97025. this.m2 = this.b2.inverseMass;
  97026. var ti1 = this.i1.elements;
  97027. var ti2 = this.i2.elements;
  97028. this.i1e00 = ti1[0];
  97029. this.i1e01 = ti1[1];
  97030. this.i1e02 = ti1[2];
  97031. this.i1e10 = ti1[3];
  97032. this.i1e11 = ti1[4];
  97033. this.i1e12 = ti1[5];
  97034. this.i1e20 = ti1[6];
  97035. this.i1e21 = ti1[7];
  97036. this.i1e22 = ti1[8];
  97037. this.i2e00 = ti2[0];
  97038. this.i2e01 = ti2[1];
  97039. this.i2e02 = ti2[2];
  97040. this.i2e10 = ti2[3];
  97041. this.i2e11 = ti2[4];
  97042. this.i2e12 = ti2[5];
  97043. this.i2e20 = ti2[6];
  97044. this.i2e21 = ti2[7];
  97045. this.i2e22 = ti2[8];
  97046. var dx = this.p2.x - this.p1.x;
  97047. var dy = this.p2.y - this.p1.y;
  97048. var dz = this.p2.z - this.p1.z;
  97049. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  97050. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  97051. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  97052. var frequency1 = this.limitMotor1.frequency;
  97053. var frequency2 = this.limitMotor2.frequency;
  97054. var frequency3 = this.limitMotor3.frequency;
  97055. var enableSpring1 = frequency1 > 0;
  97056. var enableSpring2 = frequency2 > 0;
  97057. var enableSpring3 = frequency3 > 0;
  97058. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97059. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97060. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97061. // for stability
  97062. if (enableSpring1 && d1 > 20 || d1 < -20) {
  97063. enableSpring1 = false;
  97064. }
  97065. if (enableSpring2 && d2 > 20 || d2 < -20) {
  97066. enableSpring2 = false;
  97067. }
  97068. if (enableSpring3 && d3 > 20 || d3 < -20) {
  97069. enableSpring3 = false;
  97070. }
  97071. if (enableLimit1) {
  97072. if (this.lowerLimit1 == this.upperLimit1) {
  97073. if (this.limitState1 != 0) {
  97074. this.limitState1 = 0;
  97075. this.limitImpulse1 = 0;
  97076. }
  97077. this.limitVelocity1 = this.lowerLimit1 - d1;
  97078. if (!enableSpring1) d1 = this.lowerLimit1;
  97079. } else if (d1 < this.lowerLimit1) {
  97080. if (this.limitState1 != -1) {
  97081. this.limitState1 = -1;
  97082. this.limitImpulse1 = 0;
  97083. }
  97084. this.limitVelocity1 = this.lowerLimit1 - d1;
  97085. if (!enableSpring1) d1 = this.lowerLimit1;
  97086. } else if (d1 > this.upperLimit1) {
  97087. if (this.limitState1 != 1) {
  97088. this.limitState1 = 1;
  97089. this.limitImpulse1 = 0;
  97090. }
  97091. this.limitVelocity1 = this.upperLimit1 - d1;
  97092. if (!enableSpring1) d1 = this.upperLimit1;
  97093. } else {
  97094. this.limitState1 = 2;
  97095. this.limitImpulse1 = 0;
  97096. this.limitVelocity1 = 0;
  97097. }
  97098. if (!enableSpring1) {
  97099. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97100. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97101. else this.limitVelocity1 = 0;
  97102. }
  97103. } else {
  97104. this.limitState1 = 2;
  97105. this.limitImpulse1 = 0;
  97106. }
  97107. if (enableLimit2) {
  97108. if (this.lowerLimit2 == this.upperLimit2) {
  97109. if (this.limitState2 != 0) {
  97110. this.limitState2 = 0;
  97111. this.limitImpulse2 = 0;
  97112. }
  97113. this.limitVelocity2 = this.lowerLimit2 - d2;
  97114. if (!enableSpring2) d2 = this.lowerLimit2;
  97115. } else if (d2 < this.lowerLimit2) {
  97116. if (this.limitState2 != -1) {
  97117. this.limitState2 = -1;
  97118. this.limitImpulse2 = 0;
  97119. }
  97120. this.limitVelocity2 = this.lowerLimit2 - d2;
  97121. if (!enableSpring2) d2 = this.lowerLimit2;
  97122. } else if (d2 > this.upperLimit2) {
  97123. if (this.limitState2 != 1) {
  97124. this.limitState2 = 1;
  97125. this.limitImpulse2 = 0;
  97126. }
  97127. this.limitVelocity2 = this.upperLimit2 - d2;
  97128. if (!enableSpring2) d2 = this.upperLimit2;
  97129. } else {
  97130. this.limitState2 = 2;
  97131. this.limitImpulse2 = 0;
  97132. this.limitVelocity2 = 0;
  97133. }
  97134. if (!enableSpring2) {
  97135. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97136. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97137. else this.limitVelocity2 = 0;
  97138. }
  97139. } else {
  97140. this.limitState2 = 2;
  97141. this.limitImpulse2 = 0;
  97142. }
  97143. if (enableLimit3) {
  97144. if (this.lowerLimit3 == this.upperLimit3) {
  97145. if (this.limitState3 != 0) {
  97146. this.limitState3 = 0;
  97147. this.limitImpulse3 = 0;
  97148. }
  97149. this.limitVelocity3 = this.lowerLimit3 - d3;
  97150. if (!enableSpring3) d3 = this.lowerLimit3;
  97151. } else if (d3 < this.lowerLimit3) {
  97152. if (this.limitState3 != -1) {
  97153. this.limitState3 = -1;
  97154. this.limitImpulse3 = 0;
  97155. }
  97156. this.limitVelocity3 = this.lowerLimit3 - d3;
  97157. if (!enableSpring3) d3 = this.lowerLimit3;
  97158. } else if (d3 > this.upperLimit3) {
  97159. if (this.limitState3 != 1) {
  97160. this.limitState3 = 1;
  97161. this.limitImpulse3 = 0;
  97162. }
  97163. this.limitVelocity3 = this.upperLimit3 - d3;
  97164. if (!enableSpring3) d3 = this.upperLimit3;
  97165. } else {
  97166. this.limitState3 = 2;
  97167. this.limitImpulse3 = 0;
  97168. this.limitVelocity3 = 0;
  97169. }
  97170. if (!enableSpring3) {
  97171. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97172. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97173. else this.limitVelocity3 = 0;
  97174. }
  97175. } else {
  97176. this.limitState3 = 2;
  97177. this.limitImpulse3 = 0;
  97178. }
  97179. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97180. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97181. } else {
  97182. this.motorImpulse1 = 0;
  97183. this.maxMotorImpulse1 = 0;
  97184. }
  97185. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97186. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97187. } else {
  97188. this.motorImpulse2 = 0;
  97189. this.maxMotorImpulse2 = 0;
  97190. }
  97191. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97192. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97193. } else {
  97194. this.motorImpulse3 = 0;
  97195. this.maxMotorImpulse3 = 0;
  97196. }
  97197. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97198. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97199. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97200. var w1 = this.m2 / (this.m1 + this.m2);
  97201. if (this.weight >= 0) w1 = this.weight; // use given weight
  97202. var w2 = 1 - w1;
  97203. this.r1x = this.r1.x + rdx * w1;
  97204. this.r1y = this.r1.y + rdy * w1;
  97205. this.r1z = this.r1.z + rdz * w1;
  97206. this.r2x = this.r2.x - rdx * w2;
  97207. this.r2y = this.r2.y - rdy * w2;
  97208. this.r2z = this.r2.z - rdz * w2;
  97209. // build jacobians
  97210. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97211. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97212. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97213. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97214. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97215. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97216. this.l1x1 = this.ax1 * this.m1;
  97217. this.l1y1 = this.ay1 * this.m1;
  97218. this.l1z1 = this.az1 * this.m1;
  97219. this.l2x1 = this.ax1 * this.m2;
  97220. this.l2y1 = this.ay1 * this.m2;
  97221. this.l2z1 = this.az1 * this.m2;
  97222. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97223. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97224. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97225. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97226. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97227. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97228. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97229. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97230. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97231. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97232. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97233. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97234. this.l1x2 = this.ax2 * this.m1;
  97235. this.l1y2 = this.ay2 * this.m1;
  97236. this.l1z2 = this.az2 * this.m1;
  97237. this.l2x2 = this.ax2 * this.m2;
  97238. this.l2y2 = this.ay2 * this.m2;
  97239. this.l2z2 = this.az2 * this.m2;
  97240. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97241. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97242. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97243. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97244. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97245. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97246. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97247. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97248. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97249. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97250. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97251. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97252. this.l1x3 = this.ax3 * this.m1;
  97253. this.l1y3 = this.ay3 * this.m1;
  97254. this.l1z3 = this.az3 * this.m1;
  97255. this.l2x3 = this.ax3 * this.m2;
  97256. this.l2y3 = this.ay3 * this.m2;
  97257. this.l2z3 = this.az3 * this.m2;
  97258. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97259. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97260. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97261. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97262. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97263. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97264. // build an impulse matrix
  97265. var m12 = this.m1 + this.m2;
  97266. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97267. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97268. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97269. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97270. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97271. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97272. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97273. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97274. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97275. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97276. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97277. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97278. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97279. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97280. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97281. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97282. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97283. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97284. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97285. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97286. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97287. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97288. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97289. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97290. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97291. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97292. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97293. this.kv00 = this.k00;
  97294. this.kv11 = this.k11;
  97295. this.kv22 = this.k22;
  97296. this.dv00 = 1 / this.kv00;
  97297. this.dv11 = 1 / this.kv11;
  97298. this.dv22 = 1 / this.kv22;
  97299. if (enableSpring1 && this.limitState1 != 2) {
  97300. var omega = 6.2831853 * frequency1;
  97301. var k = omega * omega * timeStep;
  97302. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97303. this.cfm1 = this.kv00 * dmp;
  97304. this.limitVelocity1 *= k * dmp;
  97305. } else {
  97306. this.cfm1 = 0;
  97307. this.limitVelocity1 *= invTimeStep * 0.05;
  97308. }
  97309. if (enableSpring2 && this.limitState2 != 2) {
  97310. omega = 6.2831853 * frequency2;
  97311. k = omega * omega * timeStep;
  97312. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97313. this.cfm2 = this.kv11 * dmp;
  97314. this.limitVelocity2 *= k * dmp;
  97315. } else {
  97316. this.cfm2 = 0;
  97317. this.limitVelocity2 *= invTimeStep * 0.05;
  97318. }
  97319. if (enableSpring3 && this.limitState3 != 2) {
  97320. omega = 6.2831853 * frequency3;
  97321. k = omega * omega * timeStep;
  97322. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97323. this.cfm3 = this.kv22 * dmp;
  97324. this.limitVelocity3 *= k * dmp;
  97325. } else {
  97326. this.cfm3 = 0;
  97327. this.limitVelocity3 *= invTimeStep * 0.05;
  97328. }
  97329. this.k00 += this.cfm1;
  97330. this.k11 += this.cfm2;
  97331. this.k22 += this.cfm3;
  97332. var inv = 1 / (
  97333. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97334. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97335. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97336. );
  97337. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97338. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97339. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97340. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97341. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97342. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97343. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97344. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97345. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97346. // warm starting
  97347. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97348. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97349. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97350. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97351. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97352. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97353. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97354. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97355. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97356. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97357. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97358. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97359. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97360. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97361. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97362. },
  97363. solve: function () {
  97364. 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;
  97365. 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;
  97366. 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;
  97367. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97368. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97369. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97370. var oldMotorImpulse1 = this.motorImpulse1;
  97371. var oldMotorImpulse2 = this.motorImpulse2;
  97372. var oldMotorImpulse3 = this.motorImpulse3;
  97373. var dMotorImpulse1 = 0;
  97374. var dMotorImpulse2 = 0;
  97375. var dMotorImpulse3 = 0;
  97376. if (this.enableMotor1) {
  97377. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97378. this.motorImpulse1 += dMotorImpulse1;
  97379. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97380. this.motorImpulse1 = this.maxMotorImpulse1;
  97381. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97382. this.motorImpulse1 = -this.maxMotorImpulse1;
  97383. }
  97384. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97385. }
  97386. if (this.enableMotor2) {
  97387. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97388. this.motorImpulse2 += dMotorImpulse2;
  97389. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97390. this.motorImpulse2 = this.maxMotorImpulse2;
  97391. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97392. this.motorImpulse2 = -this.maxMotorImpulse2;
  97393. }
  97394. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97395. }
  97396. if (this.enableMotor3) {
  97397. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97398. this.motorImpulse3 += dMotorImpulse3;
  97399. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97400. this.motorImpulse3 = this.maxMotorImpulse3;
  97401. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97402. this.motorImpulse3 = -this.maxMotorImpulse3;
  97403. }
  97404. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97405. }
  97406. // apply motor impulse to relative velocity
  97407. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97408. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97409. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97410. // subtract target velocity and applied impulse
  97411. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97412. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97413. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97414. var oldLimitImpulse1 = this.limitImpulse1;
  97415. var oldLimitImpulse2 = this.limitImpulse2;
  97416. var oldLimitImpulse3 = this.limitImpulse3;
  97417. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97418. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97419. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97420. this.limitImpulse1 += dLimitImpulse1;
  97421. this.limitImpulse2 += dLimitImpulse2;
  97422. this.limitImpulse3 += dLimitImpulse3;
  97423. // clamp
  97424. var clampState = 0;
  97425. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97426. dLimitImpulse1 = -oldLimitImpulse1;
  97427. rvn2 += dLimitImpulse1 * this.k10;
  97428. rvn3 += dLimitImpulse1 * this.k20;
  97429. clampState |= 1;
  97430. }
  97431. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97432. dLimitImpulse2 = -oldLimitImpulse2;
  97433. rvn1 += dLimitImpulse2 * this.k01;
  97434. rvn3 += dLimitImpulse2 * this.k21;
  97435. clampState |= 2;
  97436. }
  97437. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97438. dLimitImpulse3 = -oldLimitImpulse3;
  97439. rvn1 += dLimitImpulse3 * this.k02;
  97440. rvn2 += dLimitImpulse3 * this.k12;
  97441. clampState |= 4;
  97442. }
  97443. // update un-clamped impulse
  97444. // TODO: isolate division
  97445. var det;
  97446. switch (clampState) {
  97447. case 1:// update 2 3
  97448. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97449. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97450. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97451. break;
  97452. case 2:// update 1 3
  97453. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97454. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97455. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97456. break;
  97457. case 3:// update 3
  97458. dLimitImpulse3 = rvn3 / this.k22;
  97459. break;
  97460. case 4:// update 1 2
  97461. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97462. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97463. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97464. break;
  97465. case 5:// update 2
  97466. dLimitImpulse2 = rvn2 / this.k11;
  97467. break;
  97468. case 6:// update 1
  97469. dLimitImpulse1 = rvn1 / this.k00;
  97470. break;
  97471. }
  97472. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97473. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97474. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97475. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97476. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97477. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97478. // apply impulse
  97479. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97480. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97481. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97482. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97483. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97484. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97485. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97486. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97487. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97488. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97489. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97490. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97491. }
  97492. }
  97493. /**
  97494. * A translational constraint for various joints.
  97495. * @author saharan
  97496. */
  97497. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97498. this.cfm = NaN;
  97499. this.m1 = NaN;
  97500. this.m2 = NaN;
  97501. this.i1e00 = NaN;
  97502. this.i1e01 = NaN;
  97503. this.i1e02 = NaN;
  97504. this.i1e10 = NaN;
  97505. this.i1e11 = NaN;
  97506. this.i1e12 = NaN;
  97507. this.i1e20 = NaN;
  97508. this.i1e21 = NaN;
  97509. this.i1e22 = NaN;
  97510. this.i2e00 = NaN;
  97511. this.i2e01 = NaN;
  97512. this.i2e02 = NaN;
  97513. this.i2e10 = NaN;
  97514. this.i2e11 = NaN;
  97515. this.i2e12 = NaN;
  97516. this.i2e20 = NaN;
  97517. this.i2e21 = NaN;
  97518. this.i2e22 = NaN;
  97519. this.motorDenom = NaN;
  97520. this.invMotorDenom = NaN;
  97521. this.invDenom = NaN;
  97522. this.ax = NaN;
  97523. this.ay = NaN;
  97524. this.az = NaN;
  97525. this.r1x = NaN;
  97526. this.r1y = NaN;
  97527. this.r1z = NaN;
  97528. this.r2x = NaN;
  97529. this.r2y = NaN;
  97530. this.r2z = NaN;
  97531. this.t1x = NaN;
  97532. this.t1y = NaN;
  97533. this.t1z = NaN;
  97534. this.t2x = NaN;
  97535. this.t2y = NaN;
  97536. this.t2z = NaN;
  97537. this.l1x = NaN;
  97538. this.l1y = NaN;
  97539. this.l1z = NaN;
  97540. this.l2x = NaN;
  97541. this.l2y = NaN;
  97542. this.l2z = NaN;
  97543. this.a1x = NaN;
  97544. this.a1y = NaN;
  97545. this.a1z = NaN;
  97546. this.a2x = NaN;
  97547. this.a2y = NaN;
  97548. this.a2z = NaN;
  97549. this.lowerLimit = NaN;
  97550. this.upperLimit = NaN;
  97551. this.limitVelocity = NaN;
  97552. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97553. this.enableMotor = false;
  97554. this.motorSpeed = NaN;
  97555. this.maxMotorForce = NaN;
  97556. this.maxMotorImpulse = NaN;
  97557. this.limitMotor = limitMotor;
  97558. this.b1 = joint.body1;
  97559. this.b2 = joint.body2;
  97560. this.p1 = joint.anchorPoint1;
  97561. this.p2 = joint.anchorPoint2;
  97562. this.r1 = joint.relativeAnchorPoint1;
  97563. this.r2 = joint.relativeAnchorPoint2;
  97564. this.l1 = this.b1.linearVelocity;
  97565. this.l2 = this.b2.linearVelocity;
  97566. this.a1 = this.b1.angularVelocity;
  97567. this.a2 = this.b2.angularVelocity;
  97568. this.i1 = this.b1.inverseInertia;
  97569. this.i2 = this.b2.inverseInertia;
  97570. this.limitImpulse = 0;
  97571. this.motorImpulse = 0;
  97572. }
  97573. OIMO.TranslationalConstraint.prototype = {
  97574. constructor: OIMO.TranslationalConstraint,
  97575. preSolve: function (timeStep, invTimeStep) {
  97576. this.ax = this.limitMotor.axis.x;
  97577. this.ay = this.limitMotor.axis.y;
  97578. this.az = this.limitMotor.axis.z;
  97579. this.lowerLimit = this.limitMotor.lowerLimit;
  97580. this.upperLimit = this.limitMotor.upperLimit;
  97581. this.motorSpeed = this.limitMotor.motorSpeed;
  97582. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97583. this.enableMotor = this.maxMotorForce > 0;
  97584. this.m1 = this.b1.inverseMass;
  97585. this.m2 = this.b2.inverseMass;
  97586. var ti1 = this.i1.elements;
  97587. var ti2 = this.i2.elements;
  97588. this.i1e00 = ti1[0];
  97589. this.i1e01 = ti1[1];
  97590. this.i1e02 = ti1[2];
  97591. this.i1e10 = ti1[3];
  97592. this.i1e11 = ti1[4];
  97593. this.i1e12 = ti1[5];
  97594. this.i1e20 = ti1[6];
  97595. this.i1e21 = ti1[7];
  97596. this.i1e22 = ti1[8];
  97597. this.i2e00 = ti2[0];
  97598. this.i2e01 = ti2[1];
  97599. this.i2e02 = ti2[2];
  97600. this.i2e10 = ti2[3];
  97601. this.i2e11 = ti2[4];
  97602. this.i2e12 = ti2[5];
  97603. this.i2e20 = ti2[6];
  97604. this.i2e21 = ti2[7];
  97605. this.i2e22 = ti2[8];
  97606. var dx = this.p2.x - this.p1.x;
  97607. var dy = this.p2.y - this.p1.y;
  97608. var dz = this.p2.z - this.p1.z;
  97609. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97610. var frequency = this.limitMotor.frequency;
  97611. var enableSpring = frequency > 0;
  97612. var enableLimit = this.lowerLimit <= this.upperLimit;
  97613. if (enableSpring && d > 20 || d < -20) {
  97614. enableSpring = false;
  97615. }
  97616. if (enableLimit) {
  97617. if (this.lowerLimit == this.upperLimit) {
  97618. if (this.limitState != 0) {
  97619. this.limitState = 0;
  97620. this.limitImpulse = 0;
  97621. }
  97622. this.limitVelocity = this.lowerLimit - d;
  97623. if (!enableSpring) d = this.lowerLimit;
  97624. } else if (d < this.lowerLimit) {
  97625. if (this.limitState != -1) {
  97626. this.limitState = -1;
  97627. this.limitImpulse = 0;
  97628. }
  97629. this.limitVelocity = this.lowerLimit - d;
  97630. if (!enableSpring) d = this.lowerLimit;
  97631. } else if (d > this.upperLimit) {
  97632. if (this.limitState != 1) {
  97633. this.limitState = 1;
  97634. this.limitImpulse = 0;
  97635. }
  97636. this.limitVelocity = this.upperLimit - d;
  97637. if (!enableSpring) d = this.upperLimit;
  97638. } else {
  97639. this.limitState = 2;
  97640. this.limitImpulse = 0;
  97641. this.limitVelocity = 0;
  97642. }
  97643. if (!enableSpring) {
  97644. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97645. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97646. else this.limitVelocity = 0;
  97647. }
  97648. } else {
  97649. this.limitState = 2;
  97650. this.limitImpulse = 0;
  97651. }
  97652. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97653. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97654. } else {
  97655. this.motorImpulse = 0;
  97656. this.maxMotorImpulse = 0;
  97657. }
  97658. var rdx = d * this.ax;
  97659. var rdy = d * this.ay;
  97660. var rdz = d * this.az;
  97661. var w1 = this.m1 / (this.m1 + this.m2);
  97662. var w2 = 1 - w1;
  97663. this.r1x = this.r1.x + rdx * w1;
  97664. this.r1y = this.r1.y + rdy * w1;
  97665. this.r1z = this.r1.z + rdz * w1;
  97666. this.r2x = this.r2.x - rdx * w2;
  97667. this.r2y = this.r2.y - rdy * w2;
  97668. this.r2z = this.r2.z - rdz * w2;
  97669. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97670. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97671. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97672. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97673. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97674. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97675. this.l1x = this.ax * this.m1;
  97676. this.l1y = this.ay * this.m1;
  97677. this.l1z = this.az * this.m1;
  97678. this.l2x = this.ax * this.m2;
  97679. this.l2y = this.ay * this.m2;
  97680. this.l2z = this.az * this.m2;
  97681. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97682. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97683. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97684. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97685. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97686. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97687. this.motorDenom =
  97688. this.m1 + this.m2 +
  97689. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97690. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97691. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97692. this.invMotorDenom = 1 / this.motorDenom;
  97693. if (enableSpring && this.limitState != 2) {
  97694. var omega = 6.2831853 * frequency;
  97695. var k = omega * omega * timeStep;
  97696. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97697. this.cfm = this.motorDenom * dmp;
  97698. this.limitVelocity *= k * dmp;
  97699. } else {
  97700. this.cfm = 0;
  97701. this.limitVelocity *= invTimeStep * 0.05;
  97702. }
  97703. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97704. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97705. this.l1.x += totalImpulse * this.l1x;
  97706. this.l1.y += totalImpulse * this.l1y;
  97707. this.l1.z += totalImpulse * this.l1z;
  97708. this.a1.x += totalImpulse * this.a1x;
  97709. this.a1.y += totalImpulse * this.a1y;
  97710. this.a1.z += totalImpulse * this.a1z;
  97711. this.l2.x -= totalImpulse * this.l2x;
  97712. this.l2.y -= totalImpulse * this.l2y;
  97713. this.l2.z -= totalImpulse * this.l2z;
  97714. this.a2.x -= totalImpulse * this.a2x;
  97715. this.a2.y -= totalImpulse * this.a2y;
  97716. this.a2.z -= totalImpulse * this.a2z;
  97717. },
  97718. solve: function () {
  97719. var rvn =
  97720. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97721. 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;
  97722. // motor part
  97723. var newMotorImpulse;
  97724. if (this.enableMotor) {
  97725. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97726. var oldMotorImpulse = this.motorImpulse;
  97727. this.motorImpulse += newMotorImpulse;
  97728. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97729. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97730. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97731. rvn -= newMotorImpulse * this.motorDenom;
  97732. } else newMotorImpulse = 0;
  97733. // limit part
  97734. var newLimitImpulse;
  97735. if (this.limitState != 2) {
  97736. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97737. var oldLimitImpulse = this.limitImpulse;
  97738. this.limitImpulse += newLimitImpulse;
  97739. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97740. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97741. } else newLimitImpulse = 0;
  97742. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97743. this.l1.x += totalImpulse * this.l1x;
  97744. this.l1.y += totalImpulse * this.l1y;
  97745. this.l1.z += totalImpulse * this.l1z;
  97746. this.a1.x += totalImpulse * this.a1x;
  97747. this.a1.y += totalImpulse * this.a1y;
  97748. this.a1.z += totalImpulse * this.a1z;
  97749. this.l2.x -= totalImpulse * this.l2x;
  97750. this.l2.y -= totalImpulse * this.l2y;
  97751. this.l2.z -= totalImpulse * this.l2z;
  97752. this.a2.x -= totalImpulse * this.a2x;
  97753. this.a2.y -= totalImpulse * this.a2y;
  97754. this.a2.z -= totalImpulse * this.a2z;
  97755. }
  97756. }
  97757. /**
  97758. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97759. * @author saharan
  97760. */
  97761. OIMO.Contact = function () {
  97762. // The first shape.
  97763. this.shape1 = null;
  97764. // The second shape.
  97765. this.shape2 = null;
  97766. // The first rigid body.
  97767. this.body1 = null;
  97768. // The second rigid body.
  97769. this.body2 = null;
  97770. // The previous contact in the world.
  97771. this.prev = null;
  97772. // The next contact in the world.
  97773. this.next = null;
  97774. // Internal
  97775. this.persisting = false;
  97776. // Whether both the rigid bodies are sleeping or not.
  97777. this.sleeping = false;
  97778. // The collision detector between two shapes.
  97779. this.detector = null;
  97780. // The contact constraint of the contact.
  97781. this.constraint = null;
  97782. // Whether the shapes are touching or not.
  97783. this.touching = false;
  97784. this.b1Link = new OIMO.ContactLink(this);
  97785. this.b2Link = new OIMO.ContactLink(this);
  97786. this.s1Link = new OIMO.ContactLink(this);
  97787. this.s2Link = new OIMO.ContactLink(this);
  97788. // The contact manifold of the contact.
  97789. this.manifold = new OIMO.ContactManifold();
  97790. this.buffer = [];// vector 4
  97791. this.buffer.length = 4;
  97792. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97793. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97794. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97795. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97796. this.points = this.manifold.points;
  97797. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97798. }
  97799. OIMO.Contact.prototype = {
  97800. constructor: OIMO.Contact,
  97801. mixRestitution: function (restitution1, restitution2) {
  97802. return OIMO.sqrt(restitution1 * restitution2);
  97803. },
  97804. mixFriction: function (friction1, friction2) {
  97805. return OIMO.sqrt(friction1 * friction2);
  97806. },
  97807. /**
  97808. * Update the contact manifold.
  97809. */
  97810. updateManifold: function () {
  97811. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97812. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97813. var numBuffers = this.manifold.numPoints;
  97814. var i = numBuffers;
  97815. while (i--) {
  97816. //for(var i=0;i<numBuffers;i++){
  97817. var b = this.buffer[i];
  97818. var p = this.points[i];
  97819. b.lp1X = p.localPoint1.x;
  97820. b.lp1Y = p.localPoint1.y;
  97821. b.lp1Z = p.localPoint1.z;
  97822. b.lp2X = p.localPoint2.x;
  97823. b.lp2Y = p.localPoint2.y;
  97824. b.lp2Z = p.localPoint2.z;
  97825. b.impulse = p.normalImpulse;
  97826. }
  97827. this.manifold.numPoints = 0;
  97828. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97829. var num = this.manifold.numPoints;
  97830. if (num == 0) {
  97831. this.touching = false;
  97832. return;
  97833. }
  97834. this.touching = true;
  97835. i = num;
  97836. while (i--) {
  97837. //for(i=0; i<num; i++){
  97838. p = this.points[i];
  97839. var lp1x = p.localPoint1.x;
  97840. var lp1y = p.localPoint1.y;
  97841. var lp1z = p.localPoint1.z;
  97842. var lp2x = p.localPoint2.x;
  97843. var lp2y = p.localPoint2.y;
  97844. var lp2z = p.localPoint2.z;
  97845. var index = -1;
  97846. var minDistance = 0.0004;
  97847. var j = numBuffers;
  97848. while (j--) {
  97849. //for(var j=0;j<numBuffers;j++){
  97850. b = this.buffer[j];
  97851. var dx = b.lp1X - lp1x;
  97852. var dy = b.lp1Y - lp1y;
  97853. var dz = b.lp1Z - lp1z;
  97854. var distance1 = dx * dx + dy * dy + dz * dz;
  97855. dx = b.lp2X - lp2x;
  97856. dy = b.lp2Y - lp2y;
  97857. dz = b.lp2Z - lp2z;
  97858. var distance2 = dx * dx + dy * dy + dz * dz;
  97859. if (distance1 < distance2) {
  97860. if (distance1 < minDistance) {
  97861. minDistance = distance1;
  97862. index = j;
  97863. }
  97864. } else {
  97865. if (distance2 < minDistance) {
  97866. minDistance = distance2;
  97867. index = j;
  97868. }
  97869. }
  97870. }
  97871. if (index != -1) {
  97872. var tmp = this.buffer[index];
  97873. this.buffer[index] = this.buffer[--numBuffers];
  97874. this.buffer[numBuffers] = tmp;
  97875. p.normalImpulse = tmp.impulse;
  97876. p.warmStarted = true;
  97877. } else {
  97878. p.normalImpulse = 0;
  97879. p.warmStarted = false;
  97880. }
  97881. }
  97882. },
  97883. /**
  97884. * Attach the contact to the shapes.
  97885. * @param shape1
  97886. * @param shape2
  97887. */
  97888. attach: function (shape1, shape2) {
  97889. this.shape1 = shape1;
  97890. this.shape2 = shape2;
  97891. this.body1 = shape1.parent;
  97892. this.body2 = shape2.parent;
  97893. this.manifold.body1 = this.body1;
  97894. this.manifold.body2 = this.body2;
  97895. this.constraint.body1 = this.body1;
  97896. this.constraint.body2 = this.body2;
  97897. this.constraint.attach();
  97898. this.s1Link.shape = shape2;
  97899. this.s1Link.body = this.body2;
  97900. this.s2Link.shape = shape1;
  97901. this.s2Link.body = this.body1;
  97902. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97903. else this.s1Link.next = null;
  97904. shape1.contactLink = this.s1Link;
  97905. shape1.numContacts++;
  97906. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97907. else this.s2Link.next = null;
  97908. shape2.contactLink = this.s2Link;
  97909. shape2.numContacts++;
  97910. this.b1Link.shape = shape2;
  97911. this.b1Link.body = this.body2;
  97912. this.b2Link.shape = shape1;
  97913. this.b2Link.body = this.body1;
  97914. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97915. else this.b1Link.next = null;
  97916. this.body1.contactLink = this.b1Link;
  97917. this.body1.numContacts++;
  97918. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97919. else this.b2Link.next = null;
  97920. this.body2.contactLink = this.b2Link;
  97921. this.body2.numContacts++;
  97922. this.prev = null;
  97923. this.next = null;
  97924. this.persisting = true;
  97925. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97926. this.manifold.numPoints = 0;
  97927. },
  97928. /**
  97929. * Detach the contact from the shapes.
  97930. */
  97931. detach: function () {
  97932. var prev = this.s1Link.prev;
  97933. var next = this.s1Link.next;
  97934. if (prev !== null) prev.next = next;
  97935. if (next !== null) next.prev = prev;
  97936. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97937. this.s1Link.prev = null;
  97938. this.s1Link.next = null;
  97939. this.s1Link.shape = null;
  97940. this.s1Link.body = null;
  97941. this.shape1.numContacts--;
  97942. prev = this.s2Link.prev;
  97943. next = this.s2Link.next;
  97944. if (prev !== null) prev.next = next;
  97945. if (next !== null) next.prev = prev;
  97946. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  97947. this.s2Link.prev = null;
  97948. this.s2Link.next = null;
  97949. this.s2Link.shape = null;
  97950. this.s2Link.body = null;
  97951. this.shape2.numContacts--;
  97952. prev = this.b1Link.prev;
  97953. next = this.b1Link.next;
  97954. if (prev !== null) prev.next = next;
  97955. if (next !== null) next.prev = prev;
  97956. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  97957. this.b1Link.prev = null;
  97958. this.b1Link.next = null;
  97959. this.b1Link.shape = null;
  97960. this.b1Link.body = null;
  97961. this.body1.numContacts--;
  97962. prev = this.b2Link.prev;
  97963. next = this.b2Link.next;
  97964. if (prev !== null) prev.next = next;
  97965. if (next !== null) next.prev = prev;
  97966. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  97967. this.b2Link.prev = null;
  97968. this.b2Link.next = null;
  97969. this.b2Link.shape = null;
  97970. this.b2Link.body = null;
  97971. this.body2.numContacts--;
  97972. this.manifold.body1 = null;
  97973. this.manifold.body2 = null;
  97974. this.constraint.body1 = null;
  97975. this.constraint.body2 = null;
  97976. this.constraint.detach();
  97977. this.shape1 = null;
  97978. this.shape2 = null;
  97979. this.body1 = null;
  97980. this.body2 = null;
  97981. }
  97982. }
  97983. /**
  97984. * ...
  97985. * @author saharan
  97986. */
  97987. OIMO.ContactConstraint = function (manifold) {
  97988. OIMO.Constraint.call(this);
  97989. // The contact manifold of the constraint.
  97990. this.manifold = manifold;
  97991. // The coefficient of restitution of the constraint.
  97992. this.restitution = NaN;
  97993. // The coefficient of friction of the constraint.
  97994. this.friction = NaN;
  97995. this.p1 = null;
  97996. this.p2 = null;
  97997. this.lv1 = null;
  97998. this.lv2 = null;
  97999. this.av1 = null;
  98000. this.av2 = null;
  98001. this.i1 = null;
  98002. this.i2 = null;
  98003. this.ii1 = null;
  98004. this.ii2 = null;
  98005. this.m1 = NaN;
  98006. this.m2 = NaN;
  98007. this.num = 0;
  98008. this.ps = manifold.points;
  98009. this.cs = new OIMO.ContactPointDataBuffer();
  98010. this.cs.next = new OIMO.ContactPointDataBuffer();
  98011. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  98012. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  98013. }
  98014. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  98015. /**
  98016. * Attach the constraint to the bodies.
  98017. */
  98018. OIMO.ContactConstraint.prototype.attach = function () {
  98019. this.p1 = this.body1.position;
  98020. this.p2 = this.body2.position;
  98021. this.lv1 = this.body1.linearVelocity;
  98022. this.av1 = this.body1.angularVelocity;
  98023. this.lv2 = this.body2.linearVelocity;
  98024. this.av2 = this.body2.angularVelocity;
  98025. this.i1 = this.body1.inverseInertia;
  98026. this.i2 = this.body2.inverseInertia;
  98027. }
  98028. /**
  98029. * Detach the constraint from the bodies.
  98030. */
  98031. OIMO.ContactConstraint.prototype.detach = function () {
  98032. this.p1 = null;
  98033. this.p2 = null;
  98034. this.lv1 = null;
  98035. this.lv2 = null;
  98036. this.av1 = null;
  98037. this.av2 = null;
  98038. this.i1 = null;
  98039. this.i2 = null;
  98040. }
  98041. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  98042. this.m1 = this.body1.inverseMass;
  98043. this.m2 = this.body2.inverseMass;
  98044. this.ii1 = this.i1.clone();
  98045. this.ii2 = this.i2.clone();
  98046. var ii1 = this.ii1.elements;
  98047. var ii2 = this.ii2.elements;
  98048. var p1x = this.p1.x;
  98049. var p1y = this.p1.y;
  98050. var p1z = this.p1.z;
  98051. var p2x = this.p2.x;
  98052. var p2y = this.p2.y;
  98053. var p2z = this.p2.z;
  98054. var m1m2 = this.m1 + this.m2;
  98055. this.num = this.manifold.numPoints;
  98056. var c = this.cs;
  98057. for (var i = 0; i < this.num; i++) {
  98058. var p = this.ps[i];
  98059. var tmp1X;
  98060. var tmp1Y;
  98061. var tmp1Z;
  98062. var tmp2X;
  98063. var tmp2Y;
  98064. var tmp2Z;
  98065. tmp1X = p.position.x;
  98066. tmp1Y = p.position.y;
  98067. tmp1Z = p.position.z;
  98068. var rp1X = tmp1X - p1x;
  98069. var rp1Y = tmp1Y - p1y;
  98070. var rp1Z = tmp1Z - p1z;
  98071. var rp2X = tmp1X - p2x;
  98072. var rp2Y = tmp1Y - p2y;
  98073. var rp2Z = tmp1Z - p2z;
  98074. c.rp1X = rp1X;
  98075. c.rp1Y = rp1Y;
  98076. c.rp1Z = rp1Z;
  98077. c.rp2X = rp2X;
  98078. c.rp2Y = rp2Y;
  98079. c.rp2Z = rp2Z;
  98080. c.norImp = p.normalImpulse;
  98081. c.tanImp = p.tangentImpulse;
  98082. c.binImp = p.binormalImpulse;
  98083. var norX = p.normal.x;
  98084. var norY = p.normal.y;
  98085. var norZ = p.normal.z;
  98086. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98087. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98088. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98089. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98090. var tanX = rvX - rvn * norX;
  98091. var tanY = rvY - rvn * norY;
  98092. var tanZ = rvZ - rvn * norZ;
  98093. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98094. if (len > 0.04) {
  98095. len = 1 / OIMO.sqrt(len);
  98096. } else {
  98097. tanX = norY * norX - norZ * norZ;
  98098. tanY = -norZ * norY - norX * norX;
  98099. tanZ = norX * norZ + norY * norY;
  98100. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98101. }
  98102. tanX *= len;
  98103. tanY *= len;
  98104. tanZ *= len;
  98105. var binX = norY * tanZ - norZ * tanY;
  98106. var binY = norZ * tanX - norX * tanZ;
  98107. var binZ = norX * tanY - norY * tanX;
  98108. c.norX = norX;
  98109. c.norY = norY;
  98110. c.norZ = norZ;
  98111. c.tanX = tanX;
  98112. c.tanY = tanY;
  98113. c.tanZ = tanZ;
  98114. c.binX = binX;
  98115. c.binY = binY;
  98116. c.binZ = binZ;
  98117. c.norU1X = norX * this.m1;
  98118. c.norU1Y = norY * this.m1;
  98119. c.norU1Z = norZ * this.m1;
  98120. c.norU2X = norX * this.m2;
  98121. c.norU2Y = norY * this.m2;
  98122. c.norU2Z = norZ * this.m2;
  98123. c.tanU1X = tanX * this.m1;
  98124. c.tanU1Y = tanY * this.m1;
  98125. c.tanU1Z = tanZ * this.m1;
  98126. c.tanU2X = tanX * this.m2;
  98127. c.tanU2Y = tanY * this.m2;
  98128. c.tanU2Z = tanZ * this.m2;
  98129. c.binU1X = binX * this.m1;
  98130. c.binU1Y = binY * this.m1;
  98131. c.binU1Z = binZ * this.m1;
  98132. c.binU2X = binX * this.m2;
  98133. c.binU2Y = binY * this.m2;
  98134. c.binU2Z = binZ * this.m2;
  98135. var norT1X = rp1Y * norZ - rp1Z * norY;
  98136. var norT1Y = rp1Z * norX - rp1X * norZ;
  98137. var norT1Z = rp1X * norY - rp1Y * norX;
  98138. var norT2X = rp2Y * norZ - rp2Z * norY;
  98139. var norT2Y = rp2Z * norX - rp2X * norZ;
  98140. var norT2Z = rp2X * norY - rp2Y * norX;
  98141. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98142. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98143. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98144. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98145. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98146. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98147. var binT1X = rp1Y * binZ - rp1Z * binY;
  98148. var binT1Y = rp1Z * binX - rp1X * binZ;
  98149. var binT1Z = rp1X * binY - rp1Y * binX;
  98150. var binT2X = rp2Y * binZ - rp2Z * binY;
  98151. var binT2Y = rp2Z * binX - rp2X * binZ;
  98152. var binT2Z = rp2X * binY - rp2Y * binX;
  98153. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98154. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98155. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98156. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98157. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98158. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98159. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98160. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98161. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98162. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98163. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98164. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98165. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98166. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98167. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98168. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98169. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98170. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98171. c.norT1X = norT1X;
  98172. c.norT1Y = norT1Y;
  98173. c.norT1Z = norT1Z;
  98174. c.tanT1X = tanT1X;
  98175. c.tanT1Y = tanT1Y;
  98176. c.tanT1Z = tanT1Z;
  98177. c.binT1X = binT1X;
  98178. c.binT1Y = binT1Y;
  98179. c.binT1Z = binT1Z;
  98180. c.norT2X = norT2X;
  98181. c.norT2Y = norT2Y;
  98182. c.norT2Z = norT2Z;
  98183. c.tanT2X = tanT2X;
  98184. c.tanT2Y = tanT2Y;
  98185. c.tanT2Z = tanT2Z;
  98186. c.binT2X = binT2X;
  98187. c.binT2Y = binT2Y;
  98188. c.binT2Z = binT2Z;
  98189. c.norTU1X = norTU1X;
  98190. c.norTU1Y = norTU1Y;
  98191. c.norTU1Z = norTU1Z;
  98192. c.tanTU1X = tanTU1X;
  98193. c.tanTU1Y = tanTU1Y;
  98194. c.tanTU1Z = tanTU1Z;
  98195. c.binTU1X = binTU1X;
  98196. c.binTU1Y = binTU1Y;
  98197. c.binTU1Z = binTU1Z;
  98198. c.norTU2X = norTU2X;
  98199. c.norTU2Y = norTU2Y;
  98200. c.norTU2Z = norTU2Z;
  98201. c.tanTU2X = tanTU2X;
  98202. c.tanTU2Y = tanTU2Y;
  98203. c.tanTU2Z = tanTU2Z;
  98204. c.binTU2X = binTU2X;
  98205. c.binTU2Y = binTU2Y;
  98206. c.binTU2Z = binTU2Z;
  98207. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98208. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98209. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98210. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98211. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98212. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98213. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98214. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98215. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98216. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98217. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98218. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98219. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98220. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98221. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98222. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98223. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98224. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98225. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98226. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98227. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98228. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98229. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98230. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98231. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98232. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98233. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98234. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98235. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98236. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98237. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98238. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98239. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98240. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98241. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98242. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98243. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98244. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98245. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98246. c.norDen = norDen;
  98247. c.tanDen = tanDen;
  98248. c.binDen = binDen;
  98249. if (p.warmStarted) {
  98250. var norImp = p.normalImpulse;
  98251. this.lv1.x += c.norU1X * norImp;
  98252. this.lv1.y += c.norU1Y * norImp;
  98253. this.lv1.z += c.norU1Z * norImp;
  98254. this.av1.x += norTU1X * norImp;
  98255. this.av1.y += norTU1Y * norImp;
  98256. this.av1.z += norTU1Z * norImp;
  98257. this.lv2.x -= c.norU2X * norImp;
  98258. this.lv2.y -= c.norU2Y * norImp;
  98259. this.lv2.z -= c.norU2Z * norImp;
  98260. this.av2.x -= norTU2X * norImp;
  98261. this.av2.y -= norTU2Y * norImp;
  98262. this.av2.z -= norTU2Z * norImp;
  98263. c.norImp = norImp;
  98264. c.tanImp = 0;
  98265. c.binImp = 0;
  98266. rvn = 0; // disable bouncing
  98267. } else {
  98268. c.norImp = 0;
  98269. c.tanImp = 0;
  98270. c.binImp = 0;
  98271. }
  98272. if (rvn > -1) {
  98273. rvn = 0; // disable bouncing
  98274. }
  98275. var norTar = this.restitution * -rvn;
  98276. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98277. if (norTar < sepV) norTar = sepV;
  98278. c.norTar = norTar;
  98279. c.last = i == this.num - 1;
  98280. c = c.next;
  98281. }
  98282. }
  98283. OIMO.ContactConstraint.prototype.solve = function () {
  98284. var lv1x = this.lv1.x;
  98285. var lv1y = this.lv1.y;
  98286. var lv1z = this.lv1.z;
  98287. var lv2x = this.lv2.x;
  98288. var lv2y = this.lv2.y;
  98289. var lv2z = this.lv2.z;
  98290. var av1x = this.av1.x;
  98291. var av1y = this.av1.y;
  98292. var av1z = this.av1.z;
  98293. var av2x = this.av2.x;
  98294. var av2y = this.av2.y;
  98295. var av2z = this.av2.z;
  98296. var c = this.cs;
  98297. while (true) {
  98298. var oldImp1;
  98299. var newImp1;
  98300. var oldImp2;
  98301. var newImp2;
  98302. var rvn;
  98303. var norImp = c.norImp;
  98304. var tanImp = c.tanImp;
  98305. var binImp = c.binImp;
  98306. var max = -norImp * this.friction;
  98307. var rvX = lv2x - lv1x;
  98308. var rvY = lv2y - lv1y;
  98309. var rvZ = lv2z - lv1z;
  98310. rvn =
  98311. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98312. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98313. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98314. ;
  98315. oldImp1 = tanImp;
  98316. newImp1 = rvn * c.tanDen;
  98317. tanImp += newImp1;
  98318. rvn =
  98319. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98320. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98321. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98322. ;
  98323. oldImp2 = binImp;
  98324. newImp2 = rvn * c.binDen;
  98325. binImp += newImp2;
  98326. // cone friction clamp
  98327. var len = tanImp * tanImp + binImp * binImp;
  98328. if (len > max * max) {
  98329. len = max / OIMO.sqrt(len);
  98330. tanImp *= len;
  98331. binImp *= len;
  98332. }
  98333. newImp1 = tanImp - oldImp1;
  98334. newImp2 = binImp - oldImp2;
  98335. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98336. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98337. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98338. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98339. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98340. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98341. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98342. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98343. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98344. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98345. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98346. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98347. // restitution part
  98348. rvn =
  98349. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98350. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98351. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98352. oldImp1 = norImp;
  98353. newImp1 = (rvn - c.norTar) * c.norDen;
  98354. norImp += newImp1;
  98355. if (norImp > 0) norImp = 0;
  98356. newImp1 = norImp - oldImp1;
  98357. lv1x += c.norU1X * newImp1;
  98358. lv1y += c.norU1Y * newImp1;
  98359. lv1z += c.norU1Z * newImp1;
  98360. av1x += c.norTU1X * newImp1;
  98361. av1y += c.norTU1Y * newImp1;
  98362. av1z += c.norTU1Z * newImp1;
  98363. lv2x -= c.norU2X * newImp1;
  98364. lv2y -= c.norU2Y * newImp1;
  98365. lv2z -= c.norU2Z * newImp1;
  98366. av2x -= c.norTU2X * newImp1;
  98367. av2y -= c.norTU2Y * newImp1;
  98368. av2z -= c.norTU2Z * newImp1;
  98369. c.norImp = norImp;
  98370. c.tanImp = tanImp;
  98371. c.binImp = binImp;
  98372. if (c.last) break;
  98373. c = c.next;
  98374. }
  98375. this.lv1.x = lv1x;
  98376. this.lv1.y = lv1y;
  98377. this.lv1.z = lv1z;
  98378. this.lv2.x = lv2x;
  98379. this.lv2.y = lv2y;
  98380. this.lv2.z = lv2z;
  98381. this.av1.x = av1x;
  98382. this.av1.y = av1y;
  98383. this.av1.z = av1z;
  98384. this.av2.x = av2x;
  98385. this.av2.y = av2y;
  98386. this.av2.z = av2z;
  98387. }
  98388. OIMO.ContactConstraint.prototype.postSolve = function () {
  98389. var c = this.cs;
  98390. var i = this.num;
  98391. while (i--) {
  98392. //for(var i=0;i<this.num;i++){
  98393. var p = this.ps[i];
  98394. p.normal.x = c.norX;
  98395. p.normal.y = c.norY;
  98396. p.normal.z = c.norZ;
  98397. p.tangent.x = c.tanX;
  98398. p.tangent.y = c.tanY;
  98399. p.tangent.z = c.tanZ;
  98400. p.binormal.x = c.binX;
  98401. p.binormal.y = c.binY;
  98402. p.binormal.z = c.binZ;
  98403. p.normalImpulse = c.norImp;
  98404. p.tangentImpulse = c.tanImp;
  98405. p.binormalImpulse = c.binImp;
  98406. p.normalDenominator = c.norDen;
  98407. p.tangentDenominator = c.tanDen;
  98408. p.binormalDenominator = c.binDen;
  98409. c = c.next;
  98410. }
  98411. }
  98412. /**
  98413. * A link list of contacts.
  98414. * @author saharan
  98415. */
  98416. OIMO.ContactLink = function (contact) {
  98417. // The previous contact link.
  98418. this.prev = null;
  98419. // The next contact link.
  98420. this.next = null;
  98421. // The shape of the contact.
  98422. this.shape = null;
  98423. // The other rigid body.
  98424. this.body = null;
  98425. // The contact of the link.
  98426. this.contact = contact;
  98427. }
  98428. /**
  98429. * A contact manifold between two shapes.
  98430. * @author saharan
  98431. */
  98432. OIMO.ContactManifold = function () {
  98433. // The first rigid body.
  98434. this.body1 = null;
  98435. // The second rigid body.
  98436. this.body2 = null;
  98437. // The number of manifold points.
  98438. this.numPoints = 0;
  98439. // The manifold points.
  98440. this.points = [];
  98441. this.points.length = 4;
  98442. this.points[0] = new OIMO.ManifoldPoint();
  98443. this.points[1] = new OIMO.ManifoldPoint();
  98444. this.points[2] = new OIMO.ManifoldPoint();
  98445. this.points[3] = new OIMO.ManifoldPoint();
  98446. }
  98447. OIMO.ContactManifold.prototype = {
  98448. constructor: OIMO.ContactManifold,
  98449. /**
  98450. * Reset the manifold.
  98451. * @param shape1
  98452. * @param shape2
  98453. */
  98454. reset: function (shape1, shape2) {
  98455. this.body1 = shape1.parent;
  98456. this.body2 = shape2.parent;
  98457. this.numPoints = 0;
  98458. },
  98459. /**
  98460. * Add a point into this manifold.
  98461. * @param x
  98462. * @param y
  98463. * @param z
  98464. * @param normalX
  98465. * @param normalY
  98466. * @param normalZ
  98467. * @param penetration
  98468. * @param flip
  98469. */
  98470. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98471. var p = this.points[this.numPoints++];
  98472. p.position.x = x;
  98473. p.position.y = y;
  98474. p.position.z = z;
  98475. var r = this.body1.rotation;
  98476. var rx = x - this.body1.position.x;
  98477. var ry = y - this.body1.position.y;
  98478. var rz = z - this.body1.position.z;
  98479. var tr = r.elements;
  98480. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98481. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98482. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98483. r = this.body2.rotation;
  98484. rx = x - this.body2.position.x;
  98485. ry = y - this.body2.position.y;
  98486. rz = z - this.body2.position.z;
  98487. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98488. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98489. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98490. p.normalImpulse = 0;
  98491. if (flip) {
  98492. p.normal.x = -normalX;
  98493. p.normal.y = -normalY;
  98494. p.normal.z = -normalZ;
  98495. } else {
  98496. p.normal.x = normalX;
  98497. p.normal.y = normalY;
  98498. p.normal.z = normalZ;
  98499. }
  98500. p.penetration = penetration;
  98501. p.warmStarted = false;
  98502. }
  98503. }
  98504. OIMO.ContactPointDataBuffer = function () {
  98505. this.norX = NaN;
  98506. this.norY = NaN;
  98507. this.norZ = NaN;
  98508. this.tanX = NaN;
  98509. this.tanY = NaN;
  98510. this.tanZ = NaN;
  98511. this.binX = NaN;
  98512. this.binY = NaN;
  98513. this.binZ = NaN;
  98514. this.rp1X = NaN;
  98515. this.rp1Y = NaN;
  98516. this.rp1Z = NaN;
  98517. this.rp2X = NaN;
  98518. this.rp2Y = NaN;
  98519. this.rp2Z = NaN;
  98520. this.norU1X = NaN;
  98521. this.norU1Y = NaN;
  98522. this.norU1Z = NaN;
  98523. this.norU2X = NaN;
  98524. this.norU2Y = NaN;
  98525. this.norU2Z = NaN;
  98526. this.tanU1X = NaN;
  98527. this.tanU1Y = NaN;
  98528. this.tanU1Z = NaN;
  98529. this.tanU2X = NaN;
  98530. this.tanU2Y = NaN;
  98531. this.tanU2Z = NaN;
  98532. this.binU1X = NaN;
  98533. this.binU1Y = NaN;
  98534. this.binU1Z = NaN;
  98535. this.binU2X = NaN;
  98536. this.binU2Y = NaN;
  98537. this.binU2Z = NaN;
  98538. this.norT1X = NaN;
  98539. this.norT1Y = NaN;
  98540. this.norT1Z = NaN;
  98541. this.norT2X = NaN;
  98542. this.norT2Y = NaN;
  98543. this.norT2Z = NaN;
  98544. this.tanT1X = NaN;
  98545. this.tanT1Y = NaN;
  98546. this.tanT1Z = NaN;
  98547. this.tanT2X = NaN;
  98548. this.tanT2Y = NaN;
  98549. this.tanT2Z = NaN;
  98550. this.binT1X = NaN;
  98551. this.binT1Y = NaN;
  98552. this.binT1Z = NaN;
  98553. this.binT2X = NaN;
  98554. this.binT2Y = NaN;
  98555. this.binT2Z = NaN;
  98556. this.norTU1X = NaN;
  98557. this.norTU1Y = NaN;
  98558. this.norTU1Z = NaN;
  98559. this.norTU2X = NaN;
  98560. this.norTU2Y = NaN;
  98561. this.norTU2Z = NaN;
  98562. this.tanTU1X = NaN;
  98563. this.tanTU1Y = NaN;
  98564. this.tanTU1Z = NaN;
  98565. this.tanTU2X = NaN;
  98566. this.tanTU2Y = NaN;
  98567. this.tanTU2Z = NaN;
  98568. this.binTU1X = NaN;
  98569. this.binTU1Y = NaN;
  98570. this.binTU1Z = NaN;
  98571. this.binTU2X = NaN;
  98572. this.binTU2Y = NaN;
  98573. this.binTU2Z = NaN;
  98574. this.norImp = NaN;
  98575. this.tanImp = NaN;
  98576. this.binImp = NaN;
  98577. this.norDen = NaN;
  98578. this.tanDen = NaN;
  98579. this.binDen = NaN;
  98580. this.norTar = NaN;
  98581. this.next = null;
  98582. this.last = false;
  98583. }
  98584. OIMO.ImpulseDataBuffer = function () {
  98585. this.lp1X = NaN;
  98586. this.lp1Y = NaN;
  98587. this.lp1Z = NaN;
  98588. this.lp2X = NaN;
  98589. this.lp2Y = NaN;
  98590. this.lp2Z = NaN;
  98591. this.impulse = NaN;
  98592. }
  98593. /**
  98594. * The class holds details of the contact point.
  98595. * @author saharan
  98596. */
  98597. OIMO.ManifoldPoint = function () {
  98598. // Whether this manifold point is persisting or not.
  98599. this.warmStarted = false;
  98600. // The position of this manifold point.
  98601. this.position = new OIMO.Vec3();
  98602. // The position in the first shape's coordinate.
  98603. this.localPoint1 = new OIMO.Vec3();
  98604. // The position in the second shape's coordinate.
  98605. this.localPoint2 = new OIMO.Vec3();
  98606. // The normal vector of this manifold point.
  98607. this.normal = new OIMO.Vec3();
  98608. // The tangent vector of this manifold point.
  98609. this.tangent = new OIMO.Vec3();
  98610. // The binormal vector of this manifold point.
  98611. this.binormal = new OIMO.Vec3();
  98612. // The impulse in normal direction.
  98613. this.normalImpulse = 0;
  98614. // The impulse in tangent direction.
  98615. this.tangentImpulse = 0;
  98616. // The impulse in binormal direction.
  98617. this.binormalImpulse = 0;
  98618. // The denominator in normal direction.
  98619. this.normalDenominator = 0;
  98620. // The denominator in tangent direction.
  98621. this.tangentDenominator = 0;
  98622. // The denominator in binormal direction.
  98623. this.binormalDenominator = 0;
  98624. // The depth of penetration.
  98625. this.penetration = 0;
  98626. }
  98627. /**
  98628. * This class holds mass information of a shape.
  98629. * @author saharan
  98630. */
  98631. OIMO.MassInfo = function () {
  98632. // Mass of the shape.
  98633. this.mass = 0;
  98634. // The moment inertia of the shape.
  98635. this.inertia = new OIMO.Mat33();
  98636. };
  98637. /**
  98638. * A shape is used to detect collisions of rigid bodies.
  98639. * @author saharan
  98640. * @author lo-th
  98641. */
  98642. OIMO.Shape = function (config) {
  98643. this.type = OIMO.SHAPE_NULL;
  98644. // The global identification of the shape should be unique to the shape.
  98645. this.id = OIMO.nextID++;
  98646. // The previous shape in parent rigid body.
  98647. this.prev = null;
  98648. // The next shape in parent rigid body.
  98649. this.next = null;
  98650. // The proxy of the shape used for broad-phase collision detection.
  98651. this.proxy = null;
  98652. // The parent rigid body of the shape.
  98653. this.parent = null;
  98654. // The linked list of the contacts with the shape.
  98655. this.contactLink = null;
  98656. // The number of the contacts with the shape.
  98657. this.numContacts = 0;
  98658. // The center of gravity of the shape in world coordinate system.
  98659. this.position = new OIMO.Vec3();
  98660. // The rotation matrix of the shape in world coordinate system
  98661. this.rotation = new OIMO.Mat33();
  98662. // The position of the shape in parent's coordinate system.
  98663. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98664. // The rotation matrix of the shape in parent's coordinate system.
  98665. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98666. // The axis-aligned bounding box of the shape.
  98667. this.aabb = new OIMO.AABB();
  98668. // The density of the shape.
  98669. this.density = config.density;
  98670. // The coefficient of friction of the shape.
  98671. this.friction = config.friction;
  98672. // The coefficient of restitution of the shape.
  98673. this.restitution = config.restitution;
  98674. // The bits of the collision groups to which the shape belongs.
  98675. this.belongsTo = config.belongsTo;
  98676. // The bits of the collision groups with which the shape collides.
  98677. this.collidesWith = config.collidesWith;
  98678. };
  98679. OIMO.Shape.prototype = {
  98680. constructor: OIMO.Shape,
  98681. // Calculate the mass information of the shape.
  98682. calculateMassInfo: function (out) {
  98683. OIMO.Error("Shape", "Inheritance error.");
  98684. },
  98685. // Update the proxy of the shape.
  98686. updateProxy: function () {
  98687. OIMO.Error("Shape", "Inheritance error.");
  98688. }
  98689. };
  98690. /**
  98691. * A shape configuration holds common configuration data for constructing a shape.
  98692. * Shape configurations can be reused safely.
  98693. * @author saharan
  98694. */
  98695. OIMO.ShapeConfig = function () {
  98696. // The position of the shape in parent's coordinate system.
  98697. this.relativePosition = new OIMO.Vec3();
  98698. // The rotation matrix of the shape in parent's coordinate system.
  98699. this.relativeRotation = new OIMO.Mat33();
  98700. // The coefficient of friction of the shape.
  98701. this.friction = 0.4;
  98702. // The coefficient of restitution of the shape.
  98703. this.restitution = 0.2;
  98704. // The density of the shape.
  98705. this.density = 1;
  98706. // The bits of the collision groups to which the shape belongs.
  98707. this.belongsTo = 1;
  98708. // The bits of the collision groups with which the shape collides.
  98709. this.collidesWith = 0xffffffff;
  98710. };
  98711. /**
  98712. * A box shape.
  98713. * @author saharan
  98714. * @author lo-th
  98715. */
  98716. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98717. OIMO.Shape.call(this, config);
  98718. this.type = OIMO.SHAPE_BOX;
  98719. // The width of the box.
  98720. this.width = Width;
  98721. // The height of the box.
  98722. this.height = Height;
  98723. // The depth of the box.
  98724. this.depth = Depth;
  98725. // The half-width of the box.
  98726. this.halfWidth = Width * 0.5;
  98727. // The half-height of the box.
  98728. this.halfHeight = Height * 0.5;
  98729. // The half-depth of the box.
  98730. this.halfDepth = Depth * 0.5;
  98731. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98732. this.elements = new OIMO_ARRAY_TYPE(24);
  98733. };
  98734. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98735. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98736. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98737. var mass = this.width * this.height * this.depth * this.density;
  98738. var divid = 1 / 12;
  98739. out.mass = mass;
  98740. out.inertia.set(
  98741. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98742. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98743. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98744. );
  98745. };
  98746. OIMO.BoxShape.prototype.updateProxy = function () {
  98747. var te = this.rotation.elements;
  98748. var di = this.dimentions;
  98749. // Width
  98750. di[0] = te[0];
  98751. di[1] = te[3];
  98752. di[2] = te[6];
  98753. // Height
  98754. di[3] = te[1];
  98755. di[4] = te[4];
  98756. di[5] = te[7];
  98757. // Depth
  98758. di[6] = te[2];
  98759. di[7] = te[5];
  98760. di[8] = te[8];
  98761. // halp Width
  98762. di[9] = te[0] * this.halfWidth;
  98763. di[10] = te[3] * this.halfWidth;
  98764. di[11] = te[6] * this.halfWidth;
  98765. // halp Height
  98766. di[12] = te[1] * this.halfHeight;
  98767. di[13] = te[4] * this.halfHeight;
  98768. di[14] = te[7] * this.halfHeight;
  98769. // halp Depth
  98770. di[15] = te[2] * this.halfDepth;
  98771. di[16] = te[5] * this.halfDepth;
  98772. di[17] = te[8] * this.halfDepth;
  98773. var wx = di[9];
  98774. var wy = di[10];
  98775. var wz = di[11];
  98776. var hx = di[12];
  98777. var hy = di[13];
  98778. var hz = di[14];
  98779. var dx = di[15];
  98780. var dy = di[16];
  98781. var dz = di[17];
  98782. var x = this.position.x;
  98783. var y = this.position.y;
  98784. var z = this.position.z;
  98785. var v = this.elements;
  98786. //v1
  98787. v[0] = x + wx + hx + dx;
  98788. v[1] = y + wy + hy + dy;
  98789. v[2] = z + wz + hz + dz;
  98790. //v2
  98791. v[3] = x + wx + hx - dx;
  98792. v[4] = y + wy + hy - dy;
  98793. v[5] = z + wz + hz - dz;
  98794. //v3
  98795. v[6] = x + wx - hx + dx;
  98796. v[7] = y + wy - hy + dy;
  98797. v[8] = z + wz - hz + dz;
  98798. //v4
  98799. v[9] = x + wx - hx - dx;
  98800. v[10] = y + wy - hy - dy;
  98801. v[11] = z + wz - hz - dz;
  98802. //v5
  98803. v[12] = x - wx + hx + dx;
  98804. v[13] = y - wy + hy + dy;
  98805. v[14] = z - wz + hz + dz;
  98806. //v6
  98807. v[15] = x - wx + hx - dx;
  98808. v[16] = y - wy + hy - dy;
  98809. v[17] = z - wz + hz - dz;
  98810. //v7
  98811. v[18] = x - wx - hx + dx;
  98812. v[19] = y - wy - hy + dy;
  98813. v[20] = z - wz - hz + dz;
  98814. //v8
  98815. v[21] = x - wx - hx - dx;
  98816. v[22] = y - wy - hy - dy;
  98817. v[23] = z - wz - hz - dz;
  98818. var w = di[9] < 0 ? -di[9] : di[9];
  98819. var h = di[10] < 0 ? -di[10] : di[10];
  98820. var d = di[11] < 0 ? -di[11] : di[11];
  98821. w = di[12] < 0 ? w - di[12] : w + di[12];
  98822. h = di[13] < 0 ? h - di[13] : h + di[13];
  98823. d = di[14] < 0 ? d - di[14] : d + di[14];
  98824. w = di[15] < 0 ? w - di[15] : w + di[15];
  98825. h = di[16] < 0 ? h - di[16] : h + di[16];
  98826. d = di[17] < 0 ? d - di[17] : d + di[17];
  98827. var p = OIMO.AABB_PROX;
  98828. this.aabb.set(
  98829. this.position.x - w - p, this.position.x + w + p,
  98830. this.position.y - h - p, this.position.y + h + p,
  98831. this.position.z - d - p, this.position.z + d + p
  98832. );
  98833. if (this.proxy != null) this.proxy.update();
  98834. };
  98835. /**
  98836. * A sphere shape.
  98837. * @author saharan
  98838. * @author lo-th
  98839. */
  98840. OIMO.SphereShape = function (config, radius) {
  98841. OIMO.Shape.call(this, config);
  98842. this.type = OIMO.SHAPE_SPHERE;
  98843. // The radius of the shape.
  98844. this.radius = radius;
  98845. };
  98846. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98847. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98848. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98849. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98850. out.mass = mass;
  98851. var inertia = mass * this.radius * this.radius * 0.4;
  98852. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98853. };
  98854. OIMO.SphereShape.prototype.updateProxy = function () {
  98855. var p = OIMO.AABB_PROX;
  98856. this.aabb.set(
  98857. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98858. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98859. this.position.z - this.radius - p, this.position.z + this.radius + p
  98860. );
  98861. if (this.proxy != null) this.proxy.update();
  98862. };
  98863. /**
  98864. * A cylinder shap.
  98865. * @author saharan
  98866. * @author lo-th
  98867. */
  98868. OIMO.CylinderShape = function (config, radius, height) {
  98869. OIMO.Shape.call(this, config);
  98870. this.type = OIMO.SHAPE_CYLINDER;
  98871. this.radius = radius;
  98872. this.height = height;
  98873. this.halfHeight = height * 0.5;
  98874. this.normalDirection = new OIMO.Vec3();
  98875. this.halfDirection = new OIMO.Vec3();
  98876. };
  98877. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98878. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98879. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98880. var rsq = this.radius * this.radius;
  98881. var mass = OIMO.PI * rsq * this.height * this.density;
  98882. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98883. var inertiaY = 0.5 * rsq;
  98884. out.mass = mass;
  98885. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98886. };
  98887. OIMO.CylinderShape.prototype.updateProxy = function () {
  98888. var te = this.rotation.elements;
  98889. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98890. xx = te[1] * te[1];
  98891. yy = te[4] * te[4];
  98892. zz = te[7] * te[7];
  98893. this.normalDirection.set(te[1], te[4], te[7]);
  98894. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98895. wx = 1 - xx;
  98896. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98897. if (len > 0) len = this.radius / len;
  98898. wx *= len;
  98899. hy = 1 - yy;
  98900. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98901. if (len > 0) len = this.radius / len;
  98902. hy *= len;
  98903. dz = 1 - zz;
  98904. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98905. if (len > 0) len = this.radius / len;
  98906. dz *= len;
  98907. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98908. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98909. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98910. w = wx < 0 ? w - wx : w + wx;
  98911. h = hy < 0 ? h - hy : h + hy;
  98912. d = dz < 0 ? d - dz : d + dz;
  98913. p = OIMO.AABB_PROX;
  98914. this.aabb.set(
  98915. this.position.x - w - p, this.position.x + w + p,
  98916. this.position.y - h - p, this.position.y + h + p,
  98917. this.position.z - d - p, this.position.z + d + p
  98918. );
  98919. if (this.proxy != null) this.proxy.update();
  98920. };
  98921. /**
  98922. * A tetra shape.
  98923. * @author xprogram
  98924. */
  98925. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98926. OIMO.Shape.call(this, config);
  98927. this.type = OIMO.SHAPE_TETRA;
  98928. // Vertices and faces of tetra
  98929. this.verts = [p1, p2, p3, p4];
  98930. this.faces = [
  98931. mtri(0, 1, 2),
  98932. mtri(1, 2, 3),
  98933. mtri(2, 3, 4),
  98934. mtri(4, 0, 1),
  98935. ];
  98936. };
  98937. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98938. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98939. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98940. // I guess you could calculate box mass and split it
  98941. // in half for the tetra...
  98942. };
  98943. OIMO.TetraShape.prototype.updateProxy = function () {
  98944. this.aabb.setFromPoints(this.verts);
  98945. if (this.proxy !== null)
  98946. this.proxy.update();
  98947. };
  98948. function mtri(a, b, c) {
  98949. return { a: a, b: b, c: c };
  98950. }
  98951. OIMO.CollisionDetector = function () {
  98952. this.flip = false;
  98953. };
  98954. OIMO.CollisionDetector.prototype = {
  98955. constructor: OIMO.CollisionDetector,
  98956. detectCollision: function (shape1, shape2, manifold) {
  98957. OIMO.Error("CollisionDetector", "Inheritance error.");
  98958. }
  98959. };
  98960. /**
  98961. * A collision detector which detects collisions between two boxes.
  98962. * @author saharan
  98963. */
  98964. OIMO.BoxBoxCollisionDetector = function () {
  98965. OIMO.CollisionDetector.call(this);
  98966. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  98967. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  98968. this.used = new OIMO_ARRAY_TYPE(8);
  98969. this.INF = 1 / 0;
  98970. };
  98971. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98972. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  98973. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98974. // What you are doing
  98975. // · I to prepare a separate axis of the fifteen
  98976. //-Six in each of three normal vectors of the xyz direction of the box both
  98977. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  98978. // · Calculate the depth to the separation axis
  98979. // Calculates the distance using the inner product and put the amount of embedment
  98980. // · However a vertical separation axis and side to weight a little to avoid vibration
  98981. // And end when there is a separate axis that is remote even one
  98982. // · I look for separation axis with little to dent most
  98983. // Men and if separation axis of the first six - end collision
  98984. // Heng If it separate axis of nine other - side collision
  98985. // Heng - case of a side collision
  98986. // · Find points of two sides on which you made ​​the separation axis
  98987. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  98988. //-Surface - the case of the plane crash
  98989. //-Box A, box B and the other a box of better made ​​a separate axis
  98990. // • 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
  98991. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  98992. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  98993. // • If more than one candidate 5 exists, scraping up to four
  98994. // For potential collision points of all, to examine the distance between the surface A
  98995. // • If you were on the inside surface of A, and the collision point
  98996. var b1;
  98997. var b2;
  98998. if (shape1.id < shape2.id) {
  98999. b1 = (shape1);
  99000. b2 = (shape2);
  99001. } else {
  99002. b1 = (shape2);
  99003. b2 = (shape1);
  99004. }
  99005. var V1 = b1.elements;
  99006. var V2 = b2.elements;
  99007. var D1 = b1.dimentions;
  99008. var D2 = b2.dimentions;
  99009. var p1 = b1.position;
  99010. var p2 = b2.position;
  99011. var p1x = p1.x;
  99012. var p1y = p1.y;
  99013. var p1z = p1.z;
  99014. var p2x = p2.x;
  99015. var p2y = p2.y;
  99016. var p2z = p2.z;
  99017. // diff
  99018. var dx = p2x - p1x;
  99019. var dy = p2y - p1y;
  99020. var dz = p2z - p1z;
  99021. // distance
  99022. var w1 = b1.halfWidth;
  99023. var h1 = b1.halfHeight;
  99024. var d1 = b1.halfDepth;
  99025. var w2 = b2.halfWidth;
  99026. var h2 = b2.halfHeight;
  99027. var d2 = b2.halfDepth;
  99028. // direction
  99029. // ----------------------------
  99030. // 15 separating axes
  99031. // 1~6: face
  99032. // 7~f: edge
  99033. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  99034. // ----------------------------
  99035. var a1x = D1[0];
  99036. var a1y = D1[1];
  99037. var a1z = D1[2];
  99038. var a2x = D1[3];
  99039. var a2y = D1[4];
  99040. var a2z = D1[5];
  99041. var a3x = D1[6];
  99042. var a3y = D1[7];
  99043. var a3z = D1[8];
  99044. var d1x = D1[9];
  99045. var d1y = D1[10];
  99046. var d1z = D1[11];
  99047. var d2x = D1[12];
  99048. var d2y = D1[13];
  99049. var d2z = D1[14];
  99050. var d3x = D1[15];
  99051. var d3y = D1[16];
  99052. var d3z = D1[17];
  99053. var a4x = D2[0];
  99054. var a4y = D2[1];
  99055. var a4z = D2[2];
  99056. var a5x = D2[3];
  99057. var a5y = D2[4];
  99058. var a5z = D2[5];
  99059. var a6x = D2[6];
  99060. var a6y = D2[7];
  99061. var a6z = D2[8];
  99062. var d4x = D2[9];
  99063. var d4y = D2[10];
  99064. var d4z = D2[11];
  99065. var d5x = D2[12];
  99066. var d5y = D2[13];
  99067. var d5z = D2[14];
  99068. var d6x = D2[15];
  99069. var d6y = D2[16];
  99070. var d6z = D2[17];
  99071. var a7x = a1y * a4z - a1z * a4y;
  99072. var a7y = a1z * a4x - a1x * a4z;
  99073. var a7z = a1x * a4y - a1y * a4x;
  99074. var a8x = a1y * a5z - a1z * a5y;
  99075. var a8y = a1z * a5x - a1x * a5z;
  99076. var a8z = a1x * a5y - a1y * a5x;
  99077. var a9x = a1y * a6z - a1z * a6y;
  99078. var a9y = a1z * a6x - a1x * a6z;
  99079. var a9z = a1x * a6y - a1y * a6x;
  99080. var aax = a2y * a4z - a2z * a4y;
  99081. var aay = a2z * a4x - a2x * a4z;
  99082. var aaz = a2x * a4y - a2y * a4x;
  99083. var abx = a2y * a5z - a2z * a5y;
  99084. var aby = a2z * a5x - a2x * a5z;
  99085. var abz = a2x * a5y - a2y * a5x;
  99086. var acx = a2y * a6z - a2z * a6y;
  99087. var acy = a2z * a6x - a2x * a6z;
  99088. var acz = a2x * a6y - a2y * a6x;
  99089. var adx = a3y * a4z - a3z * a4y;
  99090. var ady = a3z * a4x - a3x * a4z;
  99091. var adz = a3x * a4y - a3y * a4x;
  99092. var aex = a3y * a5z - a3z * a5y;
  99093. var aey = a3z * a5x - a3x * a5z;
  99094. var aez = a3x * a5y - a3y * a5x;
  99095. var afx = a3y * a6z - a3z * a6y;
  99096. var afy = a3z * a6x - a3x * a6z;
  99097. var afz = a3x * a6y - a3y * a6x;
  99098. // right or left flags
  99099. var right1;
  99100. var right2;
  99101. var right3;
  99102. var right4;
  99103. var right5;
  99104. var right6;
  99105. var right7;
  99106. var right8;
  99107. var right9;
  99108. var righta;
  99109. var rightb;
  99110. var rightc;
  99111. var rightd;
  99112. var righte;
  99113. var rightf;
  99114. // overlapping distances
  99115. var overlap1;
  99116. var overlap2;
  99117. var overlap3;
  99118. var overlap4;
  99119. var overlap5;
  99120. var overlap6;
  99121. var overlap7;
  99122. var overlap8;
  99123. var overlap9;
  99124. var overlapa;
  99125. var overlapb;
  99126. var overlapc;
  99127. var overlapd;
  99128. var overlape;
  99129. var overlapf;
  99130. // invalid flags
  99131. var invalid7 = false;
  99132. var invalid8 = false;
  99133. var invalid9 = false;
  99134. var invalida = false;
  99135. var invalidb = false;
  99136. var invalidc = false;
  99137. var invalidd = false;
  99138. var invalide = false;
  99139. var invalidf = false;
  99140. // temporary variables
  99141. var len;
  99142. var len1;
  99143. var len2;
  99144. var dot1;
  99145. var dot2;
  99146. var dot3;
  99147. // try axis 1
  99148. len = a1x * dx + a1y * dy + a1z * dz;
  99149. right1 = len > 0;
  99150. if (!right1) len = -len;
  99151. len1 = w1;
  99152. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99153. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99154. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99155. if (dot1 < 0) dot1 = -dot1;
  99156. if (dot2 < 0) dot2 = -dot2;
  99157. if (dot3 < 0) dot3 = -dot3;
  99158. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99159. overlap1 = len - len1 - len2;
  99160. if (overlap1 > 0) return;
  99161. // try axis 2
  99162. len = a2x * dx + a2y * dy + a2z * dz;
  99163. right2 = len > 0;
  99164. if (!right2) len = -len;
  99165. len1 = h1;
  99166. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99167. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99168. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99169. if (dot1 < 0) dot1 = -dot1;
  99170. if (dot2 < 0) dot2 = -dot2;
  99171. if (dot3 < 0) dot3 = -dot3;
  99172. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99173. overlap2 = len - len1 - len2;
  99174. if (overlap2 > 0) return;
  99175. // try axis 3
  99176. len = a3x * dx + a3y * dy + a3z * dz;
  99177. right3 = len > 0;
  99178. if (!right3) len = -len;
  99179. len1 = d1;
  99180. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99181. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99182. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99183. if (dot1 < 0) dot1 = -dot1;
  99184. if (dot2 < 0) dot2 = -dot2;
  99185. if (dot3 < 0) dot3 = -dot3;
  99186. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99187. overlap3 = len - len1 - len2;
  99188. if (overlap3 > 0) return;
  99189. // try axis 4
  99190. len = a4x * dx + a4y * dy + a4z * dz;
  99191. right4 = len > 0;
  99192. if (!right4) len = -len;
  99193. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99194. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99195. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99196. if (dot1 < 0) dot1 = -dot1;
  99197. if (dot2 < 0) dot2 = -dot2;
  99198. if (dot3 < 0) dot3 = -dot3;
  99199. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99200. len2 = w2;
  99201. overlap4 = (len - len1 - len2) * 1.0;
  99202. if (overlap4 > 0) return;
  99203. // try axis 5
  99204. len = a5x * dx + a5y * dy + a5z * dz;
  99205. right5 = len > 0;
  99206. if (!right5) len = -len;
  99207. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99208. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99209. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99210. if (dot1 < 0) dot1 = -dot1;
  99211. if (dot2 < 0) dot2 = -dot2;
  99212. if (dot3 < 0) dot3 = -dot3;
  99213. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99214. len2 = h2;
  99215. overlap5 = (len - len1 - len2) * 1.0;
  99216. if (overlap5 > 0) return;
  99217. // try axis 6
  99218. len = a6x * dx + a6y * dy + a6z * dz;
  99219. right6 = len > 0;
  99220. if (!right6) len = -len;
  99221. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99222. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99223. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99224. if (dot1 < 0) dot1 = -dot1;
  99225. if (dot2 < 0) dot2 = -dot2;
  99226. if (dot3 < 0) dot3 = -dot3;
  99227. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99228. len2 = d2;
  99229. overlap6 = (len - len1 - len2) * 1.0;
  99230. if (overlap6 > 0) return;
  99231. // try axis 7
  99232. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99233. if (len > 1e-5) {
  99234. len = 1 / OIMO.sqrt(len);
  99235. a7x *= len;
  99236. a7y *= len;
  99237. a7z *= len;
  99238. len = a7x * dx + a7y * dy + a7z * dz;
  99239. right7 = len > 0;
  99240. if (!right7) len = -len;
  99241. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99242. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99243. if (dot1 < 0) dot1 = -dot1;
  99244. if (dot2 < 0) dot2 = -dot2;
  99245. len1 = dot1 * h1 + dot2 * d1;
  99246. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99247. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99248. if (dot1 < 0) dot1 = -dot1;
  99249. if (dot2 < 0) dot2 = -dot2;
  99250. len2 = dot1 * h2 + dot2 * d2;
  99251. overlap7 = len - len1 - len2;
  99252. if (overlap7 > 0) return;
  99253. } else {
  99254. right7 = false;
  99255. overlap7 = 0;
  99256. invalid7 = true;
  99257. }
  99258. // try axis 8
  99259. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99260. if (len > 1e-5) {
  99261. len = 1 / OIMO.sqrt(len);
  99262. a8x *= len;
  99263. a8y *= len;
  99264. a8z *= len;
  99265. len = a8x * dx + a8y * dy + a8z * dz;
  99266. right8 = len > 0;
  99267. if (!right8) len = -len;
  99268. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99269. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99270. if (dot1 < 0) dot1 = -dot1;
  99271. if (dot2 < 0) dot2 = -dot2;
  99272. len1 = dot1 * h1 + dot2 * d1;
  99273. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99274. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99275. if (dot1 < 0) dot1 = -dot1;
  99276. if (dot2 < 0) dot2 = -dot2;
  99277. len2 = dot1 * w2 + dot2 * d2;
  99278. overlap8 = len - len1 - len2;
  99279. if (overlap8 > 0) return;
  99280. } else {
  99281. right8 = false;
  99282. overlap8 = 0;
  99283. invalid8 = true;
  99284. }
  99285. // try axis 9
  99286. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99287. if (len > 1e-5) {
  99288. len = 1 / OIMO.sqrt(len);
  99289. a9x *= len;
  99290. a9y *= len;
  99291. a9z *= len;
  99292. len = a9x * dx + a9y * dy + a9z * dz;
  99293. right9 = len > 0;
  99294. if (!right9) len = -len;
  99295. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99296. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99297. if (dot1 < 0) dot1 = -dot1;
  99298. if (dot2 < 0) dot2 = -dot2;
  99299. len1 = dot1 * h1 + dot2 * d1;
  99300. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99301. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99302. if (dot1 < 0) dot1 = -dot1;
  99303. if (dot2 < 0) dot2 = -dot2;
  99304. len2 = dot1 * w2 + dot2 * h2;
  99305. overlap9 = len - len1 - len2;
  99306. if (overlap9 > 0) return;
  99307. } else {
  99308. right9 = false;
  99309. overlap9 = 0;
  99310. invalid9 = true;
  99311. }
  99312. // try axis 10
  99313. len = aax * aax + aay * aay + aaz * aaz;
  99314. if (len > 1e-5) {
  99315. len = 1 / OIMO.sqrt(len);
  99316. aax *= len;
  99317. aay *= len;
  99318. aaz *= len;
  99319. len = aax * dx + aay * dy + aaz * dz;
  99320. righta = len > 0;
  99321. if (!righta) len = -len;
  99322. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99323. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99324. if (dot1 < 0) dot1 = -dot1;
  99325. if (dot2 < 0) dot2 = -dot2;
  99326. len1 = dot1 * w1 + dot2 * d1;
  99327. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99328. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99329. if (dot1 < 0) dot1 = -dot1;
  99330. if (dot2 < 0) dot2 = -dot2;
  99331. len2 = dot1 * h2 + dot2 * d2;
  99332. overlapa = len - len1 - len2;
  99333. if (overlapa > 0) return;
  99334. } else {
  99335. righta = false;
  99336. overlapa = 0;
  99337. invalida = true;
  99338. }
  99339. // try axis 11
  99340. len = abx * abx + aby * aby + abz * abz;
  99341. if (len > 1e-5) {
  99342. len = 1 / OIMO.sqrt(len);
  99343. abx *= len;
  99344. aby *= len;
  99345. abz *= len;
  99346. len = abx * dx + aby * dy + abz * dz;
  99347. rightb = len > 0;
  99348. if (!rightb) len = -len;
  99349. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99350. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99351. if (dot1 < 0) dot1 = -dot1;
  99352. if (dot2 < 0) dot2 = -dot2;
  99353. len1 = dot1 * w1 + dot2 * d1;
  99354. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99355. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99356. if (dot1 < 0) dot1 = -dot1;
  99357. if (dot2 < 0) dot2 = -dot2;
  99358. len2 = dot1 * w2 + dot2 * d2;
  99359. overlapb = len - len1 - len2;
  99360. if (overlapb > 0) return;
  99361. } else {
  99362. rightb = false;
  99363. overlapb = 0;
  99364. invalidb = true;
  99365. }
  99366. // try axis 12
  99367. len = acx * acx + acy * acy + acz * acz;
  99368. if (len > 1e-5) {
  99369. len = 1 / OIMO.sqrt(len);
  99370. acx *= len;
  99371. acy *= len;
  99372. acz *= len;
  99373. len = acx * dx + acy * dy + acz * dz;
  99374. rightc = len > 0;
  99375. if (!rightc) len = -len;
  99376. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99377. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99378. if (dot1 < 0) dot1 = -dot1;
  99379. if (dot2 < 0) dot2 = -dot2;
  99380. len1 = dot1 * w1 + dot2 * d1;
  99381. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99382. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99383. if (dot1 < 0) dot1 = -dot1;
  99384. if (dot2 < 0) dot2 = -dot2;
  99385. len2 = dot1 * w2 + dot2 * h2;
  99386. overlapc = len - len1 - len2;
  99387. if (overlapc > 0) return;
  99388. } else {
  99389. rightc = false;
  99390. overlapc = 0;
  99391. invalidc = true;
  99392. }
  99393. // try axis 13
  99394. len = adx * adx + ady * ady + adz * adz;
  99395. if (len > 1e-5) {
  99396. len = 1 / OIMO.sqrt(len);
  99397. adx *= len;
  99398. ady *= len;
  99399. adz *= len;
  99400. len = adx * dx + ady * dy + adz * dz;
  99401. rightd = len > 0;
  99402. if (!rightd) len = -len;
  99403. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99404. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99405. if (dot1 < 0) dot1 = -dot1;
  99406. if (dot2 < 0) dot2 = -dot2;
  99407. len1 = dot1 * w1 + dot2 * h1;
  99408. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99409. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99410. if (dot1 < 0) dot1 = -dot1;
  99411. if (dot2 < 0) dot2 = -dot2;
  99412. len2 = dot1 * h2 + dot2 * d2;
  99413. overlapd = len - len1 - len2;
  99414. if (overlapd > 0) return;
  99415. } else {
  99416. rightd = false;
  99417. overlapd = 0;
  99418. invalidd = true;
  99419. }
  99420. // try axis 14
  99421. len = aex * aex + aey * aey + aez * aez;
  99422. if (len > 1e-5) {
  99423. len = 1 / OIMO.sqrt(len);
  99424. aex *= len;
  99425. aey *= len;
  99426. aez *= len;
  99427. len = aex * dx + aey * dy + aez * dz;
  99428. righte = len > 0;
  99429. if (!righte) len = -len;
  99430. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99431. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99432. if (dot1 < 0) dot1 = -dot1;
  99433. if (dot2 < 0) dot2 = -dot2;
  99434. len1 = dot1 * w1 + dot2 * h1;
  99435. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99436. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99437. if (dot1 < 0) dot1 = -dot1;
  99438. if (dot2 < 0) dot2 = -dot2;
  99439. len2 = dot1 * w2 + dot2 * d2;
  99440. overlape = len - len1 - len2;
  99441. if (overlape > 0) return;
  99442. } else {
  99443. righte = false;
  99444. overlape = 0;
  99445. invalide = true;
  99446. }
  99447. // try axis 15
  99448. len = afx * afx + afy * afy + afz * afz;
  99449. if (len > 1e-5) {
  99450. len = 1 / OIMO.sqrt(len);
  99451. afx *= len;
  99452. afy *= len;
  99453. afz *= len;
  99454. len = afx * dx + afy * dy + afz * dz;
  99455. rightf = len > 0;
  99456. if (!rightf) len = -len;
  99457. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99458. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99459. if (dot1 < 0) dot1 = -dot1;
  99460. if (dot2 < 0) dot2 = -dot2;
  99461. len1 = dot1 * w1 + dot2 * h1;
  99462. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99463. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99464. if (dot1 < 0) dot1 = -dot1;
  99465. if (dot2 < 0) dot2 = -dot2;
  99466. len2 = dot1 * w2 + dot2 * h2;
  99467. overlapf = len - len1 - len2;
  99468. if (overlapf > 0) return;
  99469. } else {
  99470. rightf = false;
  99471. overlapf = 0;
  99472. invalidf = true;
  99473. }
  99474. // boxes are overlapping
  99475. var depth = overlap1;
  99476. var depth2 = overlap1;
  99477. var minIndex = 0;
  99478. var right = right1;
  99479. if (overlap2 > depth2) {
  99480. depth = overlap2;
  99481. depth2 = overlap2;
  99482. minIndex = 1;
  99483. right = right2;
  99484. }
  99485. if (overlap3 > depth2) {
  99486. depth = overlap3;
  99487. depth2 = overlap3;
  99488. minIndex = 2;
  99489. right = right3;
  99490. }
  99491. if (overlap4 > depth2) {
  99492. depth = overlap4;
  99493. depth2 = overlap4;
  99494. minIndex = 3;
  99495. right = right4;
  99496. }
  99497. if (overlap5 > depth2) {
  99498. depth = overlap5;
  99499. depth2 = overlap5;
  99500. minIndex = 4;
  99501. right = right5;
  99502. }
  99503. if (overlap6 > depth2) {
  99504. depth = overlap6;
  99505. depth2 = overlap6;
  99506. minIndex = 5;
  99507. right = right6;
  99508. }
  99509. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99510. depth = overlap7;
  99511. depth2 = overlap7 - 0.01;
  99512. minIndex = 6;
  99513. right = right7;
  99514. }
  99515. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99516. depth = overlap8;
  99517. depth2 = overlap8 - 0.01;
  99518. minIndex = 7;
  99519. right = right8;
  99520. }
  99521. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99522. depth = overlap9;
  99523. depth2 = overlap9 - 0.01;
  99524. minIndex = 8;
  99525. right = right9;
  99526. }
  99527. if (overlapa - 0.01 > depth2 && !invalida) {
  99528. depth = overlapa;
  99529. depth2 = overlapa - 0.01;
  99530. minIndex = 9;
  99531. right = righta;
  99532. }
  99533. if (overlapb - 0.01 > depth2 && !invalidb) {
  99534. depth = overlapb;
  99535. depth2 = overlapb - 0.01;
  99536. minIndex = 10;
  99537. right = rightb;
  99538. }
  99539. if (overlapc - 0.01 > depth2 && !invalidc) {
  99540. depth = overlapc;
  99541. depth2 = overlapc - 0.01;
  99542. minIndex = 11;
  99543. right = rightc;
  99544. }
  99545. if (overlapd - 0.01 > depth2 && !invalidd) {
  99546. depth = overlapd;
  99547. depth2 = overlapd - 0.01;
  99548. minIndex = 12;
  99549. right = rightd;
  99550. }
  99551. if (overlape - 0.01 > depth2 && !invalide) {
  99552. depth = overlape;
  99553. depth2 = overlape - 0.01;
  99554. minIndex = 13;
  99555. right = righte;
  99556. }
  99557. if (overlapf - 0.01 > depth2 && !invalidf) {
  99558. depth = overlapf;
  99559. minIndex = 14;
  99560. right = rightf;
  99561. }
  99562. // normal
  99563. var nx = 0;
  99564. var ny = 0;
  99565. var nz = 0;
  99566. // edge line or face side normal
  99567. var n1x = 0;
  99568. var n1y = 0;
  99569. var n1z = 0;
  99570. var n2x = 0;
  99571. var n2y = 0;
  99572. var n2z = 0;
  99573. // center of current face
  99574. var cx = 0;
  99575. var cy = 0;
  99576. var cz = 0;
  99577. // face side
  99578. var s1x = 0;
  99579. var s1y = 0;
  99580. var s1z = 0;
  99581. var s2x = 0;
  99582. var s2y = 0;
  99583. var s2z = 0;
  99584. // swap b1 b2
  99585. var swap = false;
  99586. //_______________________________________
  99587. if (minIndex == 0) {// b1.x * b2
  99588. if (right) {
  99589. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99590. nx = a1x; ny = a1y; nz = a1z;
  99591. } else {
  99592. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99593. nx = -a1x; ny = -a1y; nz = -a1z;
  99594. }
  99595. s1x = d2x; s1y = d2y; s1z = d2z;
  99596. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99597. s2x = d3x; s2y = d3y; s2z = d3z;
  99598. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99599. }
  99600. else if (minIndex == 1) {// b1.y * b2
  99601. if (right) {
  99602. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99603. nx = a2x; ny = a2y; nz = a2z;
  99604. } else {
  99605. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99606. nx = -a2x; ny = -a2y; nz = -a2z;
  99607. }
  99608. s1x = d1x; s1y = d1y; s1z = d1z;
  99609. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99610. s2x = d3x; s2y = d3y; s2z = d3z;
  99611. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99612. }
  99613. else if (minIndex == 2) {// b1.z * b2
  99614. if (right) {
  99615. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99616. nx = a3x; ny = a3y; nz = a3z;
  99617. } else {
  99618. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99619. nx = -a3x; ny = -a3y; nz = -a3z;
  99620. }
  99621. s1x = d1x; s1y = d1y; s1z = d1z;
  99622. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99623. s2x = d2x; s2y = d2y; s2z = d2z;
  99624. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99625. }
  99626. else if (minIndex == 3) {// b2.x * b1
  99627. swap = true;
  99628. if (!right) {
  99629. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99630. nx = a4x; ny = a4y; nz = a4z;
  99631. } else {
  99632. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99633. nx = -a4x; ny = -a4y; nz = -a4z;
  99634. }
  99635. s1x = d5x; s1y = d5y; s1z = d5z;
  99636. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99637. s2x = d6x; s2y = d6y; s2z = d6z;
  99638. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99639. }
  99640. else if (minIndex == 4) {// b2.y * b1
  99641. swap = true;
  99642. if (!right) {
  99643. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99644. nx = a5x; ny = a5y; nz = a5z;
  99645. } else {
  99646. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99647. nx = -a5x; ny = -a5y; nz = -a5z;
  99648. }
  99649. s1x = d4x; s1y = d4y; s1z = d4z;
  99650. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99651. s2x = d6x; s2y = d6y; s2z = d6z;
  99652. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99653. }
  99654. else if (minIndex == 5) {// b2.z * b1
  99655. swap = true;
  99656. if (!right) {
  99657. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99658. nx = a6x; ny = a6y; nz = a6z;
  99659. } else {
  99660. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99661. nx = -a6x; ny = -a6y; nz = -a6z;
  99662. }
  99663. s1x = d4x; s1y = d4y; s1z = d4z;
  99664. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99665. s2x = d5x; s2y = d5y; s2z = d5z;
  99666. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99667. }
  99668. else if (minIndex == 6) {// b1.x * b2.x
  99669. nx = a7x; ny = a7y; nz = a7z;
  99670. n1x = a1x; n1y = a1y; n1z = a1z;
  99671. n2x = a4x; n2y = a4y; n2z = a4z;
  99672. }
  99673. else if (minIndex == 7) {// b1.x * b2.y
  99674. nx = a8x; ny = a8y; nz = a8z;
  99675. n1x = a1x; n1y = a1y; n1z = a1z;
  99676. n2x = a5x; n2y = a5y; n2z = a5z;
  99677. }
  99678. else if (minIndex == 8) {// b1.x * b2.z
  99679. nx = a9x; ny = a9y; nz = a9z;
  99680. n1x = a1x; n1y = a1y; n1z = a1z;
  99681. n2x = a6x; n2y = a6y; n2z = a6z;
  99682. }
  99683. else if (minIndex == 9) {// b1.y * b2.x
  99684. nx = aax; ny = aay; nz = aaz;
  99685. n1x = a2x; n1y = a2y; n1z = a2z;
  99686. n2x = a4x; n2y = a4y; n2z = a4z
  99687. }
  99688. else if (minIndex == 10) {// b1.y * b2.y
  99689. nx = abx; ny = aby; nz = abz;
  99690. n1x = a2x; n1y = a2y; n1z = a2z;
  99691. n2x = a5x; n2y = a5y; n2z = a5z;
  99692. }
  99693. else if (minIndex == 11) {// b1.y * b2.z
  99694. nx = acx; ny = acy; nz = acz;
  99695. n1x = a2x; n1y = a2y; n1z = a2z;
  99696. n2x = a6x; n2y = a6y; n2z = a6z;
  99697. }
  99698. else if (minIndex == 12) {// b1.z * b2.x
  99699. nx = adx; ny = ady; nz = adz;
  99700. n1x = a3x; n1y = a3y; n1z = a3z;
  99701. n2x = a4x; n2y = a4y; n2z = a4z;
  99702. }
  99703. else if (minIndex == 13) {// b1.z * b2.y
  99704. nx = aex; ny = aey; nz = aez;
  99705. n1x = a3x; n1y = a3y; n1z = a3z;
  99706. n2x = a5x; n2y = a5y; n2z = a5z;
  99707. }
  99708. else if (minIndex == 14) {// b1.z * b2.z
  99709. nx = afx; ny = afy; nz = afz;
  99710. n1x = a3x; n1y = a3y; n1z = a3z;
  99711. n2x = a6x; n2y = a6y; n2z = a6z;
  99712. }
  99713. //__________________________________________
  99714. var v;
  99715. if (minIndex > 5) {
  99716. if (!right) {
  99717. nx = -nx; ny = -ny; nz = -nz;
  99718. }
  99719. var distance;
  99720. var maxDistance;
  99721. var vx;
  99722. var vy;
  99723. var vz;
  99724. var v1x;
  99725. var v1y;
  99726. var v1z;
  99727. var v2x;
  99728. var v2y;
  99729. var v2z;
  99730. //vertex1;
  99731. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99732. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99733. //vertex2;
  99734. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99735. distance = nx * vx + ny * vy + nz * vz;
  99736. if (distance > maxDistance) {
  99737. maxDistance = distance;
  99738. v1x = vx; v1y = vy; v1z = vz;
  99739. }
  99740. //vertex3;
  99741. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99742. distance = nx * vx + ny * vy + nz * vz;
  99743. if (distance > maxDistance) {
  99744. maxDistance = distance;
  99745. v1x = vx; v1y = vy; v1z = vz;
  99746. }
  99747. //vertex4;
  99748. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99749. distance = nx * vx + ny * vy + nz * vz;
  99750. if (distance > maxDistance) {
  99751. maxDistance = distance;
  99752. v1x = vx; v1y = vy; v1z = vz;
  99753. }
  99754. //vertex5;
  99755. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99756. distance = nx * vx + ny * vy + nz * vz;
  99757. if (distance > maxDistance) {
  99758. maxDistance = distance;
  99759. v1x = vx; v1y = vy; v1z = vz;
  99760. }
  99761. //vertex6;
  99762. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99763. distance = nx * vx + ny * vy + nz * vz;
  99764. if (distance > maxDistance) {
  99765. maxDistance = distance;
  99766. v1x = vx; v1y = vy; v1z = vz;
  99767. }
  99768. //vertex7;
  99769. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99770. distance = nx * vx + ny * vy + nz * vz;
  99771. if (distance > maxDistance) {
  99772. maxDistance = distance;
  99773. v1x = vx; v1y = vy; v1z = vz;
  99774. }
  99775. //vertex8;
  99776. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99777. distance = nx * vx + ny * vy + nz * vz;
  99778. if (distance > maxDistance) {
  99779. maxDistance = distance;
  99780. v1x = vx; v1y = vy; v1z = vz;
  99781. }
  99782. //vertex1;
  99783. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99784. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99785. //vertex2;
  99786. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99787. distance = nx * vx + ny * vy + nz * vz;
  99788. if (distance < maxDistance) {
  99789. maxDistance = distance;
  99790. v2x = vx; v2y = vy; v2z = vz;
  99791. }
  99792. //vertex3;
  99793. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99794. distance = nx * vx + ny * vy + nz * vz;
  99795. if (distance < maxDistance) {
  99796. maxDistance = distance;
  99797. v2x = vx; v2y = vy; v2z = vz;
  99798. }
  99799. //vertex4;
  99800. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99801. distance = nx * vx + ny * vy + nz * vz;
  99802. if (distance < maxDistance) {
  99803. maxDistance = distance;
  99804. v2x = vx; v2y = vy; v2z = vz;
  99805. }
  99806. //vertex5;
  99807. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99808. distance = nx * vx + ny * vy + nz * vz;
  99809. if (distance < maxDistance) {
  99810. maxDistance = distance;
  99811. v2x = vx; v2y = vy; v2z = vz;
  99812. }
  99813. //vertex6;
  99814. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99815. distance = nx * vx + ny * vy + nz * vz;
  99816. if (distance < maxDistance) {
  99817. maxDistance = distance;
  99818. v2x = vx; v2y = vy; v2z = vz;
  99819. }
  99820. //vertex7;
  99821. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99822. distance = nx * vx + ny * vy + nz * vz;
  99823. if (distance < maxDistance) {
  99824. maxDistance = distance;
  99825. v2x = vx; v2y = vy; v2z = vz;
  99826. }
  99827. //vertex8;
  99828. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99829. distance = nx * vx + ny * vy + nz * vz;
  99830. if (distance < maxDistance) {
  99831. maxDistance = distance;
  99832. v2x = vx; v2y = vy; v2z = vz;
  99833. }
  99834. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99835. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99836. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99837. 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);
  99838. return;
  99839. }
  99840. // now detect face-face collision...
  99841. // target quad
  99842. var q1x;
  99843. var q1y;
  99844. var q1z;
  99845. var q2x;
  99846. var q2y;
  99847. var q2z;
  99848. var q3x;
  99849. var q3y;
  99850. var q3z;
  99851. var q4x;
  99852. var q4y;
  99853. var q4z;
  99854. // search support face and vertex
  99855. var minDot = 1;
  99856. var dot = 0;
  99857. var minDotIndex = 0;
  99858. if (swap) {
  99859. dot = a1x * nx + a1y * ny + a1z * nz;
  99860. if (dot < minDot) {
  99861. minDot = dot;
  99862. minDotIndex = 0;
  99863. }
  99864. if (-dot < minDot) {
  99865. minDot = -dot;
  99866. minDotIndex = 1;
  99867. }
  99868. dot = a2x * nx + a2y * ny + a2z * nz;
  99869. if (dot < minDot) {
  99870. minDot = dot;
  99871. minDotIndex = 2;
  99872. }
  99873. if (-dot < minDot) {
  99874. minDot = -dot;
  99875. minDotIndex = 3;
  99876. }
  99877. dot = a3x * nx + a3y * ny + a3z * nz;
  99878. if (dot < minDot) {
  99879. minDot = dot;
  99880. minDotIndex = 4;
  99881. }
  99882. if (-dot < minDot) {
  99883. minDot = -dot;
  99884. minDotIndex = 5;
  99885. }
  99886. if (minDotIndex == 0) {// x+ face
  99887. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99888. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99889. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99890. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99891. }
  99892. else if (minDotIndex == 1) {// x- face
  99893. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99894. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99895. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99896. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99897. }
  99898. else if (minDotIndex == 2) {// y+ face
  99899. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99900. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99901. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99902. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99903. }
  99904. else if (minDotIndex == 3) {// y- face
  99905. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99906. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99907. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99908. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99909. }
  99910. else if (minDotIndex == 4) {// z+ face
  99911. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99912. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99913. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99914. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99915. }
  99916. else if (minDotIndex == 5) {// z- face
  99917. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99918. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99919. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99920. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99921. }
  99922. } else {
  99923. dot = a4x * nx + a4y * ny + a4z * nz;
  99924. if (dot < minDot) {
  99925. minDot = dot;
  99926. minDotIndex = 0;
  99927. }
  99928. if (-dot < minDot) {
  99929. minDot = -dot;
  99930. minDotIndex = 1;
  99931. }
  99932. dot = a5x * nx + a5y * ny + a5z * nz;
  99933. if (dot < minDot) {
  99934. minDot = dot;
  99935. minDotIndex = 2;
  99936. }
  99937. if (-dot < minDot) {
  99938. minDot = -dot;
  99939. minDotIndex = 3;
  99940. }
  99941. dot = a6x * nx + a6y * ny + a6z * nz;
  99942. if (dot < minDot) {
  99943. minDot = dot;
  99944. minDotIndex = 4;
  99945. }
  99946. if (-dot < minDot) {
  99947. minDot = -dot;
  99948. minDotIndex = 5;
  99949. }
  99950. //______________________________________________________
  99951. if (minDotIndex == 0) {// x+ face
  99952. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  99953. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  99954. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  99955. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  99956. }
  99957. else if (minDotIndex == 1) {// x- face
  99958. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  99959. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  99960. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  99961. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  99962. }
  99963. else if (minDotIndex == 2) {// y+ face
  99964. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99965. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  99966. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  99967. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99968. }
  99969. else if (minDotIndex == 3) {// y- face
  99970. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  99971. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99972. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99973. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  99974. }
  99975. else if (minDotIndex == 4) {// z+ face
  99976. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99977. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  99978. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99979. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  99980. }
  99981. else if (minDotIndex == 5) {// z- face
  99982. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  99983. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99984. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  99985. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99986. }
  99987. }
  99988. // clip vertices
  99989. var numClipVertices;
  99990. var numAddedClipVertices;
  99991. var index;
  99992. var x1;
  99993. var y1;
  99994. var z1;
  99995. var x2;
  99996. var y2;
  99997. var z2;
  99998. this.clipVertices1[0] = q1x;
  99999. this.clipVertices1[1] = q1y;
  100000. this.clipVertices1[2] = q1z;
  100001. this.clipVertices1[3] = q2x;
  100002. this.clipVertices1[4] = q2y;
  100003. this.clipVertices1[5] = q2z;
  100004. this.clipVertices1[6] = q3x;
  100005. this.clipVertices1[7] = q3y;
  100006. this.clipVertices1[8] = q3z;
  100007. this.clipVertices1[9] = q4x;
  100008. this.clipVertices1[10] = q4y;
  100009. this.clipVertices1[11] = q4z;
  100010. numAddedClipVertices = 0;
  100011. x1 = this.clipVertices1[9];
  100012. y1 = this.clipVertices1[10];
  100013. z1 = this.clipVertices1[11];
  100014. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  100015. //var i = 4;
  100016. //while(i--){
  100017. for (var i = 0; i < 4; i++) {
  100018. index = i * 3;
  100019. x2 = this.clipVertices1[index];
  100020. y2 = this.clipVertices1[index + 1];
  100021. z2 = this.clipVertices1[index + 2];
  100022. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  100023. if (dot1 > 0) {
  100024. if (dot2 > 0) {
  100025. index = numAddedClipVertices * 3;
  100026. numAddedClipVertices++;
  100027. this.clipVertices2[index] = x2;
  100028. this.clipVertices2[index + 1] = y2;
  100029. this.clipVertices2[index + 2] = z2;
  100030. } else {
  100031. index = numAddedClipVertices * 3;
  100032. numAddedClipVertices++;
  100033. t = dot1 / (dot1 - dot2);
  100034. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100035. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100036. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100037. }
  100038. } else {
  100039. if (dot2 > 0) {
  100040. index = numAddedClipVertices * 3;
  100041. numAddedClipVertices++;
  100042. t = dot1 / (dot1 - dot2);
  100043. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100044. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100045. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100046. index = numAddedClipVertices * 3;
  100047. numAddedClipVertices++;
  100048. this.clipVertices2[index] = x2;
  100049. this.clipVertices2[index + 1] = y2;
  100050. this.clipVertices2[index + 2] = z2;
  100051. }
  100052. }
  100053. x1 = x2;
  100054. y1 = y2;
  100055. z1 = z2;
  100056. dot1 = dot2;
  100057. }
  100058. numClipVertices = numAddedClipVertices;
  100059. if (numClipVertices == 0) return;
  100060. numAddedClipVertices = 0;
  100061. index = (numClipVertices - 1) * 3;
  100062. x1 = this.clipVertices2[index];
  100063. y1 = this.clipVertices2[index + 1];
  100064. z1 = this.clipVertices2[index + 2];
  100065. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  100066. //i = numClipVertices;
  100067. //while(i--){
  100068. for (i = 0; i < numClipVertices; i++) {
  100069. index = i * 3;
  100070. x2 = this.clipVertices2[index];
  100071. y2 = this.clipVertices2[index + 1];
  100072. z2 = this.clipVertices2[index + 2];
  100073. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  100074. if (dot1 > 0) {
  100075. if (dot2 > 0) {
  100076. index = numAddedClipVertices * 3;
  100077. numAddedClipVertices++;
  100078. this.clipVertices1[index] = x2;
  100079. this.clipVertices1[index + 1] = y2;
  100080. this.clipVertices1[index + 2] = z2;
  100081. } else {
  100082. index = numAddedClipVertices * 3;
  100083. numAddedClipVertices++;
  100084. t = dot1 / (dot1 - dot2);
  100085. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100086. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100087. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100088. }
  100089. } else {
  100090. if (dot2 > 0) {
  100091. index = numAddedClipVertices * 3;
  100092. numAddedClipVertices++;
  100093. t = dot1 / (dot1 - dot2);
  100094. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100095. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100096. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100097. index = numAddedClipVertices * 3;
  100098. numAddedClipVertices++;
  100099. this.clipVertices1[index] = x2;
  100100. this.clipVertices1[index + 1] = y2;
  100101. this.clipVertices1[index + 2] = z2;
  100102. }
  100103. }
  100104. x1 = x2;
  100105. y1 = y2;
  100106. z1 = z2;
  100107. dot1 = dot2;
  100108. }
  100109. numClipVertices = numAddedClipVertices;
  100110. if (numClipVertices == 0) return;
  100111. numAddedClipVertices = 0;
  100112. index = (numClipVertices - 1) * 3;
  100113. x1 = this.clipVertices1[index];
  100114. y1 = this.clipVertices1[index + 1];
  100115. z1 = this.clipVertices1[index + 2];
  100116. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100117. //i = numClipVertices;
  100118. //while(i--){
  100119. for (i = 0; i < numClipVertices; i++) {
  100120. index = i * 3;
  100121. x2 = this.clipVertices1[index];
  100122. y2 = this.clipVertices1[index + 1];
  100123. z2 = this.clipVertices1[index + 2];
  100124. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100125. if (dot1 > 0) {
  100126. if (dot2 > 0) {
  100127. index = numAddedClipVertices * 3;
  100128. numAddedClipVertices++;
  100129. this.clipVertices2[index] = x2;
  100130. this.clipVertices2[index + 1] = y2;
  100131. this.clipVertices2[index + 2] = z2;
  100132. } else {
  100133. index = numAddedClipVertices * 3;
  100134. numAddedClipVertices++;
  100135. t = dot1 / (dot1 - dot2);
  100136. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100137. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100138. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100139. }
  100140. } else {
  100141. if (dot2 > 0) {
  100142. index = numAddedClipVertices * 3;
  100143. numAddedClipVertices++;
  100144. t = dot1 / (dot1 - dot2);
  100145. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100146. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100147. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100148. index = numAddedClipVertices * 3;
  100149. numAddedClipVertices++;
  100150. this.clipVertices2[index] = x2;
  100151. this.clipVertices2[index + 1] = y2;
  100152. this.clipVertices2[index + 2] = z2;
  100153. }
  100154. }
  100155. x1 = x2;
  100156. y1 = y2;
  100157. z1 = z2;
  100158. dot1 = dot2;
  100159. }
  100160. numClipVertices = numAddedClipVertices;
  100161. if (numClipVertices == 0) return;
  100162. numAddedClipVertices = 0;
  100163. index = (numClipVertices - 1) * 3;
  100164. x1 = this.clipVertices2[index];
  100165. y1 = this.clipVertices2[index + 1];
  100166. z1 = this.clipVertices2[index + 2];
  100167. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100168. //i = numClipVertices;
  100169. //while(i--){
  100170. for (i = 0; i < numClipVertices; i++) {
  100171. index = i * 3;
  100172. x2 = this.clipVertices2[index];
  100173. y2 = this.clipVertices2[index + 1];
  100174. z2 = this.clipVertices2[index + 2];
  100175. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100176. if (dot1 > 0) {
  100177. if (dot2 > 0) {
  100178. index = numAddedClipVertices * 3;
  100179. numAddedClipVertices++;
  100180. this.clipVertices1[index] = x2;
  100181. this.clipVertices1[index + 1] = y2;
  100182. this.clipVertices1[index + 2] = z2;
  100183. } else {
  100184. index = numAddedClipVertices * 3;
  100185. numAddedClipVertices++;
  100186. t = dot1 / (dot1 - dot2);
  100187. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100188. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100189. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100190. }
  100191. } else {
  100192. if (dot2 > 0) {
  100193. index = numAddedClipVertices * 3;
  100194. numAddedClipVertices++;
  100195. t = dot1 / (dot1 - dot2);
  100196. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100197. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100198. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100199. index = numAddedClipVertices * 3;
  100200. numAddedClipVertices++;
  100201. this.clipVertices1[index] = x2;
  100202. this.clipVertices1[index + 1] = y2;
  100203. this.clipVertices1[index + 2] = z2;
  100204. }
  100205. }
  100206. x1 = x2;
  100207. y1 = y2;
  100208. z1 = z2;
  100209. dot1 = dot2;
  100210. }
  100211. numClipVertices = numAddedClipVertices;
  100212. if (swap) {
  100213. var tb = b1;
  100214. b1 = b2;
  100215. b2 = tb;
  100216. }
  100217. if (numClipVertices == 0) return;
  100218. var flipped = b1 != shape1;
  100219. if (numClipVertices > 4) {
  100220. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100221. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100222. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100223. n1x = q1x - x1;
  100224. n1y = q1y - y1;
  100225. n1z = q1z - z1;
  100226. n2x = q2x - x1;
  100227. n2y = q2y - y1;
  100228. n2z = q2z - z1;
  100229. var index1 = 0;
  100230. var index2 = 0;
  100231. var index3 = 0;
  100232. var index4 = 0;
  100233. var maxDot = -this.INF;
  100234. minDot = this.INF;
  100235. //i = numClipVertices;
  100236. //while(i--){
  100237. for (i = 0; i < numClipVertices; i++) {
  100238. this.used[i] = false;
  100239. index = i * 3;
  100240. x1 = this.clipVertices1[index];
  100241. y1 = this.clipVertices1[index + 1];
  100242. z1 = this.clipVertices1[index + 2];
  100243. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100244. if (dot < minDot) {
  100245. minDot = dot;
  100246. index1 = i;
  100247. }
  100248. if (dot > maxDot) {
  100249. maxDot = dot;
  100250. index3 = i;
  100251. }
  100252. }
  100253. this.used[index1] = true;
  100254. this.used[index3] = true;
  100255. maxDot = -this.INF;
  100256. minDot = this.INF;
  100257. //i = numClipVertices;
  100258. //while(i--){
  100259. for (i = 0; i < numClipVertices; i++) {
  100260. if (this.used[i]) continue;
  100261. index = i * 3;
  100262. x1 = this.clipVertices1[index];
  100263. y1 = this.clipVertices1[index + 1];
  100264. z1 = this.clipVertices1[index + 2];
  100265. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100266. if (dot < minDot) {
  100267. minDot = dot;
  100268. index2 = i;
  100269. }
  100270. if (dot > maxDot) {
  100271. maxDot = dot;
  100272. index4 = i;
  100273. }
  100274. }
  100275. index = index1 * 3;
  100276. x1 = this.clipVertices1[index];
  100277. y1 = this.clipVertices1[index + 1];
  100278. z1 = this.clipVertices1[index + 2];
  100279. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100280. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100281. index = index2 * 3;
  100282. x1 = this.clipVertices1[index];
  100283. y1 = this.clipVertices1[index + 1];
  100284. z1 = this.clipVertices1[index + 2];
  100285. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100286. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100287. index = index3 * 3;
  100288. x1 = this.clipVertices1[index];
  100289. y1 = this.clipVertices1[index + 1];
  100290. z1 = this.clipVertices1[index + 2];
  100291. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100292. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100293. index = index4 * 3;
  100294. x1 = this.clipVertices1[index];
  100295. y1 = this.clipVertices1[index + 1];
  100296. z1 = this.clipVertices1[index + 2];
  100297. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100298. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100299. } else {
  100300. //i = numClipVertices;
  100301. //while(i--){
  100302. for (i = 0; i < numClipVertices; i++) {
  100303. index = i * 3;
  100304. x1 = this.clipVertices1[index];
  100305. y1 = this.clipVertices1[index + 1];
  100306. z1 = this.clipVertices1[index + 2];
  100307. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100308. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100309. }
  100310. }
  100311. };
  100312. /**
  100313. * A collision detector which detects collisions between sphere and box.
  100314. * @author saharan
  100315. */
  100316. OIMO.SphereBoxCollisionDetector = function (flip) {
  100317. OIMO.CollisionDetector.call(this);
  100318. this.flip = flip;
  100319. };
  100320. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100321. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100322. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100323. var s;
  100324. var b;
  100325. if (this.flip) {
  100326. s = (shape2);
  100327. b = (shape1);
  100328. } else {
  100329. s = (shape1);
  100330. b = (shape2);
  100331. }
  100332. var D = b.dimentions;
  100333. var ps = s.position;
  100334. var psx = ps.x;
  100335. var psy = ps.y;
  100336. var psz = ps.z;
  100337. var pb = b.position;
  100338. var pbx = pb.x;
  100339. var pby = pb.y;
  100340. var pbz = pb.z;
  100341. var rad = s.radius;
  100342. var hw = b.halfWidth;
  100343. var hh = b.halfHeight;
  100344. var hd = b.halfDepth;
  100345. var dx = psx - pbx;
  100346. var dy = psy - pby;
  100347. var dz = psz - pbz;
  100348. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100349. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100350. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100351. var cx;
  100352. var cy;
  100353. var cz;
  100354. var len;
  100355. var invLen;
  100356. var overlap = 0;
  100357. if (sx > hw) {
  100358. sx = hw;
  100359. } else if (sx < -hw) {
  100360. sx = -hw;
  100361. } else {
  100362. overlap = 1;
  100363. }
  100364. if (sy > hh) {
  100365. sy = hh;
  100366. } else if (sy < -hh) {
  100367. sy = -hh;
  100368. } else {
  100369. overlap |= 2;
  100370. }
  100371. if (sz > hd) {
  100372. sz = hd;
  100373. } else if (sz < -hd) {
  100374. sz = -hd;
  100375. } else {
  100376. overlap |= 4;
  100377. }
  100378. if (overlap == 7) {
  100379. // center of sphere is in the box
  100380. if (sx < 0) {
  100381. dx = hw + sx;
  100382. } else {
  100383. dx = hw - sx;
  100384. }
  100385. if (sy < 0) {
  100386. dy = hh + sy;
  100387. } else {
  100388. dy = hh - sy;
  100389. }
  100390. if (sz < 0) {
  100391. dz = hd + sz;
  100392. } else {
  100393. dz = hd - sz;
  100394. }
  100395. if (dx < dy) {
  100396. if (dx < dz) {
  100397. len = dx - hw;
  100398. if (sx < 0) {
  100399. sx = -hw;
  100400. dx = D[0];
  100401. dy = D[1];
  100402. dz = D[2];
  100403. } else {
  100404. sx = hw;
  100405. dx = -D[0];
  100406. dy = -D[1];
  100407. dz = -D[2];
  100408. }
  100409. } else {
  100410. len = dz - hd;
  100411. if (sz < 0) {
  100412. sz = -hd;
  100413. dx = D[6];
  100414. dy = D[7];
  100415. dz = D[8];
  100416. } else {
  100417. sz = hd;
  100418. dx = -D[6];
  100419. dy = -D[7];
  100420. dz = -D[8];
  100421. }
  100422. }
  100423. } else {
  100424. if (dy < dz) {
  100425. len = dy - hh;
  100426. if (sy < 0) {
  100427. sy = -hh;
  100428. dx = D[3];
  100429. dy = D[4];
  100430. dz = D[5];
  100431. } else {
  100432. sy = hh;
  100433. dx = -D[3];
  100434. dy = -D[4];
  100435. dz = -D[5];
  100436. }
  100437. } else {
  100438. len = dz - hd;
  100439. if (sz < 0) {
  100440. sz = -hd;
  100441. dx = D[6];
  100442. dy = D[7];
  100443. dz = D[8];
  100444. } else {
  100445. sz = hd;
  100446. dx = -D[6];
  100447. dy = -D[7];
  100448. dz = -D[8];
  100449. }
  100450. }
  100451. }
  100452. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100453. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100454. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100455. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100456. } else {
  100457. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100458. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100459. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100460. dx = cx - ps.x;
  100461. dy = cy - ps.y;
  100462. dz = cz - ps.z;
  100463. len = dx * dx + dy * dy + dz * dz;
  100464. if (len > 0 && len < rad * rad) {
  100465. len = OIMO.sqrt(len);
  100466. invLen = 1 / len;
  100467. dx *= invLen;
  100468. dy *= invLen;
  100469. dz *= invLen;
  100470. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100471. }
  100472. }
  100473. };
  100474. /**
  100475. * A collision detector which detects collisions between two spheres.
  100476. * @author saharan
  100477. */
  100478. OIMO.SphereSphereCollisionDetector = function () {
  100479. OIMO.CollisionDetector.call(this);
  100480. };
  100481. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100482. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100483. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100484. var s1 = shape1;
  100485. var s2 = shape2;
  100486. var p1 = s1.position;
  100487. var p2 = s2.position;
  100488. var dx = p2.x - p1.x;
  100489. var dy = p2.y - p1.y;
  100490. var dz = p2.z - p1.z;
  100491. var len = dx * dx + dy * dy + dz * dz;
  100492. var r1 = s1.radius;
  100493. var r2 = s2.radius;
  100494. var rad = r1 + r2;
  100495. if (len > 0 && len < rad * rad) {
  100496. len = OIMO.sqrt(len);
  100497. var invLen = 1 / len;
  100498. dx *= invLen;
  100499. dy *= invLen;
  100500. dz *= invLen;
  100501. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100502. }
  100503. };
  100504. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100505. OIMO.CollisionDetector.call(this);
  100506. this.flip = flip;
  100507. };
  100508. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100509. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100510. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100511. var t1x;
  100512. var t1y;
  100513. var t1z;
  100514. var t2x;
  100515. var t2y;
  100516. var t2z;
  100517. var sup = new OIMO.Vec3();
  100518. var len;
  100519. var p1x;
  100520. var p1y;
  100521. var p1z;
  100522. var p2x;
  100523. var p2y;
  100524. var p2z;
  100525. var v01x = c1.position.x;
  100526. var v01y = c1.position.y;
  100527. var v01z = c1.position.z;
  100528. var v02x = c2.position.x;
  100529. var v02y = c2.position.y;
  100530. var v02z = c2.position.z;
  100531. var v0x = v02x - v01x;
  100532. var v0y = v02y - v01y;
  100533. var v0z = v02z - v01z;
  100534. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100535. var nx = -v0x;
  100536. var ny = -v0y;
  100537. var nz = -v0z;
  100538. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100539. var v11x = sup.x;
  100540. var v11y = sup.y;
  100541. var v11z = sup.z;
  100542. this.supportPointC(c2, nx, ny, nz, sup);
  100543. var v12x = sup.x;
  100544. var v12y = sup.y;
  100545. var v12z = sup.z;
  100546. var v1x = v12x - v11x;
  100547. var v1y = v12y - v11y;
  100548. var v1z = v12z - v11z;
  100549. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100550. return false;
  100551. }
  100552. nx = v1y * v0z - v1z * v0y;
  100553. ny = v1z * v0x - v1x * v0z;
  100554. nz = v1x * v0y - v1y * v0x;
  100555. if (nx * nx + ny * ny + nz * nz == 0) {
  100556. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100557. sep.normalize(sep);
  100558. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100559. return true;
  100560. }
  100561. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100562. var v21x = sup.x;
  100563. var v21y = sup.y;
  100564. var v21z = sup.z;
  100565. this.supportPointC(c2, nx, ny, nz, sup);
  100566. var v22x = sup.x;
  100567. var v22y = sup.y;
  100568. var v22z = sup.z;
  100569. var v2x = v22x - v21x;
  100570. var v2y = v22y - v21y;
  100571. var v2z = v22z - v21z;
  100572. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100573. return false;
  100574. }
  100575. t1x = v1x - v0x;
  100576. t1y = v1y - v0y;
  100577. t1z = v1z - v0z;
  100578. t2x = v2x - v0x;
  100579. t2y = v2y - v0y;
  100580. t2z = v2z - v0z;
  100581. nx = t1y * t2z - t1z * t2y;
  100582. ny = t1z * t2x - t1x * t2z;
  100583. nz = t1x * t2y - t1y * t2x;
  100584. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100585. t1x = v1x;
  100586. t1y = v1y;
  100587. t1z = v1z;
  100588. v1x = v2x;
  100589. v1y = v2y;
  100590. v1z = v2z;
  100591. v2x = t1x;
  100592. v2y = t1y;
  100593. v2z = t1z;
  100594. t1x = v11x;
  100595. t1y = v11y;
  100596. t1z = v11z;
  100597. v11x = v21x;
  100598. v11y = v21y;
  100599. v11z = v21z;
  100600. v21x = t1x;
  100601. v21y = t1y;
  100602. v21z = t1z;
  100603. t1x = v12x;
  100604. t1y = v12y;
  100605. t1z = v12z;
  100606. v12x = v22x;
  100607. v12y = v22y;
  100608. v12z = v22z;
  100609. v22x = t1x;
  100610. v22y = t1y;
  100611. v22z = t1z;
  100612. nx = -nx;
  100613. ny = -ny;
  100614. nz = -nz;
  100615. }
  100616. var iterations = 0;
  100617. while (true) {
  100618. if (++iterations > 100) {
  100619. return false;
  100620. }
  100621. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100622. var v31x = sup.x;
  100623. var v31y = sup.y;
  100624. var v31z = sup.z;
  100625. this.supportPointC(c2, nx, ny, nz, sup);
  100626. var v32x = sup.x;
  100627. var v32y = sup.y;
  100628. var v32z = sup.z;
  100629. var v3x = v32x - v31x;
  100630. var v3y = v32y - v31y;
  100631. var v3z = v32z - v31z;
  100632. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100633. return false;
  100634. }
  100635. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100636. v2x = v3x;
  100637. v2y = v3y;
  100638. v2z = v3z;
  100639. v21x = v31x;
  100640. v21y = v31y;
  100641. v21z = v31z;
  100642. v22x = v32x;
  100643. v22y = v32y;
  100644. v22z = v32z;
  100645. t1x = v1x - v0x;
  100646. t1y = v1y - v0y;
  100647. t1z = v1z - v0z;
  100648. t2x = v3x - v0x;
  100649. t2y = v3y - v0y;
  100650. t2z = v3z - v0z;
  100651. nx = t1y * t2z - t1z * t2y;
  100652. ny = t1z * t2x - t1x * t2z;
  100653. nz = t1x * t2y - t1y * t2x;
  100654. continue;
  100655. }
  100656. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100657. v1x = v3x;
  100658. v1y = v3y;
  100659. v1z = v3z;
  100660. v11x = v31x;
  100661. v11y = v31y;
  100662. v11z = v31z;
  100663. v12x = v32x;
  100664. v12y = v32y;
  100665. v12z = v32z;
  100666. t1x = v3x - v0x;
  100667. t1y = v3y - v0y;
  100668. t1z = v3z - v0z;
  100669. t2x = v2x - v0x;
  100670. t2y = v2y - v0y;
  100671. t2z = v2z - v0z;
  100672. nx = t1y * t2z - t1z * t2y;
  100673. ny = t1z * t2x - t1x * t2z;
  100674. nz = t1x * t2y - t1y * t2x;
  100675. continue;
  100676. }
  100677. var hit = false;
  100678. while (true) {
  100679. t1x = v2x - v1x;
  100680. t1y = v2y - v1y;
  100681. t1z = v2z - v1z;
  100682. t2x = v3x - v1x;
  100683. t2y = v3y - v1y;
  100684. t2z = v3z - v1z;
  100685. nx = t1y * t2z - t1z * t2y;
  100686. ny = t1z * t2x - t1x * t2z;
  100687. nz = t1x * t2y - t1y * t2x;
  100688. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100689. nx *= len;
  100690. ny *= len;
  100691. nz *= len;
  100692. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100693. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100694. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100695. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100696. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100697. var sum = b0 + b1 + b2 + b3;
  100698. if (sum <= 0) {
  100699. b0 = 0;
  100700. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100701. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100702. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100703. sum = b1 + b2 + b3;
  100704. }
  100705. var inv = 1 / sum;
  100706. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100707. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100708. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100709. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100710. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100711. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100712. hit = true;
  100713. }
  100714. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100715. var v41x = sup.x;
  100716. var v41y = sup.y;
  100717. var v41z = sup.z;
  100718. this.supportPointC(c2, nx, ny, nz, sup);
  100719. var v42x = sup.x;
  100720. var v42y = sup.y;
  100721. var v42z = sup.z;
  100722. var v4x = v42x - v41x;
  100723. var v4y = v42y - v41y;
  100724. var v4z = v42z - v41z;
  100725. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100726. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100727. if (hit) {
  100728. sep.init(-nx, -ny, -nz);
  100729. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100730. dep.x = separation;
  100731. return true;
  100732. }
  100733. return false;
  100734. }
  100735. if (
  100736. (v4y * v1z - v4z * v1y) * v0x +
  100737. (v4z * v1x - v4x * v1z) * v0y +
  100738. (v4x * v1y - v4y * v1x) * v0z < 0
  100739. ) {
  100740. if (
  100741. (v4y * v2z - v4z * v2y) * v0x +
  100742. (v4z * v2x - v4x * v2z) * v0y +
  100743. (v4x * v2y - v4y * v2x) * v0z < 0
  100744. ) {
  100745. v1x = v4x;
  100746. v1y = v4y;
  100747. v1z = v4z;
  100748. v11x = v41x;
  100749. v11y = v41y;
  100750. v11z = v41z;
  100751. v12x = v42x;
  100752. v12y = v42y;
  100753. v12z = v42z;
  100754. } else {
  100755. v3x = v4x;
  100756. v3y = v4y;
  100757. v3z = v4z;
  100758. v31x = v41x;
  100759. v31y = v41y;
  100760. v31z = v41z;
  100761. v32x = v42x;
  100762. v32y = v42y;
  100763. v32z = v42z;
  100764. }
  100765. } else {
  100766. if (
  100767. (v4y * v3z - v4z * v3y) * v0x +
  100768. (v4z * v3x - v4x * v3z) * v0y +
  100769. (v4x * v3y - v4y * v3x) * v0z < 0
  100770. ) {
  100771. v2x = v4x;
  100772. v2y = v4y;
  100773. v2z = v4z;
  100774. v21x = v41x;
  100775. v21y = v41y;
  100776. v21z = v41z;
  100777. v22x = v42x;
  100778. v22y = v42y;
  100779. v22z = v42z;
  100780. } else {
  100781. v1x = v4x;
  100782. v1y = v4y;
  100783. v1z = v4z;
  100784. v11x = v41x;
  100785. v11y = v41y;
  100786. v11z = v41z;
  100787. v12x = v42x;
  100788. v12y = v42y;
  100789. v12z = v42z;
  100790. }
  100791. }
  100792. }
  100793. }
  100794. //return false;
  100795. };
  100796. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100797. var rot = c.rotation.elements;
  100798. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100799. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100800. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100801. var w = c.halfWidth;
  100802. var h = c.halfHeight;
  100803. var d = c.halfDepth;
  100804. var ox;
  100805. var oy;
  100806. var oz;
  100807. if (ldx < 0) ox = -w;
  100808. else ox = w;
  100809. if (ldy < 0) oy = -h;
  100810. else oy = h;
  100811. if (ldz < 0) oz = -d;
  100812. else oz = d;
  100813. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100814. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100815. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100816. out.init(ldx, ldy, ldz);
  100817. };
  100818. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100819. var rot = c.rotation.elements;
  100820. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100821. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100822. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100823. var radx = ldx;
  100824. var radz = ldz;
  100825. var len = radx * radx + radz * radz;
  100826. var rad = c.radius;
  100827. var hh = c.halfHeight;
  100828. var ox;
  100829. var oy;
  100830. var oz;
  100831. if (len == 0) {
  100832. if (ldy < 0) {
  100833. ox = rad;
  100834. oy = -hh;
  100835. oz = 0;
  100836. } else {
  100837. ox = rad;
  100838. oy = hh;
  100839. oz = 0;
  100840. }
  100841. } else {
  100842. len = c.radius / OIMO.sqrt(len);
  100843. if (ldy < 0) {
  100844. ox = radx * len;
  100845. oy = -hh;
  100846. oz = radz * len;
  100847. } else {
  100848. ox = radx * len;
  100849. oy = hh;
  100850. oz = radz * len;
  100851. }
  100852. }
  100853. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100854. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100855. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100856. out.init(ldx, ldy, ldz);
  100857. };
  100858. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100859. var b;
  100860. var c;
  100861. if (this.flip) {
  100862. b = shape2;
  100863. c = shape1;
  100864. } else {
  100865. b = shape1;
  100866. c = shape2;
  100867. }
  100868. var sep = new OIMO.Vec3();
  100869. var pos = new OIMO.Vec3();
  100870. var dep = new OIMO.Vec3();
  100871. var co;
  100872. if (!this.getSep(b, c, sep, pos, dep)) return;
  100873. var pbx = b.position.x;
  100874. var pby = b.position.y;
  100875. var pbz = b.position.z;
  100876. var pcx = c.position.x;
  100877. var pcy = c.position.y;
  100878. var pcz = c.position.z;
  100879. var bw = b.halfWidth;
  100880. var bh = b.halfHeight;
  100881. var bd = b.halfDepth;
  100882. var ch = c.halfHeight;
  100883. var r = c.radius;
  100884. var D = b.dimentions;
  100885. var nwx = D[0];//b.normalDirectionWidth.x;
  100886. var nwy = D[1];//b.normalDirectionWidth.y;
  100887. var nwz = D[2];//b.normalDirectionWidth.z;
  100888. var nhx = D[3];//b.normalDirectionHeight.x;
  100889. var nhy = D[4];//b.normalDirectionHeight.y;
  100890. var nhz = D[5];//b.normalDirectionHeight.z;
  100891. var ndx = D[6];//b.normalDirectionDepth.x;
  100892. var ndy = D[7];//b.normalDirectionDepth.y;
  100893. var ndz = D[8];//b.normalDirectionDepth.z;
  100894. var dwx = D[9];//b.halfDirectionWidth.x;
  100895. var dwy = D[10];//b.halfDirectionWidth.y;
  100896. var dwz = D[11];//b.halfDirectionWidth.z;
  100897. var dhx = D[12];//b.halfDirectionHeight.x;
  100898. var dhy = D[13];//b.halfDirectionHeight.y;
  100899. var dhz = D[14];//b.halfDirectionHeight.z;
  100900. var ddx = D[15];//b.halfDirectionDepth.x;
  100901. var ddy = D[16];//b.halfDirectionDepth.y;
  100902. var ddz = D[17];//b.halfDirectionDepth.z;
  100903. var ncx = c.normalDirection.x;
  100904. var ncy = c.normalDirection.y;
  100905. var ncz = c.normalDirection.z;
  100906. var dcx = c.halfDirection.x;
  100907. var dcy = c.halfDirection.y;
  100908. var dcz = c.halfDirection.z;
  100909. var nx = sep.x;
  100910. var ny = sep.y;
  100911. var nz = sep.z;
  100912. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100913. var doth = nx * nhx + ny * nhy + nz * nhz;
  100914. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100915. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100916. var right1 = dotw > 0;
  100917. var right2 = doth > 0;
  100918. var right3 = dotd > 0;
  100919. var right4 = dotc > 0;
  100920. if (!right1) dotw = -dotw;
  100921. if (!right2) doth = -doth;
  100922. if (!right3) dotd = -dotd;
  100923. if (!right4) dotc = -dotc;
  100924. var state = 0;
  100925. if (dotc > 0.999) {
  100926. if (dotw > 0.999) {
  100927. if (dotw > dotc) state = 1;
  100928. else state = 4;
  100929. } else if (doth > 0.999) {
  100930. if (doth > dotc) state = 2;
  100931. else state = 4;
  100932. } else if (dotd > 0.999) {
  100933. if (dotd > dotc) state = 3;
  100934. else state = 4;
  100935. } else state = 4;
  100936. } else {
  100937. if (dotw > 0.999) state = 1;
  100938. else if (doth > 0.999) state = 2;
  100939. else if (dotd > 0.999) state = 3;
  100940. }
  100941. var cbx;
  100942. var cby;
  100943. var cbz;
  100944. var ccx;
  100945. var ccy;
  100946. var ccz;
  100947. var r00;
  100948. var r01;
  100949. var r02;
  100950. var r10;
  100951. var r11;
  100952. var r12;
  100953. var r20;
  100954. var r21;
  100955. var r22;
  100956. var px;
  100957. var py;
  100958. var pz;
  100959. var pd;
  100960. var dot;
  100961. var len;
  100962. var tx;
  100963. var ty;
  100964. var tz;
  100965. var td;
  100966. var dx;
  100967. var dy;
  100968. var dz;
  100969. var d1x;
  100970. var d1y;
  100971. var d1z;
  100972. var d2x;
  100973. var d2y;
  100974. var d2z;
  100975. var sx;
  100976. var sy;
  100977. var sz;
  100978. var sd;
  100979. var ex;
  100980. var ey;
  100981. var ez;
  100982. var ed;
  100983. var dot1;
  100984. var dot2;
  100985. var t1;
  100986. var t2;
  100987. var dir1x;
  100988. var dir1y;
  100989. var dir1z;
  100990. var dir2x;
  100991. var dir2y;
  100992. var dir2z;
  100993. var dir1l;
  100994. var dir2l;
  100995. if (state == 0) {
  100996. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  100997. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  100998. } else if (state == 4) {
  100999. if (right4) {
  101000. ccx = pcx - dcx;
  101001. ccy = pcy - dcy;
  101002. ccz = pcz - dcz;
  101003. nx = -ncx;
  101004. ny = -ncy;
  101005. nz = -ncz;
  101006. } else {
  101007. ccx = pcx + dcx;
  101008. ccy = pcy + dcy;
  101009. ccz = pcz + dcz;
  101010. nx = ncx;
  101011. ny = ncy;
  101012. nz = ncz;
  101013. }
  101014. var v1x;
  101015. var v1y;
  101016. var v1z;
  101017. var v2x;
  101018. var v2y;
  101019. var v2z;
  101020. var v3x;
  101021. var v3y;
  101022. var v3z;
  101023. var v4x;
  101024. var v4y;
  101025. var v4z;
  101026. dot = 1;
  101027. state = 0;
  101028. dot1 = nwx * nx + nwy * ny + nwz * nz;
  101029. if (dot1 < dot) {
  101030. dot = dot1;
  101031. state = 0;
  101032. }
  101033. if (-dot1 < dot) {
  101034. dot = -dot1;
  101035. state = 1;
  101036. }
  101037. dot1 = nhx * nx + nhy * ny + nhz * nz;
  101038. if (dot1 < dot) {
  101039. dot = dot1;
  101040. state = 2;
  101041. }
  101042. if (-dot1 < dot) {
  101043. dot = -dot1;
  101044. state = 3;
  101045. }
  101046. dot1 = ndx * nx + ndy * ny + ndz * nz;
  101047. if (dot1 < dot) {
  101048. dot = dot1;
  101049. state = 4;
  101050. }
  101051. if (-dot1 < dot) {
  101052. dot = -dot1;
  101053. state = 5;
  101054. }
  101055. var v = b.elements;
  101056. switch (state) {
  101057. case 0:
  101058. //v=b.vertex1;
  101059. v1x = v[0];//v.x;
  101060. v1y = v[1];//v.y;
  101061. v1z = v[2];//v.z;
  101062. //v=b.vertex3;
  101063. v2x = v[6];//v.x;
  101064. v2y = v[7];//v.y;
  101065. v2z = v[8];//v.z;
  101066. //v=b.vertex4;
  101067. v3x = v[9];//v.x;
  101068. v3y = v[10];//v.y;
  101069. v3z = v[11];//v.z;
  101070. //v=b.vertex2;
  101071. v4x = v[3];//v.x;
  101072. v4y = v[4];//v.y;
  101073. v4z = v[5];//v.z;
  101074. break;
  101075. case 1:
  101076. //v=b.vertex6;
  101077. v1x = v[15];//v.x;
  101078. v1y = v[16];//v.y;
  101079. v1z = v[17];//v.z;
  101080. //v=b.vertex8;
  101081. v2x = v[21];//v.x;
  101082. v2y = v[22];//v.y;
  101083. v2z = v[23];//v.z;
  101084. //v=b.vertex7;
  101085. v3x = v[18];//v.x;
  101086. v3y = v[19];//v.y;
  101087. v3z = v[20];//v.z;
  101088. //v=b.vertex5;
  101089. v4x = v[12];//v.x;
  101090. v4y = v[13];//v.y;
  101091. v4z = v[14];//v.z;
  101092. break;
  101093. case 2:
  101094. //v=b.vertex5;
  101095. v1x = v[12];//v.x;
  101096. v1y = v[13];//v.y;
  101097. v1z = v[14];//v.z;
  101098. //v=b.vertex1;
  101099. v2x = v[0];//v.x;
  101100. v2y = v[1];//v.y;
  101101. v2z = v[2];//v.z;
  101102. //v=b.vertex2;
  101103. v3x = v[3];//v.x;
  101104. v3y = v[4];//v.y;
  101105. v3z = v[5];//v.z;
  101106. //v=b.vertex6;
  101107. v4x = v[15];//v.x;
  101108. v4y = v[16];//v.y;
  101109. v4z = v[17];//v.z;
  101110. break;
  101111. case 3:
  101112. //v=b.vertex8;
  101113. v1x = v[21];//v.x;
  101114. v1y = v[22];//v.y;
  101115. v1z = v[23];//v.z;
  101116. //v=b.vertex4;
  101117. v2x = v[9];//v.x;
  101118. v2y = v[10];//v.y;
  101119. v2z = v[11];//v.z;
  101120. //v=b.vertex3;
  101121. v3x = v[6];//v.x;
  101122. v3y = v[7];//v.y;
  101123. v3z = v[8];//v.z;
  101124. //v=b.vertex7;
  101125. v4x = v[18];//v.x;
  101126. v4y = v[19];//v.y;
  101127. v4z = v[20];//v.z;
  101128. break;
  101129. case 4:
  101130. //v=b.vertex5;
  101131. v1x = v[12];//v.x;
  101132. v1y = v[13];//v.y;
  101133. v1z = v[14];//v.z;
  101134. //v=b.vertex7;
  101135. v2x = v[18];//v.x;
  101136. v2y = v[19];//v.y;
  101137. v2z = v[20];//v.z;
  101138. //v=b.vertex3;
  101139. v3x = v[6];//v.x;
  101140. v3y = v[7];//v.y;
  101141. v3z = v[8];//v.z;
  101142. //v=b.vertex1;
  101143. v4x = v[0];//v.x;
  101144. v4y = v[1];//v.y;
  101145. v4z = v[2];//v.z;
  101146. break;
  101147. case 5:
  101148. //v=b.vertex2;
  101149. v1x = v[3];//v.x;
  101150. v1y = v[4];//v.y;
  101151. v1z = v[5];//v.z;
  101152. //v=b.vertex4;
  101153. v2x = v[9];//v.x;
  101154. v2y = v[10];//v.y;
  101155. v2z = v[11];//v.z;
  101156. //v=b.vertex8;
  101157. v3x = v[21];//v.x;
  101158. v3y = v[22];//v.y;
  101159. v3z = v[23];//v.z;
  101160. //v=b.vertex6;
  101161. v4x = v[15];//v.x;
  101162. v4y = v[16];//v.y;
  101163. v4z = v[17];//v.z;
  101164. break;
  101165. }
  101166. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101167. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101168. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101169. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101170. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101171. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101172. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101173. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101174. } else {
  101175. switch (state) {
  101176. case 1:
  101177. if (right1) {
  101178. cbx = pbx + dwx;
  101179. cby = pby + dwy;
  101180. cbz = pbz + dwz;
  101181. nx = nwx;
  101182. ny = nwy;
  101183. nz = nwz;
  101184. } else {
  101185. cbx = pbx - dwx;
  101186. cby = pby - dwy;
  101187. cbz = pbz - dwz;
  101188. nx = -nwx;
  101189. ny = -nwy;
  101190. nz = -nwz;
  101191. }
  101192. dir1x = nhx;
  101193. dir1y = nhy;
  101194. dir1z = nhz;
  101195. dir1l = bh;
  101196. dir2x = ndx;
  101197. dir2y = ndy;
  101198. dir2z = ndz;
  101199. dir2l = bd;
  101200. break;
  101201. case 2:
  101202. if (right2) {
  101203. cbx = pbx + dhx;
  101204. cby = pby + dhy;
  101205. cbz = pbz + dhz;
  101206. nx = nhx;
  101207. ny = nhy;
  101208. nz = nhz;
  101209. } else {
  101210. cbx = pbx - dhx;
  101211. cby = pby - dhy;
  101212. cbz = pbz - dhz;
  101213. nx = -nhx;
  101214. ny = -nhy;
  101215. nz = -nhz;
  101216. }
  101217. dir1x = nwx;
  101218. dir1y = nwy;
  101219. dir1z = nwz;
  101220. dir1l = bw;
  101221. dir2x = ndx;
  101222. dir2y = ndy;
  101223. dir2z = ndz;
  101224. dir2l = bd;
  101225. break;
  101226. case 3:
  101227. if (right3) {
  101228. cbx = pbx + ddx;
  101229. cby = pby + ddy;
  101230. cbz = pbz + ddz;
  101231. nx = ndx;
  101232. ny = ndy;
  101233. nz = ndz;
  101234. } else {
  101235. cbx = pbx - ddx;
  101236. cby = pby - ddy;
  101237. cbz = pbz - ddz;
  101238. nx = -ndx;
  101239. ny = -ndy;
  101240. nz = -ndz;
  101241. }
  101242. dir1x = nwx;
  101243. dir1y = nwy;
  101244. dir1z = nwz;
  101245. dir1l = bw;
  101246. dir2x = nhx;
  101247. dir2y = nhy;
  101248. dir2z = nhz;
  101249. dir2l = bh;
  101250. break;
  101251. }
  101252. dot = nx * ncx + ny * ncy + nz * ncz;
  101253. if (dot < 0) len = ch;
  101254. else len = -ch;
  101255. ccx = pcx + len * ncx;
  101256. ccy = pcy + len * ncy;
  101257. ccz = pcz + len * ncz;
  101258. if (dotc >= 0.999999) {
  101259. tx = -ny;
  101260. ty = nz;
  101261. tz = nx;
  101262. } else {
  101263. tx = nx;
  101264. ty = ny;
  101265. tz = nz;
  101266. }
  101267. len = tx * ncx + ty * ncy + tz * ncz;
  101268. dx = len * ncx - tx;
  101269. dy = len * ncy - ty;
  101270. dz = len * ncz - tz;
  101271. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101272. if (len == 0) return;
  101273. len = r / len;
  101274. dx *= len;
  101275. dy *= len;
  101276. dz *= len;
  101277. tx = ccx + dx;
  101278. ty = ccy + dy;
  101279. tz = ccz + dz;
  101280. if (dot < -0.96 || dot > 0.96) {
  101281. r00 = ncx * ncx * 1.5 - 0.5;
  101282. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101283. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101284. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101285. r11 = ncy * ncy * 1.5 - 0.5;
  101286. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101287. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101288. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101289. r22 = ncz * ncz * 1.5 - 0.5;
  101290. px = tx;
  101291. py = ty;
  101292. pz = tz;
  101293. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101294. tx = px - pd * nx - cbx;
  101295. ty = py - pd * ny - cby;
  101296. tz = pz - pd * nz - cbz;
  101297. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101298. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101299. if (sd < -dir1l) sd = -dir1l;
  101300. else if (sd > dir1l) sd = dir1l;
  101301. if (ed < -dir2l) ed = -dir2l;
  101302. else if (ed > dir2l) ed = dir2l;
  101303. tx = sd * dir1x + ed * dir2x;
  101304. ty = sd * dir1y + ed * dir2y;
  101305. tz = sd * dir1z + ed * dir2z;
  101306. px = cbx + tx;
  101307. py = cby + ty;
  101308. pz = cbz + tz;
  101309. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101310. px = dx * r00 + dy * r01 + dz * r02;
  101311. py = dx * r10 + dy * r11 + dz * r12;
  101312. pz = dx * r20 + dy * r21 + dz * r22;
  101313. px = (dx = px) + ccx;
  101314. py = (dy = py) + ccy;
  101315. pz = (dz = pz) + ccz;
  101316. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101317. if (pd <= 0) {
  101318. tx = px - pd * nx - cbx;
  101319. ty = py - pd * ny - cby;
  101320. tz = pz - pd * nz - cbz;
  101321. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101322. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101323. if (sd < -dir1l) sd = -dir1l;
  101324. else if (sd > dir1l) sd = dir1l;
  101325. if (ed < -dir2l) ed = -dir2l;
  101326. else if (ed > dir2l) ed = dir2l;
  101327. tx = sd * dir1x + ed * dir2x;
  101328. ty = sd * dir1y + ed * dir2y;
  101329. tz = sd * dir1z + ed * dir2z;
  101330. px = cbx + tx;
  101331. py = cby + ty;
  101332. pz = cbz + tz;
  101333. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101334. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101335. }
  101336. px = dx * r00 + dy * r01 + dz * r02;
  101337. py = dx * r10 + dy * r11 + dz * r12;
  101338. pz = dx * r20 + dy * r21 + dz * r22;
  101339. px = (dx = px) + ccx;
  101340. py = (dy = py) + ccy;
  101341. pz = (dz = pz) + ccz;
  101342. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101343. if (pd <= 0) {
  101344. tx = px - pd * nx - cbx;
  101345. ty = py - pd * ny - cby;
  101346. tz = pz - pd * nz - cbz;
  101347. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101348. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101349. if (sd < -dir1l) sd = -dir1l;
  101350. else if (sd > dir1l) sd = dir1l;
  101351. if (ed < -dir2l) ed = -dir2l;
  101352. else if (ed > dir2l) ed = dir2l;
  101353. tx = sd * dir1x + ed * dir2x;
  101354. ty = sd * dir1y + ed * dir2y;
  101355. tz = sd * dir1z + ed * dir2z;
  101356. px = cbx + tx;
  101357. py = cby + ty;
  101358. pz = cbz + tz;
  101359. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101360. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101361. }
  101362. } else {
  101363. sx = tx;
  101364. sy = ty;
  101365. sz = tz;
  101366. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101367. sx -= sd * nx;
  101368. sy -= sd * ny;
  101369. sz -= sd * nz;
  101370. if (dot > 0) {
  101371. ex = tx + dcx * 2;
  101372. ey = ty + dcy * 2;
  101373. ez = tz + dcz * 2;
  101374. } else {
  101375. ex = tx - dcx * 2;
  101376. ey = ty - dcy * 2;
  101377. ez = tz - dcz * 2;
  101378. }
  101379. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101380. ex -= ed * nx;
  101381. ey -= ed * ny;
  101382. ez -= ed * nz;
  101383. d1x = sx - cbx;
  101384. d1y = sy - cby;
  101385. d1z = sz - cbz;
  101386. d2x = ex - cbx;
  101387. d2y = ey - cby;
  101388. d2z = ez - cbz;
  101389. tx = ex - sx;
  101390. ty = ey - sy;
  101391. tz = ez - sz;
  101392. td = ed - sd;
  101393. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101394. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101395. dot1 = dotw - dir1l;
  101396. dot2 = doth - dir1l;
  101397. if (dot1 > 0) {
  101398. if (dot2 > 0) return;
  101399. t1 = dot1 / (dot1 - dot2);
  101400. sx = sx + tx * t1;
  101401. sy = sy + ty * t1;
  101402. sz = sz + tz * t1;
  101403. sd = sd + td * t1;
  101404. d1x = sx - cbx;
  101405. d1y = sy - cby;
  101406. d1z = sz - cbz;
  101407. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101408. tx = ex - sx;
  101409. ty = ey - sy;
  101410. tz = ez - sz;
  101411. td = ed - sd;
  101412. } else if (dot2 > 0) {
  101413. t1 = dot1 / (dot1 - dot2);
  101414. ex = sx + tx * t1;
  101415. ey = sy + ty * t1;
  101416. ez = sz + tz * t1;
  101417. ed = sd + td * t1;
  101418. d2x = ex - cbx;
  101419. d2y = ey - cby;
  101420. d2z = ez - cbz;
  101421. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101422. tx = ex - sx;
  101423. ty = ey - sy;
  101424. tz = ez - sz;
  101425. td = ed - sd;
  101426. }
  101427. dot1 = dotw + dir1l;
  101428. dot2 = doth + dir1l;
  101429. if (dot1 < 0) {
  101430. if (dot2 < 0) return;
  101431. t1 = dot1 / (dot1 - dot2);
  101432. sx = sx + tx * t1;
  101433. sy = sy + ty * t1;
  101434. sz = sz + tz * t1;
  101435. sd = sd + td * t1;
  101436. d1x = sx - cbx;
  101437. d1y = sy - cby;
  101438. d1z = sz - cbz;
  101439. tx = ex - sx;
  101440. ty = ey - sy;
  101441. tz = ez - sz;
  101442. td = ed - sd;
  101443. } else if (dot2 < 0) {
  101444. t1 = dot1 / (dot1 - dot2);
  101445. ex = sx + tx * t1;
  101446. ey = sy + ty * t1;
  101447. ez = sz + tz * t1;
  101448. ed = sd + td * t1;
  101449. d2x = ex - cbx;
  101450. d2y = ey - cby;
  101451. d2z = ez - cbz;
  101452. tx = ex - sx;
  101453. ty = ey - sy;
  101454. tz = ez - sz;
  101455. td = ed - sd;
  101456. }
  101457. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101458. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101459. dot1 = dotw - dir2l;
  101460. dot2 = doth - dir2l;
  101461. if (dot1 > 0) {
  101462. if (dot2 > 0) return;
  101463. t1 = dot1 / (dot1 - dot2);
  101464. sx = sx + tx * t1;
  101465. sy = sy + ty * t1;
  101466. sz = sz + tz * t1;
  101467. sd = sd + td * t1;
  101468. d1x = sx - cbx;
  101469. d1y = sy - cby;
  101470. d1z = sz - cbz;
  101471. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101472. tx = ex - sx;
  101473. ty = ey - sy;
  101474. tz = ez - sz;
  101475. td = ed - sd;
  101476. } else if (dot2 > 0) {
  101477. t1 = dot1 / (dot1 - dot2);
  101478. ex = sx + tx * t1;
  101479. ey = sy + ty * t1;
  101480. ez = sz + tz * t1;
  101481. ed = sd + td * t1;
  101482. d2x = ex - cbx;
  101483. d2y = ey - cby;
  101484. d2z = ez - cbz;
  101485. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101486. tx = ex - sx;
  101487. ty = ey - sy;
  101488. tz = ez - sz;
  101489. td = ed - sd;
  101490. }
  101491. dot1 = dotw + dir2l;
  101492. dot2 = doth + dir2l;
  101493. if (dot1 < 0) {
  101494. if (dot2 < 0) return;
  101495. t1 = dot1 / (dot1 - dot2);
  101496. sx = sx + tx * t1;
  101497. sy = sy + ty * t1;
  101498. sz = sz + tz * t1;
  101499. sd = sd + td * t1;
  101500. } else if (dot2 < 0) {
  101501. t1 = dot1 / (dot1 - dot2);
  101502. ex = sx + tx * t1;
  101503. ey = sy + ty * t1;
  101504. ez = sz + tz * t1;
  101505. ed = sd + td * t1;
  101506. }
  101507. if (sd < 0) {
  101508. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101509. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101510. }
  101511. if (ed < 0) {
  101512. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101513. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101514. }
  101515. }
  101516. }
  101517. };
  101518. OIMO.CylinderCylinderCollisionDetector = function () {
  101519. OIMO.CollisionDetector.call(this);
  101520. };
  101521. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101522. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101523. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101524. var t1x;
  101525. var t1y;
  101526. var t1z;
  101527. var t2x;
  101528. var t2y;
  101529. var t2z;
  101530. var sup = new OIMO.Vec3();
  101531. var len;
  101532. var p1x;
  101533. var p1y;
  101534. var p1z;
  101535. var p2x;
  101536. var p2y;
  101537. var p2z;
  101538. var v01x = c1.position.x;
  101539. var v01y = c1.position.y;
  101540. var v01z = c1.position.z;
  101541. var v02x = c2.position.x;
  101542. var v02y = c2.position.y;
  101543. var v02z = c2.position.z;
  101544. var v0x = v02x - v01x;
  101545. var v0y = v02y - v01y;
  101546. var v0z = v02z - v01z;
  101547. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101548. var nx = -v0x;
  101549. var ny = -v0y;
  101550. var nz = -v0z;
  101551. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101552. var v11x = sup.x;
  101553. var v11y = sup.y;
  101554. var v11z = sup.z;
  101555. this.supportPoint(c2, nx, ny, nz, sup);
  101556. var v12x = sup.x;
  101557. var v12y = sup.y;
  101558. var v12z = sup.z;
  101559. var v1x = v12x - v11x;
  101560. var v1y = v12y - v11y;
  101561. var v1z = v12z - v11z;
  101562. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101563. return false;
  101564. }
  101565. nx = v1y * v0z - v1z * v0y;
  101566. ny = v1z * v0x - v1x * v0z;
  101567. nz = v1x * v0y - v1y * v0x;
  101568. if (nx * nx + ny * ny + nz * nz == 0) {
  101569. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101570. sep.normalize(sep);
  101571. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101572. return true;
  101573. }
  101574. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101575. var v21x = sup.x;
  101576. var v21y = sup.y;
  101577. var v21z = sup.z;
  101578. this.supportPoint(c2, nx, ny, nz, sup);
  101579. var v22x = sup.x;
  101580. var v22y = sup.y;
  101581. var v22z = sup.z;
  101582. var v2x = v22x - v21x;
  101583. var v2y = v22y - v21y;
  101584. var v2z = v22z - v21z;
  101585. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101586. return false;
  101587. }
  101588. t1x = v1x - v0x;
  101589. t1y = v1y - v0y;
  101590. t1z = v1z - v0z;
  101591. t2x = v2x - v0x;
  101592. t2y = v2y - v0y;
  101593. t2z = v2z - v0z;
  101594. nx = t1y * t2z - t1z * t2y;
  101595. ny = t1z * t2x - t1x * t2z;
  101596. nz = t1x * t2y - t1y * t2x;
  101597. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101598. t1x = v1x;
  101599. t1y = v1y;
  101600. t1z = v1z;
  101601. v1x = v2x;
  101602. v1y = v2y;
  101603. v1z = v2z;
  101604. v2x = t1x;
  101605. v2y = t1y;
  101606. v2z = t1z;
  101607. t1x = v11x;
  101608. t1y = v11y;
  101609. t1z = v11z;
  101610. v11x = v21x;
  101611. v11y = v21y;
  101612. v11z = v21z;
  101613. v21x = t1x;
  101614. v21y = t1y;
  101615. v21z = t1z;
  101616. t1x = v12x;
  101617. t1y = v12y;
  101618. t1z = v12z;
  101619. v12x = v22x;
  101620. v12y = v22y;
  101621. v12z = v22z;
  101622. v22x = t1x;
  101623. v22y = t1y;
  101624. v22z = t1z;
  101625. nx = -nx;
  101626. ny = -ny;
  101627. nz = -nz;
  101628. }
  101629. var iterations = 0;
  101630. while (true) {
  101631. if (++iterations > 100) {
  101632. return false;
  101633. }
  101634. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101635. var v31x = sup.x;
  101636. var v31y = sup.y;
  101637. var v31z = sup.z;
  101638. this.supportPoint(c2, nx, ny, nz, sup);
  101639. var v32x = sup.x;
  101640. var v32y = sup.y;
  101641. var v32z = sup.z;
  101642. var v3x = v32x - v31x;
  101643. var v3y = v32y - v31y;
  101644. var v3z = v32z - v31z;
  101645. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101646. return false;
  101647. }
  101648. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101649. v2x = v3x;
  101650. v2y = v3y;
  101651. v2z = v3z;
  101652. v21x = v31x;
  101653. v21y = v31y;
  101654. v21z = v31z;
  101655. v22x = v32x;
  101656. v22y = v32y;
  101657. v22z = v32z;
  101658. t1x = v1x - v0x;
  101659. t1y = v1y - v0y;
  101660. t1z = v1z - v0z;
  101661. t2x = v3x - v0x;
  101662. t2y = v3y - v0y;
  101663. t2z = v3z - v0z;
  101664. nx = t1y * t2z - t1z * t2y;
  101665. ny = t1z * t2x - t1x * t2z;
  101666. nz = t1x * t2y - t1y * t2x;
  101667. continue;
  101668. }
  101669. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101670. v1x = v3x;
  101671. v1y = v3y;
  101672. v1z = v3z;
  101673. v11x = v31x;
  101674. v11y = v31y;
  101675. v11z = v31z;
  101676. v12x = v32x;
  101677. v12y = v32y;
  101678. v12z = v32z;
  101679. t1x = v3x - v0x;
  101680. t1y = v3y - v0y;
  101681. t1z = v3z - v0z;
  101682. t2x = v2x - v0x;
  101683. t2y = v2y - v0y;
  101684. t2z = v2z - v0z;
  101685. nx = t1y * t2z - t1z * t2y;
  101686. ny = t1z * t2x - t1x * t2z;
  101687. nz = t1x * t2y - t1y * t2x;
  101688. continue;
  101689. }
  101690. var hit = false;
  101691. while (true) {
  101692. t1x = v2x - v1x;
  101693. t1y = v2y - v1y;
  101694. t1z = v2z - v1z;
  101695. t2x = v3x - v1x;
  101696. t2y = v3y - v1y;
  101697. t2z = v3z - v1z;
  101698. nx = t1y * t2z - t1z * t2y;
  101699. ny = t1z * t2x - t1x * t2z;
  101700. nz = t1x * t2y - t1y * t2x;
  101701. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101702. nx *= len;
  101703. ny *= len;
  101704. nz *= len;
  101705. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101706. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101707. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101708. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101709. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101710. var sum = b0 + b1 + b2 + b3;
  101711. if (sum <= 0) {
  101712. b0 = 0;
  101713. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101714. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101715. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101716. sum = b1 + b2 + b3;
  101717. }
  101718. var inv = 1 / sum;
  101719. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101720. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101721. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101722. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101723. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101724. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101725. hit = true;
  101726. }
  101727. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101728. var v41x = sup.x;
  101729. var v41y = sup.y;
  101730. var v41z = sup.z;
  101731. this.supportPoint(c2, nx, ny, nz, sup);
  101732. var v42x = sup.x;
  101733. var v42y = sup.y;
  101734. var v42z = sup.z;
  101735. var v4x = v42x - v41x;
  101736. var v4y = v42y - v41y;
  101737. var v4z = v42z - v41z;
  101738. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101739. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101740. if (hit) {
  101741. sep.init(-nx, -ny, -nz);
  101742. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101743. dep.x = separation;
  101744. return true;
  101745. }
  101746. return false;
  101747. }
  101748. if (
  101749. (v4y * v1z - v4z * v1y) * v0x +
  101750. (v4z * v1x - v4x * v1z) * v0y +
  101751. (v4x * v1y - v4y * v1x) * v0z < 0
  101752. ) {
  101753. if (
  101754. (v4y * v2z - v4z * v2y) * v0x +
  101755. (v4z * v2x - v4x * v2z) * v0y +
  101756. (v4x * v2y - v4y * v2x) * v0z < 0
  101757. ) {
  101758. v1x = v4x;
  101759. v1y = v4y;
  101760. v1z = v4z;
  101761. v11x = v41x;
  101762. v11y = v41y;
  101763. v11z = v41z;
  101764. v12x = v42x;
  101765. v12y = v42y;
  101766. v12z = v42z;
  101767. } else {
  101768. v3x = v4x;
  101769. v3y = v4y;
  101770. v3z = v4z;
  101771. v31x = v41x;
  101772. v31y = v41y;
  101773. v31z = v41z;
  101774. v32x = v42x;
  101775. v32y = v42y;
  101776. v32z = v42z;
  101777. }
  101778. } else {
  101779. if (
  101780. (v4y * v3z - v4z * v3y) * v0x +
  101781. (v4z * v3x - v4x * v3z) * v0y +
  101782. (v4x * v3y - v4y * v3x) * v0z < 0
  101783. ) {
  101784. v2x = v4x;
  101785. v2y = v4y;
  101786. v2z = v4z;
  101787. v21x = v41x;
  101788. v21y = v41y;
  101789. v21z = v41z;
  101790. v22x = v42x;
  101791. v22y = v42y;
  101792. v22z = v42z;
  101793. } else {
  101794. v1x = v4x;
  101795. v1y = v4y;
  101796. v1z = v4z;
  101797. v11x = v41x;
  101798. v11y = v41y;
  101799. v11z = v41z;
  101800. v12x = v42x;
  101801. v12y = v42y;
  101802. v12z = v42z;
  101803. }
  101804. }
  101805. }
  101806. }
  101807. //return false;
  101808. };
  101809. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101810. var rot = c.rotation.elements;
  101811. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101812. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101813. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101814. var radx = ldx;
  101815. var radz = ldz;
  101816. var len = radx * radx + radz * radz;
  101817. var rad = c.radius;
  101818. var hh = c.halfHeight;
  101819. var ox;
  101820. var oy;
  101821. var oz;
  101822. if (len == 0) {
  101823. if (ldy < 0) {
  101824. ox = rad;
  101825. oy = -hh;
  101826. oz = 0;
  101827. } else {
  101828. ox = rad;
  101829. oy = hh;
  101830. oz = 0;
  101831. }
  101832. } else {
  101833. len = c.radius / OIMO.sqrt(len);
  101834. if (ldy < 0) {
  101835. ox = radx * len;
  101836. oy = -hh;
  101837. oz = radz * len;
  101838. } else {
  101839. ox = radx * len;
  101840. oy = hh;
  101841. oz = radz * len;
  101842. }
  101843. }
  101844. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101845. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101846. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101847. out.init(ldx, ldy, ldz);
  101848. };
  101849. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101850. var c1;
  101851. var c2;
  101852. if (shape1.id < shape2.id) {
  101853. c1 = shape1;
  101854. c2 = shape2;
  101855. } else {
  101856. c1 = shape2;
  101857. c2 = shape1;
  101858. }
  101859. var p1 = c1.position;
  101860. var p2 = c2.position;
  101861. var p1x = p1.x;
  101862. var p1y = p1.y;
  101863. var p1z = p1.z;
  101864. var p2x = p2.x;
  101865. var p2y = p2.y;
  101866. var p2z = p2.z;
  101867. var h1 = c1.halfHeight;
  101868. var h2 = c2.halfHeight;
  101869. var n1 = c1.normalDirection;
  101870. var n2 = c2.normalDirection;
  101871. var d1 = c1.halfDirection;
  101872. var d2 = c2.halfDirection;
  101873. var r1 = c1.radius;
  101874. var r2 = c2.radius;
  101875. var n1x = n1.x;
  101876. var n1y = n1.y;
  101877. var n1z = n1.z;
  101878. var n2x = n2.x;
  101879. var n2y = n2.y;
  101880. var n2z = n2.z;
  101881. var d1x = d1.x;
  101882. var d1y = d1.y;
  101883. var d1z = d1.z;
  101884. var d2x = d2.x;
  101885. var d2y = d2.y;
  101886. var d2z = d2.z;
  101887. var dx = p1x - p2x;
  101888. var dy = p1y - p2y;
  101889. var dz = p1z - p2z;
  101890. var len;
  101891. var len1;
  101892. var len2;
  101893. var c;
  101894. var c1x;
  101895. var c1y;
  101896. var c1z;
  101897. var c2x;
  101898. var c2y;
  101899. var c2z;
  101900. var tx;
  101901. var ty;
  101902. var tz;
  101903. var sx;
  101904. var sy;
  101905. var sz;
  101906. var ex;
  101907. var ey;
  101908. var ez;
  101909. var depth1;
  101910. var depth2;
  101911. var dot;
  101912. var t1;
  101913. var t2;
  101914. var sep = new OIMO.Vec3();
  101915. var pos = new OIMO.Vec3();
  101916. var dep = new OIMO.Vec3();
  101917. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101918. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101919. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101920. var right1 = dot1 > 0;
  101921. var right2 = dot2 > 0;
  101922. if (!right1) dot1 = -dot1;
  101923. if (!right2) dot2 = -dot2;
  101924. var state = 0;
  101925. if (dot1 > 0.999 || dot2 > 0.999) {
  101926. if (dot1 > dot2) state = 1;
  101927. else state = 2;
  101928. }
  101929. var nx;
  101930. var ny;
  101931. var nz;
  101932. var depth = dep.x;
  101933. var r00;
  101934. var r01;
  101935. var r02;
  101936. var r10;
  101937. var r11;
  101938. var r12;
  101939. var r20;
  101940. var r21;
  101941. var r22;
  101942. var px;
  101943. var py;
  101944. var pz;
  101945. var pd;
  101946. var a;
  101947. var b;
  101948. var e;
  101949. var f;
  101950. nx = sep.x;
  101951. ny = sep.y;
  101952. nz = sep.z;
  101953. switch (state) {
  101954. case 0:
  101955. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  101956. break;
  101957. case 1:
  101958. if (right1) {
  101959. c1x = p1x + d1x;
  101960. c1y = p1y + d1y;
  101961. c1z = p1z + d1z;
  101962. nx = n1x;
  101963. ny = n1y;
  101964. nz = n1z;
  101965. } else {
  101966. c1x = p1x - d1x;
  101967. c1y = p1y - d1y;
  101968. c1z = p1z - d1z;
  101969. nx = -n1x;
  101970. ny = -n1y;
  101971. nz = -n1z;
  101972. }
  101973. dot = nx * n2x + ny * n2y + nz * n2z;
  101974. if (dot < 0) len = h2;
  101975. else len = -h2;
  101976. c2x = p2x + len * n2x;
  101977. c2y = p2y + len * n2y;
  101978. c2z = p2z + len * n2z;
  101979. if (dot2 >= 0.999999) {
  101980. tx = -ny;
  101981. ty = nz;
  101982. tz = nx;
  101983. } else {
  101984. tx = nx;
  101985. ty = ny;
  101986. tz = nz;
  101987. }
  101988. len = tx * n2x + ty * n2y + tz * n2z;
  101989. dx = len * n2x - tx;
  101990. dy = len * n2y - ty;
  101991. dz = len * n2z - tz;
  101992. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101993. if (len == 0) break;
  101994. len = r2 / len;
  101995. dx *= len;
  101996. dy *= len;
  101997. dz *= len;
  101998. tx = c2x + dx;
  101999. ty = c2y + dy;
  102000. tz = c2z + dz;
  102001. if (dot < -0.96 || dot > 0.96) {
  102002. r00 = n2x * n2x * 1.5 - 0.5;
  102003. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  102004. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  102005. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  102006. r11 = n2y * n2y * 1.5 - 0.5;
  102007. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  102008. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  102009. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  102010. r22 = n2z * n2z * 1.5 - 0.5;
  102011. px = tx;
  102012. py = ty;
  102013. pz = tz;
  102014. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102015. tx = px - pd * nx - c1x;
  102016. ty = py - pd * ny - c1y;
  102017. tz = pz - pd * nz - c1z;
  102018. len = tx * tx + ty * ty + tz * tz;
  102019. if (len > r1 * r1) {
  102020. len = r1 / OIMO.sqrt(len);
  102021. tx *= len;
  102022. ty *= len;
  102023. tz *= len;
  102024. }
  102025. px = c1x + tx;
  102026. py = c1y + ty;
  102027. pz = c1z + tz;
  102028. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102029. px = dx * r00 + dy * r01 + dz * r02;
  102030. py = dx * r10 + dy * r11 + dz * r12;
  102031. pz = dx * r20 + dy * r21 + dz * r22;
  102032. px = (dx = px) + c2x;
  102033. py = (dy = py) + c2y;
  102034. pz = (dz = pz) + c2z;
  102035. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102036. if (pd <= 0) {
  102037. tx = px - pd * nx - c1x;
  102038. ty = py - pd * ny - c1y;
  102039. tz = pz - pd * nz - c1z;
  102040. len = tx * tx + ty * ty + tz * tz;
  102041. if (len > r1 * r1) {
  102042. len = r1 / OIMO.sqrt(len);
  102043. tx *= len;
  102044. ty *= len;
  102045. tz *= len;
  102046. }
  102047. px = c1x + tx;
  102048. py = c1y + ty;
  102049. pz = c1z + tz;
  102050. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102051. }
  102052. px = dx * r00 + dy * r01 + dz * r02;
  102053. py = dx * r10 + dy * r11 + dz * r12;
  102054. pz = dx * r20 + dy * r21 + dz * r22;
  102055. px = (dx = px) + c2x;
  102056. py = (dy = py) + c2y;
  102057. pz = (dz = pz) + c2z;
  102058. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102059. if (pd <= 0) {
  102060. tx = px - pd * nx - c1x;
  102061. ty = py - pd * ny - c1y;
  102062. tz = pz - pd * nz - c1z;
  102063. len = tx * tx + ty * ty + tz * tz;
  102064. if (len > r1 * r1) {
  102065. len = r1 / OIMO.sqrt(len);
  102066. tx *= len;
  102067. ty *= len;
  102068. tz *= len;
  102069. }
  102070. px = c1x + tx;
  102071. py = c1y + ty;
  102072. pz = c1z + tz;
  102073. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102074. }
  102075. } else {
  102076. sx = tx;
  102077. sy = ty;
  102078. sz = tz;
  102079. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  102080. sx -= depth1 * nx;
  102081. sy -= depth1 * ny;
  102082. sz -= depth1 * nz;
  102083. if (dot > 0) {
  102084. ex = tx + n2x * h2 * 2;
  102085. ey = ty + n2y * h2 * 2;
  102086. ez = tz + n2z * h2 * 2;
  102087. } else {
  102088. ex = tx - n2x * h2 * 2;
  102089. ey = ty - n2y * h2 * 2;
  102090. ez = tz - n2z * h2 * 2;
  102091. }
  102092. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102093. ex -= depth2 * nx;
  102094. ey -= depth2 * ny;
  102095. ez -= depth2 * nz;
  102096. dx = c1x - sx;
  102097. dy = c1y - sy;
  102098. dz = c1z - sz;
  102099. tx = ex - sx;
  102100. ty = ey - sy;
  102101. tz = ez - sz;
  102102. a = dx * dx + dy * dy + dz * dz;
  102103. b = dx * tx + dy * ty + dz * tz;
  102104. e = tx * tx + ty * ty + tz * tz;
  102105. f = b * b - e * (a - r1 * r1);
  102106. if (f < 0) break;
  102107. f = OIMO.sqrt(f);
  102108. t1 = (b + f) / e;
  102109. t2 = (b - f) / e;
  102110. if (t2 < t1) {
  102111. len = t1;
  102112. t1 = t2;
  102113. t2 = len;
  102114. }
  102115. if (t2 > 1) t2 = 1;
  102116. if (t1 < 0) t1 = 0;
  102117. tx = sx + (ex - sx) * t1;
  102118. ty = sy + (ey - sy) * t1;
  102119. tz = sz + (ez - sz) * t1;
  102120. ex = sx + (ex - sx) * t2;
  102121. ey = sy + (ey - sy) * t2;
  102122. ez = sz + (ez - sz) * t2;
  102123. sx = tx;
  102124. sy = ty;
  102125. sz = tz;
  102126. len = depth1 + (depth2 - depth1) * t1;
  102127. depth2 = depth1 + (depth2 - depth1) * t2;
  102128. depth1 = len;
  102129. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102130. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102131. }
  102132. break;
  102133. case 2:
  102134. if (right2) {
  102135. c2x = p2x - d2x;
  102136. c2y = p2y - d2y;
  102137. c2z = p2z - d2z;
  102138. nx = -n2x;
  102139. ny = -n2y;
  102140. nz = -n2z;
  102141. } else {
  102142. c2x = p2x + d2x;
  102143. c2y = p2y + d2y;
  102144. c2z = p2z + d2z;
  102145. nx = n2x;
  102146. ny = n2y;
  102147. nz = n2z;
  102148. }
  102149. dot = nx * n1x + ny * n1y + nz * n1z;
  102150. if (dot < 0) len = h1;
  102151. else len = -h1;
  102152. c1x = p1x + len * n1x;
  102153. c1y = p1y + len * n1y;
  102154. c1z = p1z + len * n1z;
  102155. if (dot1 >= 0.999999) {
  102156. tx = -ny;
  102157. ty = nz;
  102158. tz = nx;
  102159. } else {
  102160. tx = nx;
  102161. ty = ny;
  102162. tz = nz;
  102163. }
  102164. len = tx * n1x + ty * n1y + tz * n1z;
  102165. dx = len * n1x - tx;
  102166. dy = len * n1y - ty;
  102167. dz = len * n1z - tz;
  102168. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102169. if (len == 0) break;
  102170. len = r1 / len;
  102171. dx *= len;
  102172. dy *= len;
  102173. dz *= len;
  102174. tx = c1x + dx;
  102175. ty = c1y + dy;
  102176. tz = c1z + dz;
  102177. if (dot < -0.96 || dot > 0.96) {
  102178. r00 = n1x * n1x * 1.5 - 0.5;
  102179. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102180. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102181. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102182. r11 = n1y * n1y * 1.5 - 0.5;
  102183. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102184. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102185. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102186. r22 = n1z * n1z * 1.5 - 0.5;
  102187. px = tx;
  102188. py = ty;
  102189. pz = tz;
  102190. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102191. tx = px - pd * nx - c2x;
  102192. ty = py - pd * ny - c2y;
  102193. tz = pz - pd * nz - c2z;
  102194. len = tx * tx + ty * ty + tz * tz;
  102195. if (len > r2 * r2) {
  102196. len = r2 / OIMO.sqrt(len);
  102197. tx *= len;
  102198. ty *= len;
  102199. tz *= len;
  102200. }
  102201. px = c2x + tx;
  102202. py = c2y + ty;
  102203. pz = c2z + tz;
  102204. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102205. px = dx * r00 + dy * r01 + dz * r02;
  102206. py = dx * r10 + dy * r11 + dz * r12;
  102207. pz = dx * r20 + dy * r21 + dz * r22;
  102208. px = (dx = px) + c1x;
  102209. py = (dy = py) + c1y;
  102210. pz = (dz = pz) + c1z;
  102211. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102212. if (pd <= 0) {
  102213. tx = px - pd * nx - c2x;
  102214. ty = py - pd * ny - c2y;
  102215. tz = pz - pd * nz - c2z;
  102216. len = tx * tx + ty * ty + tz * tz;
  102217. if (len > r2 * r2) {
  102218. len = r2 / OIMO.sqrt(len);
  102219. tx *= len;
  102220. ty *= len;
  102221. tz *= len;
  102222. }
  102223. px = c2x + tx;
  102224. py = c2y + ty;
  102225. pz = c2z + tz;
  102226. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102227. }
  102228. px = dx * r00 + dy * r01 + dz * r02;
  102229. py = dx * r10 + dy * r11 + dz * r12;
  102230. pz = dx * r20 + dy * r21 + dz * r22;
  102231. px = (dx = px) + c1x;
  102232. py = (dy = py) + c1y;
  102233. pz = (dz = pz) + c1z;
  102234. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102235. if (pd <= 0) {
  102236. tx = px - pd * nx - c2x;
  102237. ty = py - pd * ny - c2y;
  102238. tz = pz - pd * nz - c2z;
  102239. len = tx * tx + ty * ty + tz * tz;
  102240. if (len > r2 * r2) {
  102241. len = r2 / OIMO.sqrt(len);
  102242. tx *= len;
  102243. ty *= len;
  102244. tz *= len;
  102245. }
  102246. px = c2x + tx;
  102247. py = c2y + ty;
  102248. pz = c2z + tz;
  102249. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102250. }
  102251. } else {
  102252. sx = tx;
  102253. sy = ty;
  102254. sz = tz;
  102255. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102256. sx -= depth1 * nx;
  102257. sy -= depth1 * ny;
  102258. sz -= depth1 * nz;
  102259. if (dot > 0) {
  102260. ex = tx + n1x * h1 * 2;
  102261. ey = ty + n1y * h1 * 2;
  102262. ez = tz + n1z * h1 * 2;
  102263. } else {
  102264. ex = tx - n1x * h1 * 2;
  102265. ey = ty - n1y * h1 * 2;
  102266. ez = tz - n1z * h1 * 2;
  102267. }
  102268. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102269. ex -= depth2 * nx;
  102270. ey -= depth2 * ny;
  102271. ez -= depth2 * nz;
  102272. dx = c2x - sx;
  102273. dy = c2y - sy;
  102274. dz = c2z - sz;
  102275. tx = ex - sx;
  102276. ty = ey - sy;
  102277. tz = ez - sz;
  102278. a = dx * dx + dy * dy + dz * dz;
  102279. b = dx * tx + dy * ty + dz * tz;
  102280. e = tx * tx + ty * ty + tz * tz;
  102281. f = b * b - e * (a - r2 * r2);
  102282. if (f < 0) break;
  102283. f = OIMO.sqrt(f);
  102284. t1 = (b + f) / e;
  102285. t2 = (b - f) / e;
  102286. if (t2 < t1) {
  102287. len = t1;
  102288. t1 = t2;
  102289. t2 = len;
  102290. }
  102291. if (t2 > 1) t2 = 1;
  102292. if (t1 < 0) t1 = 0;
  102293. tx = sx + (ex - sx) * t1;
  102294. ty = sy + (ey - sy) * t1;
  102295. tz = sz + (ez - sz) * t1;
  102296. ex = sx + (ex - sx) * t2;
  102297. ey = sy + (ey - sy) * t2;
  102298. ez = sz + (ez - sz) * t2;
  102299. sx = tx;
  102300. sy = ty;
  102301. sz = tz;
  102302. len = depth1 + (depth2 - depth1) * t1;
  102303. depth2 = depth1 + (depth2 - depth1) * t2;
  102304. depth1 = len;
  102305. if (depth1 < 0) {
  102306. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102307. }
  102308. if (depth2 < 0) {
  102309. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102310. }
  102311. }
  102312. break;
  102313. }
  102314. };
  102315. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102316. OIMO.CollisionDetector.call(this);
  102317. this.flip = flip;
  102318. };
  102319. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102320. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102321. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102322. var s;
  102323. var c;
  102324. if (this.flip) {
  102325. s = shape2;
  102326. c = shape1;
  102327. } else {
  102328. s = shape1;
  102329. c = shape2;
  102330. }
  102331. var ps = s.position;
  102332. var psx = ps.x;
  102333. var psy = ps.y;
  102334. var psz = ps.z;
  102335. var pc = c.position;
  102336. var pcx = pc.x;
  102337. var pcy = pc.y;
  102338. var pcz = pc.z;
  102339. var dirx = c.normalDirection.x;
  102340. var diry = c.normalDirection.y;
  102341. var dirz = c.normalDirection.z;
  102342. var rads = s.radius;
  102343. var radc = c.radius;
  102344. var rad2 = rads + radc;
  102345. var halfh = c.halfHeight;
  102346. var dx = psx - pcx;
  102347. var dy = psy - pcy;
  102348. var dz = psz - pcz;
  102349. var dot = dx * dirx + dy * diry + dz * dirz;
  102350. if (dot < -halfh - rads || dot > halfh + rads) return;
  102351. var cx = pcx + dot * dirx;
  102352. var cy = pcy + dot * diry;
  102353. var cz = pcz + dot * dirz;
  102354. var d2x = psx - cx;
  102355. var d2y = psy - cy;
  102356. var d2z = psz - cz;
  102357. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102358. if (len > rad2 * rad2) return;
  102359. if (len > radc * radc) {
  102360. len = radc / OIMO.sqrt(len);
  102361. d2x *= len;
  102362. d2y *= len;
  102363. d2z *= len;
  102364. }
  102365. if (dot < -halfh) dot = -halfh;
  102366. else if (dot > halfh) dot = halfh;
  102367. cx = pcx + dot * dirx + d2x;
  102368. cy = pcy + dot * diry + d2y;
  102369. cz = pcz + dot * dirz + d2z;
  102370. dx = cx - psx;
  102371. dy = cy - psy;
  102372. dz = cz - psz;
  102373. len = dx * dx + dy * dy + dz * dz;
  102374. var invLen;
  102375. if (len > 0 && len < rads * rads) {
  102376. len = OIMO.sqrt(len);
  102377. invLen = 1 / len;
  102378. dx *= invLen;
  102379. dy *= invLen;
  102380. dz *= invLen;
  102381. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102382. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102383. }
  102384. };
  102385. /**
  102386. * Class for checking collisions between 2 tetras,
  102387. * a shape that is made with 4 vertices and 4 faces
  102388. * arranged in triangles. With this algorigthm, soft
  102389. * body physics are possible and easier to implement.
  102390. * @author xprogram
  102391. */
  102392. OIMO.TetraTetraCollisionDetector = function () {
  102393. OIMO.CollisionDetector.call(this);
  102394. };
  102395. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102396. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102397. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102398. /*
  102399. * What we are doing:
  102400. * Each tetra is represented by four 3D triangles. The only
  102401. * quick way of finding if another tetra is within the other
  102402. * tetra is to see if a single vertex is within the triangles
  102403. * of the other tetra. So, for example, a tetra is represented
  102404. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102405. * There is another tetra with a vertex A which was detected for
  102406. * collision by the broadphase. Now, if the point A is between ALL
  102407. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102408. * is valid and we can pass point A to the manifold. Since the only
  102409. * points on the tetra are the 4 vertices, collision detection is
  102410. * not so complex. However, it can be time-consuming because we
  102411. * need to split the 3D triangles into three 2D triangles each for
  102412. * collision detection.
  102413. */
  102414. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102415. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102416. // fs is undeclared
  102417. var fs = fs1;
  102418. for (i = 0; i < 4; i++) {
  102419. vec = vs1[i];
  102420. for (j = 0; j < 4; j++) {
  102421. j1 = vs2[fs[i].a];
  102422. j2 = vs2[fs[i].b];
  102423. j3 = vs2[fs[i].c];
  102424. if (
  102425. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102426. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102427. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102428. )
  102429. ts++;
  102430. if (ts === 4) // Only add point if it is inside all 4 triangles
  102431. manifold.addPoint(vec);
  102432. }
  102433. }
  102434. };
  102435. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102436. function tricheck(p, p0, p1, p2) {
  102437. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102438. var sg = A < 0 ? -1 : 1;
  102439. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102440. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102441. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102442. }
  102443. function pt(x, y) { return { x: x, y: y }; }
  102444. /**
  102445. * An axis-aligned bounding box.
  102446. * @author saharan
  102447. * @author lo-th
  102448. */
  102449. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102450. this.elements = new OIMO_ARRAY_TYPE(6);
  102451. var te = this.elements;
  102452. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102453. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102454. };
  102455. OIMO.AABB.prototype = {
  102456. constructor: OIMO.AABB,
  102457. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102458. var te = this.elements;
  102459. te[0] = minX; te[3] = maxX;
  102460. te[1] = minY; te[4] = maxY;
  102461. te[2] = minZ; te[5] = maxZ;
  102462. return this;
  102463. },
  102464. intersectTest: function (aabb) {
  102465. var te = this.elements;
  102466. var ue = aabb.elements;
  102467. 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];
  102468. },
  102469. intersectTestTwo: function (aabb) {
  102470. var te = this.elements;
  102471. var ue = aabb.elements;
  102472. 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];
  102473. },
  102474. clone: function () {
  102475. return new this.constructor().fromArray(this.elements);
  102476. },
  102477. copy: function (aabb, margin) {
  102478. var m = margin || 0;
  102479. var me = aabb.elements;
  102480. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102481. return this;
  102482. },
  102483. fromArray: function (array) {
  102484. this.elements.set(array);
  102485. return this;
  102486. },
  102487. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102488. combine: function (aabb1, aabb2) {
  102489. var a = aabb1.elements;
  102490. var b = aabb2.elements;
  102491. var te = this.elements;
  102492. te[0] = a[0] < b[0] ? a[0] : b[0];
  102493. te[1] = a[1] < b[1] ? a[1] : b[1];
  102494. te[2] = a[2] < b[2] ? a[2] : b[2];
  102495. te[3] = a[3] > b[3] ? a[3] : b[3];
  102496. te[4] = a[4] > b[4] ? a[4] : b[4];
  102497. te[5] = a[5] > b[5] ? a[5] : b[5];
  102498. return this;
  102499. },
  102500. // Get the surface area.
  102501. surfaceArea: function () {
  102502. var te = this.elements;
  102503. var a = te[3] - te[0];
  102504. var h = te[4] - te[1];
  102505. var d = te[5] - te[2];
  102506. return 2 * (a * (h + d) + h * d);
  102507. },
  102508. // Get whether the AABB intersects with the point or not.
  102509. intersectsWithPoint: function (x, y, z) {
  102510. var te = this.elements;
  102511. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102512. },
  102513. /**
  102514. * Set the AABB from an array
  102515. * of vertices. From THREE.
  102516. * @author mrdoob
  102517. * @author xprogram
  102518. */
  102519. setFromPoints: function (arr) {
  102520. this.makeEmpty();
  102521. for (var i = 0; i < arr.length; i++) {
  102522. this.expandByPoint(arr[i]);
  102523. }
  102524. },
  102525. makeEmpty: function () {
  102526. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102527. },
  102528. expandByPoint: function (pt) {
  102529. var te = this.elements;
  102530. this.set(
  102531. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102532. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102533. );
  102534. }
  102535. };
  102536. /**
  102537. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102538. */
  102539. OIMO.Proxy = function (shape) {
  102540. // The parent shape.
  102541. this.shape = shape;
  102542. // The axis-aligned bounding box.
  102543. this.aabb = shape.aabb;
  102544. };
  102545. OIMO.Proxy.prototype = {
  102546. constructor: OIMO.Proxy,
  102547. // Update the proxy.
  102548. update: function () {
  102549. OIMO.Error("Proxy", "Inheritance error.");
  102550. }
  102551. };
  102552. /**
  102553. * A basic implementation of proxies.
  102554. * @author saharan
  102555. */
  102556. OIMO.BasicProxy = function (shape) {
  102557. OIMO.Proxy.call(this, shape);
  102558. this.id = OIMO.proxyID++;
  102559. };
  102560. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102561. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102562. OIMO.BasicProxy.prototype.update = function () {
  102563. };
  102564. /**
  102565. * The broad-phase is used for collecting all possible pairs for collision.
  102566. */
  102567. OIMO.BroadPhase = function () {
  102568. this.types = OIMO.BR_NULL;
  102569. this.numPairChecks = 0;
  102570. this.numPairs = 0;
  102571. this.pairs = [];
  102572. };
  102573. OIMO.BroadPhase.prototype = {
  102574. constructor: OIMO.BroadPhase,
  102575. /**
  102576. * Create a new proxy.
  102577. * @param shape
  102578. * @return
  102579. */
  102580. createProxy: function (shape) {
  102581. OIMO.Error("BroadPhase", "Inheritance error.");
  102582. },
  102583. /**
  102584. * Add the proxy into the broad-phase.
  102585. * @param proxy
  102586. */
  102587. addProxy: function (proxy) {
  102588. OIMO.Error("BroadPhase", "Inheritance error.");
  102589. },
  102590. /**
  102591. * Remove the proxy from the broad-phase.
  102592. * @param proxy
  102593. */
  102594. removeProxy: function (proxy) {
  102595. OIMO.Error("BroadPhase", "Inheritance error.");
  102596. },
  102597. /**
  102598. * Returns whether the pair is available or not.
  102599. * @param s1
  102600. * @param s2
  102601. * @return
  102602. */
  102603. isAvailablePair: function (s1, s2) {
  102604. var b1 = s1.parent;
  102605. var b2 = s2.parent;
  102606. if (b1 == b2 || // same parents
  102607. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102608. (s1.belongsTo & s2.collidesWith) == 0 ||
  102609. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102610. ) { return false; }
  102611. var js;
  102612. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102613. else js = b2.jointLink;
  102614. while (js !== null) {
  102615. var joint = js.joint;
  102616. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102617. js = js.next;
  102618. }
  102619. return true;
  102620. },
  102621. // Detect overlapping pairs.
  102622. detectPairs: function () {
  102623. // clear old
  102624. this.pairs = [];
  102625. this.numPairs = 0;
  102626. this.numPairChecks = 0;
  102627. this.collectPairs();
  102628. },
  102629. collectPairs: function () {
  102630. OIMO.Error("BroadPhase", "Inheritance error.");
  102631. },
  102632. addPair: function (s1, s2) {
  102633. var pair = new OIMO.Pair(s1, s2);
  102634. this.pairs.push(pair);
  102635. this.numPairs++;
  102636. }
  102637. };
  102638. /**
  102639. * A broad-phase algorithm with brute-force search.
  102640. * This always checks for all possible pairs.
  102641. */
  102642. OIMO.BruteForceBroadPhase = function () {
  102643. OIMO.BroadPhase.call(this);
  102644. this.types = OIMO.BR_BRUTE_FORCE;;
  102645. //this.numProxies=0;
  102646. ///this.maxProxies = 256;
  102647. this.proxies = [];
  102648. //this.proxies.length = 256;
  102649. };
  102650. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102651. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102652. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102653. return new OIMO.BasicProxy(shape);
  102654. };
  102655. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102656. /*if(this.numProxies==this.maxProxies){
  102657. //this.maxProxies<<=1;
  102658. this.maxProxies*=2;
  102659. var newProxies=[];
  102660. newProxies.length = this.maxProxies;
  102661. var i = this.numProxies;
  102662. while(i--){
  102663. //for(var i=0, l=this.numProxies;i<l;i++){
  102664. newProxies[i]=this.proxies[i];
  102665. }
  102666. this.proxies=newProxies;
  102667. }*/
  102668. //this.proxies[this.numProxies++] = proxy;
  102669. this.proxies.push(proxy);
  102670. //this.numProxies++;
  102671. };
  102672. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102673. var n = this.proxies.indexOf(proxy);
  102674. if (n > -1) {
  102675. this.proxies.splice(n, 1);
  102676. //this.numProxies--;
  102677. }
  102678. /*var i = this.numProxies;
  102679. while(i--){
  102680. //for(var i=0, l=this.numProxies;i<l;i++){
  102681. if(this.proxies[i] == proxy){
  102682. this.proxies[i] = this.proxies[--this.numProxies];
  102683. this.proxies[this.numProxies] = null;
  102684. return;
  102685. }
  102686. }*/
  102687. };
  102688. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102689. var i = 0, j, p1, p2;
  102690. var px = this.proxies;
  102691. var l = px.length;//this.numProxies;
  102692. //var ar1 = [];
  102693. //var ar2 = [];
  102694. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102695. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102696. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102697. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102698. this.numPairChecks = l * (l - 1) >> 1;
  102699. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102700. while (i < l) {
  102701. p1 = px[i++];
  102702. j = i + 1;
  102703. while (j < l) {
  102704. p2 = px[j++];
  102705. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102706. this.addPair(p1.shape, p2.shape);
  102707. }
  102708. }
  102709. };
  102710. /**
  102711. * A pair of shapes that may collide.
  102712. * @author saharan
  102713. */
  102714. OIMO.Pair = function (s1, s2) {
  102715. // The first shape.
  102716. this.shape1 = s1 || null;
  102717. // The second shape.
  102718. this.shape2 = s2 || null;
  102719. };
  102720. /**
  102721. * A projection axis for sweep and prune broad-phase.
  102722. * @author saharan
  102723. */
  102724. OIMO.SAPAxis = function () {
  102725. this.numElements = 0;
  102726. this.bufferSize = 256;
  102727. this.elements = [];
  102728. this.elements.length = this.bufferSize;
  102729. this.stack = new OIMO_ARRAY_TYPE(64);
  102730. };
  102731. OIMO.SAPAxis.prototype = {
  102732. constructor: OIMO.SAPAxis,
  102733. addElements: function (min, max) {
  102734. if (this.numElements + 2 >= this.bufferSize) {
  102735. //this.bufferSize<<=1;
  102736. this.bufferSize *= 2;
  102737. var newElements = [];
  102738. var i = this.numElements;
  102739. while (i--) {
  102740. //for(var i=0, l=this.numElements; i<l; i++){
  102741. newElements[i] = this.elements[i];
  102742. }
  102743. }
  102744. this.elements[this.numElements++] = min;
  102745. this.elements[this.numElements++] = max;
  102746. },
  102747. removeElements: function (min, max) {
  102748. var minIndex = -1;
  102749. var maxIndex = -1;
  102750. for (var i = 0, l = this.numElements; i < l; i++) {
  102751. var e = this.elements[i];
  102752. if (e == min || e == max) {
  102753. if (minIndex == -1) {
  102754. minIndex = i;
  102755. } else {
  102756. maxIndex = i;
  102757. break;
  102758. }
  102759. }
  102760. }
  102761. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102762. this.elements[i - 1] = this.elements[i];
  102763. }
  102764. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102765. this.elements[i - 2] = this.elements[i];
  102766. }
  102767. this.elements[--this.numElements] = null;
  102768. this.elements[--this.numElements] = null;
  102769. },
  102770. sort: function () {
  102771. var count = 0;
  102772. var threshold = 1;
  102773. while ((this.numElements >> threshold) != 0) threshold++;
  102774. threshold = threshold * this.numElements >> 2;
  102775. count = 0;
  102776. var giveup = false;
  102777. var elements = this.elements;
  102778. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102779. var tmp = elements[i];
  102780. var pivot = tmp.value;
  102781. var tmp2 = elements[i - 1];
  102782. if (tmp2.value > pivot) {
  102783. var j = i;
  102784. do {
  102785. elements[j] = tmp2;
  102786. if (--j == 0) break;
  102787. tmp2 = elements[j - 1];
  102788. } while (tmp2.value > pivot);
  102789. elements[j] = tmp;
  102790. count += i - j;
  102791. if (count > threshold) {
  102792. giveup = true; // stop and use quick sort
  102793. break;
  102794. }
  102795. }
  102796. }
  102797. if (!giveup) return;
  102798. count = 2; var stack = this.stack;
  102799. stack[0] = 0;
  102800. stack[1] = this.numElements - 1;
  102801. while (count > 0) {
  102802. var right = stack[--count];
  102803. var left = stack[--count];
  102804. var diff = right - left;
  102805. if (diff > 16) { // quick sort
  102806. //var mid=left+(diff>>1);
  102807. var mid = left + (OIMO.floor(diff * 0.5));
  102808. tmp = elements[mid];
  102809. elements[mid] = elements[right];
  102810. elements[right] = tmp;
  102811. pivot = tmp.value;
  102812. i = left - 1;
  102813. j = right;
  102814. while (true) {
  102815. var ei;
  102816. var ej;
  102817. do { ei = elements[++i]; } while (ei.value < pivot);
  102818. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102819. if (i >= j) break;
  102820. elements[i] = ej;
  102821. elements[j] = ei;
  102822. }
  102823. elements[right] = elements[i];
  102824. elements[i] = tmp;
  102825. if (i - left > right - i) {
  102826. stack[count++] = left;
  102827. stack[count++] = i - 1;
  102828. stack[count++] = i + 1;
  102829. stack[count++] = right;
  102830. } else {
  102831. stack[count++] = i + 1;
  102832. stack[count++] = right;
  102833. stack[count++] = left;
  102834. stack[count++] = i - 1;
  102835. }
  102836. } else {
  102837. for (i = left + 1; i <= right; i++) {
  102838. tmp = elements[i];
  102839. pivot = tmp.value;
  102840. tmp2 = elements[i - 1];
  102841. if (tmp2.value > pivot) {
  102842. j = i;
  102843. do {
  102844. elements[j] = tmp2;
  102845. if (--j == 0) break;
  102846. tmp2 = elements[j - 1];
  102847. } while (tmp2.value > pivot);
  102848. elements[j] = tmp;
  102849. }
  102850. }
  102851. }
  102852. }
  102853. },
  102854. calculateTestCount: function () {
  102855. var num = 1;
  102856. var sum = 0;
  102857. for (var i = 1, l = this.numElements; i < l; i++) {
  102858. if (this.elements[i].max) {
  102859. num--;
  102860. } else {
  102861. sum += num;
  102862. num++;
  102863. }
  102864. }
  102865. return sum;
  102866. }
  102867. }
  102868. /**
  102869. * A broad-phase collision detection algorithm using sweep and prune.
  102870. * @author saharan
  102871. * @author lo-th
  102872. */
  102873. OIMO.SAPBroadPhase = function () {
  102874. OIMO.BroadPhase.call(this);
  102875. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102876. this.numElementsD = 0;
  102877. this.numElementsS = 0;
  102878. // dynamic proxies
  102879. this.axesD = [
  102880. new OIMO.SAPAxis(),
  102881. new OIMO.SAPAxis(),
  102882. new OIMO.SAPAxis()
  102883. ];
  102884. // static or sleeping proxies
  102885. this.axesS = [
  102886. new OIMO.SAPAxis(),
  102887. new OIMO.SAPAxis(),
  102888. new OIMO.SAPAxis()
  102889. ];
  102890. this.index1 = 0;
  102891. this.index2 = 1;
  102892. };
  102893. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102894. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102895. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102896. return new OIMO.SAPProxy(this, shape);
  102897. };
  102898. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102899. var p = proxy;
  102900. if (p.isDynamic()) {
  102901. this.axesD[0].addElements(p.min[0], p.max[0]);
  102902. this.axesD[1].addElements(p.min[1], p.max[1]);
  102903. this.axesD[2].addElements(p.min[2], p.max[2]);
  102904. p.belongsTo = 1;
  102905. this.numElementsD += 2;
  102906. } else {
  102907. this.axesS[0].addElements(p.min[0], p.max[0]);
  102908. this.axesS[1].addElements(p.min[1], p.max[1]);
  102909. this.axesS[2].addElements(p.min[2], p.max[2]);
  102910. p.belongsTo = 2;
  102911. this.numElementsS += 2;
  102912. }
  102913. };
  102914. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102915. var p = proxy;
  102916. if (p.belongsTo == 0) return;
  102917. /*else if ( p.belongsTo == 1 ) {
  102918. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102919. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102920. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102921. this.numElementsD -= 2;
  102922. } else if ( p.belongsTo == 2 ) {
  102923. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102924. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102925. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102926. this.numElementsS -= 2;
  102927. }*/
  102928. switch (p.belongsTo) {
  102929. case 1:
  102930. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102931. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102932. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102933. this.numElementsD -= 2;
  102934. break;
  102935. case 2:
  102936. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102937. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102938. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102939. this.numElementsS -= 2;
  102940. break;
  102941. }
  102942. p.belongsTo = 0;
  102943. };
  102944. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102945. if (this.numElementsD == 0) return;
  102946. var axis1 = this.axesD[this.index1];
  102947. var axis2 = this.axesD[this.index2];
  102948. axis1.sort();
  102949. axis2.sort();
  102950. var count1 = axis1.calculateTestCount();
  102951. var count2 = axis2.calculateTestCount();
  102952. var elementsD;
  102953. var elementsS;
  102954. if (count1 <= count2) {// select the best axis
  102955. axis2 = this.axesS[this.index1];
  102956. axis2.sort();
  102957. elementsD = axis1.elements;
  102958. elementsS = axis2.elements;
  102959. } else {
  102960. axis1 = this.axesS[this.index2];
  102961. axis1.sort();
  102962. elementsD = axis2.elements;
  102963. elementsS = axis1.elements;
  102964. this.index1 ^= this.index2;
  102965. this.index2 ^= this.index1;
  102966. this.index1 ^= this.index2;
  102967. }
  102968. var activeD;
  102969. var activeS;
  102970. var p = 0;
  102971. var q = 0;
  102972. while (p < this.numElementsD) {
  102973. var e1;
  102974. var dyn;
  102975. if (q == this.numElementsS) {
  102976. e1 = elementsD[p];
  102977. dyn = true;
  102978. p++;
  102979. } else {
  102980. var d = elementsD[p];
  102981. var s = elementsS[q];
  102982. if (d.value < s.value) {
  102983. e1 = d;
  102984. dyn = true;
  102985. p++;
  102986. } else {
  102987. e1 = s;
  102988. dyn = false;
  102989. q++;
  102990. }
  102991. }
  102992. if (!e1.max) {
  102993. var s1 = e1.proxy.shape;
  102994. var min1 = e1.min1.value;
  102995. var max1 = e1.max1.value;
  102996. var min2 = e1.min2.value;
  102997. var max2 = e1.max2.value;
  102998. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  102999. var s2 = e2.proxy.shape;
  103000. this.numPairChecks++;
  103001. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103002. this.addPair(s1, s2);
  103003. }
  103004. if (dyn) {
  103005. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  103006. s2 = e2.proxy.shape;
  103007. this.numPairChecks++;
  103008. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103009. this.addPair(s1, s2);
  103010. }
  103011. e1.pair = activeD;
  103012. activeD = e1;
  103013. } else {
  103014. e1.pair = activeS;
  103015. activeS = e1;
  103016. }
  103017. } else {
  103018. var min = e1.pair;
  103019. if (dyn) {
  103020. if (min == activeD) {
  103021. activeD = activeD.pair;
  103022. continue;
  103023. } else {
  103024. e1 = activeD;
  103025. }
  103026. } else {
  103027. if (min == activeS) {
  103028. activeS = activeS.pair;
  103029. continue;
  103030. } else {
  103031. e1 = activeS;
  103032. }
  103033. }
  103034. do {
  103035. e2 = e1.pair;
  103036. if (e2 == min) {
  103037. e1.pair = e2.pair;
  103038. break;
  103039. }
  103040. e1 = e2;
  103041. } while (e1 != null);
  103042. }
  103043. }
  103044. this.index2 = (this.index1 | this.index2) ^ 3;
  103045. };
  103046. /**
  103047. * An element of proxies.
  103048. * @author saharan
  103049. */
  103050. OIMO.SAPElement = function (proxy, max) {
  103051. // The parent proxy
  103052. this.proxy = proxy;
  103053. // The pair element.
  103054. this.pair = null;
  103055. // The minimum element on other axis.
  103056. this.min1 = null;
  103057. // The maximum element on other axis.
  103058. this.max1 = null;
  103059. // The minimum element on other axis.
  103060. this.min2 = null;
  103061. // The maximum element on other axis.
  103062. this.max2 = null;
  103063. // Whether the element has maximum value or not.
  103064. this.max = max;
  103065. // The value of the element.
  103066. this.value = 0;
  103067. };
  103068. /**
  103069. * A proxy for sweep and prune broad-phase.
  103070. * @author saharan
  103071. * @author lo-th
  103072. */
  103073. OIMO.SAPProxy = function (sap, shape) {
  103074. OIMO.Proxy.call(this, shape);
  103075. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  103076. this.belongsTo = 0;
  103077. // The maximum elements on each axis.
  103078. this.max = [];
  103079. // The minimum elements on each axis.
  103080. this.min = [];
  103081. this.sap = sap;
  103082. this.min[0] = new OIMO.SAPElement(this, false);
  103083. this.max[0] = new OIMO.SAPElement(this, true);
  103084. this.min[1] = new OIMO.SAPElement(this, false);
  103085. this.max[1] = new OIMO.SAPElement(this, true);
  103086. this.min[2] = new OIMO.SAPElement(this, false);
  103087. this.max[2] = new OIMO.SAPElement(this, true);
  103088. this.max[0].pair = this.min[0];
  103089. this.max[1].pair = this.min[1];
  103090. this.max[2].pair = this.min[2];
  103091. this.min[0].min1 = this.min[1];
  103092. this.min[0].max1 = this.max[1];
  103093. this.min[0].min2 = this.min[2];
  103094. this.min[0].max2 = this.max[2];
  103095. this.min[1].min1 = this.min[0];
  103096. this.min[1].max1 = this.max[0];
  103097. this.min[1].min2 = this.min[2];
  103098. this.min[1].max2 = this.max[2];
  103099. this.min[2].min1 = this.min[0];
  103100. this.min[2].max1 = this.max[0];
  103101. this.min[2].min2 = this.min[1];
  103102. this.min[2].max2 = this.max[1];
  103103. };
  103104. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103105. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103106. // Returns whether the proxy is dynamic or not.
  103107. OIMO.SAPProxy.prototype.isDynamic = function () {
  103108. var body = this.shape.parent;
  103109. return body.isDynamic && !body.sleeping;
  103110. };
  103111. OIMO.SAPProxy.prototype.update = function () {
  103112. var te = this.aabb.elements;
  103113. this.min[0].value = te[0];
  103114. this.min[1].value = te[1];
  103115. this.min[2].value = te[2];
  103116. this.max[0].value = te[3];
  103117. this.max[1].value = te[4];
  103118. this.max[2].value = te[5];
  103119. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103120. this.sap.removeProxy(this);
  103121. this.sap.addProxy(this);
  103122. }
  103123. };
  103124. /**
  103125. * A dynamic bounding volume tree for the broad-phase algorithm.
  103126. * @author saharan
  103127. * @author lo-th
  103128. */
  103129. OIMO.DBVT = function () {
  103130. // The root of the tree.
  103131. this.root = null;
  103132. this.freeNodes = [];
  103133. this.freeNodes.length = 16384;
  103134. this.numFreeNodes = 0;
  103135. this.aabb = new OIMO.AABB();
  103136. };
  103137. OIMO.DBVT.prototype = {
  103138. constructor: OIMO.DBVT,
  103139. /**
  103140. * Move a leaf.
  103141. * @param leaf
  103142. */
  103143. moveLeaf: function (leaf) {
  103144. this.deleteLeaf(leaf);
  103145. this.insertLeaf(leaf);
  103146. },
  103147. /**
  103148. * Insert a leaf to the tree.
  103149. * @param node
  103150. */
  103151. insertLeaf: function (leaf) {
  103152. if (this.root == null) {
  103153. this.root = leaf;
  103154. return;
  103155. }
  103156. var lb = leaf.aabb;
  103157. var sibling = this.root;
  103158. var oldArea;
  103159. var newArea;
  103160. while (sibling.proxy == null) { // descend the node to search the best pair
  103161. var c1 = sibling.child1;
  103162. var c2 = sibling.child2;
  103163. var b = sibling.aabb;
  103164. var c1b = c1.aabb;
  103165. var c2b = c2.aabb;
  103166. oldArea = b.surfaceArea();
  103167. this.aabb.combine(lb, b);
  103168. newArea = this.aabb.surfaceArea();
  103169. var creatingCost = newArea * 2;
  103170. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103171. var discendingCost1 = incrementalCost;
  103172. this.aabb.combine(lb, c1b);
  103173. if (c1.proxy != null) {
  103174. // leaf cost = area(combined aabb)
  103175. discendingCost1 += this.aabb.surfaceArea();
  103176. } else {
  103177. // node cost = area(combined aabb) - area(old aabb)
  103178. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103179. }
  103180. var discendingCost2 = incrementalCost;
  103181. this.aabb.combine(lb, c2b);
  103182. if (c2.proxy != null) {
  103183. // leaf cost = area(combined aabb)
  103184. discendingCost2 += this.aabb.surfaceArea();
  103185. } else {
  103186. // node cost = area(combined aabb) - area(old aabb)
  103187. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103188. }
  103189. if (discendingCost1 < discendingCost2) {
  103190. if (creatingCost < discendingCost1) {
  103191. break;// stop descending
  103192. } else {
  103193. sibling = c1;// descend into first child
  103194. }
  103195. } else {
  103196. if (creatingCost < discendingCost2) {
  103197. break;// stop descending
  103198. } else {
  103199. sibling = c2;// descend into second child
  103200. }
  103201. }
  103202. }
  103203. var oldParent = sibling.parent;
  103204. var newParent;
  103205. if (this.numFreeNodes > 0) {
  103206. newParent = this.freeNodes[--this.numFreeNodes];
  103207. } else {
  103208. newParent = new OIMO.DBVTNode();
  103209. }
  103210. newParent.parent = oldParent;
  103211. newParent.child1 = leaf;
  103212. newParent.child2 = sibling;
  103213. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103214. newParent.height = sibling.height + 1;
  103215. sibling.parent = newParent;
  103216. leaf.parent = newParent;
  103217. if (sibling == this.root) {
  103218. // replace root
  103219. this.root = newParent;
  103220. } else {
  103221. // replace child
  103222. if (oldParent.child1 == sibling) {
  103223. oldParent.child1 = newParent;
  103224. } else {
  103225. oldParent.child2 = newParent;
  103226. }
  103227. }
  103228. // update whole tree
  103229. do {
  103230. newParent = this.balance(newParent);
  103231. this.fix(newParent);
  103232. newParent = newParent.parent;
  103233. } while (newParent != null);
  103234. },
  103235. getBalance: function (node) {
  103236. if (node.proxy != null) return 0;
  103237. return node.child1.height - node.child2.height;
  103238. },
  103239. /*print:function(node,indent,text){
  103240. var hasChild=node.proxy==null;
  103241. if(hasChild)text=this.print(node.child1,indent+1,text);
  103242. for(var i=indent*2;i>=0;i--){
  103243. text+=" ";
  103244. }
  103245. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103246. if(hasChild)text=this.print(node.child2,indent+1,text);
  103247. return text;
  103248. },*/
  103249. /**
  103250. * Delete a leaf from the tree.
  103251. * @param node
  103252. */
  103253. deleteLeaf: function (leaf) {
  103254. if (leaf == this.root) {
  103255. this.root = null;
  103256. return;
  103257. }
  103258. var parent = leaf.parent;
  103259. var sibling;
  103260. if (parent.child1 == leaf) {
  103261. sibling = parent.child2;
  103262. } else {
  103263. sibling = parent.child1;
  103264. }
  103265. if (parent == this.root) {
  103266. this.root = sibling;
  103267. sibling.parent = null;
  103268. return;
  103269. }
  103270. var grandParent = parent.parent;
  103271. sibling.parent = grandParent;
  103272. if (grandParent.child1 == parent) {
  103273. grandParent.child1 = sibling;
  103274. } else {
  103275. grandParent.child2 = sibling;
  103276. }
  103277. if (this.numFreeNodes < 16384) {
  103278. this.freeNodes[this.numFreeNodes++] = parent;
  103279. }
  103280. do {
  103281. grandParent = this.balance(grandParent);
  103282. this.fix(grandParent);
  103283. grandParent = grandParent.parent;
  103284. } while (grandParent != null);
  103285. },
  103286. balance: function (node) {
  103287. var nh = node.height;
  103288. if (nh < 2) {
  103289. return node;
  103290. }
  103291. var p = node.parent;
  103292. var l = node.child1;
  103293. var r = node.child2;
  103294. var lh = l.height;
  103295. var rh = r.height;
  103296. var balance = lh - rh;
  103297. var t;// for bit operation
  103298. // [ N ]
  103299. // / \
  103300. // [ L ] [ R ]
  103301. // / \ / \
  103302. // [L-L] [L-R] [R-L] [R-R]
  103303. // Is the tree balanced?
  103304. if (balance > 1) {
  103305. var ll = l.child1;
  103306. var lr = l.child2;
  103307. var llh = ll.height;
  103308. var lrh = lr.height;
  103309. // Is L-L higher than L-R?
  103310. if (llh > lrh) {
  103311. // set N to L-R
  103312. l.child2 = node;
  103313. node.parent = l;
  103314. // [ L ]
  103315. // / \
  103316. // [L-L] [ N ]
  103317. // / \ / \
  103318. // [...] [...] [ L ] [ R ]
  103319. // set L-R
  103320. node.child1 = lr;
  103321. lr.parent = node;
  103322. // [ L ]
  103323. // / \
  103324. // [L-L] [ N ]
  103325. // / \ / \
  103326. // [...] [...] [L-R] [ R ]
  103327. // fix bounds and heights
  103328. node.aabb.combine(lr.aabb, r.aabb);
  103329. t = lrh - rh;
  103330. node.height = lrh - (t & t >> 31) + 1;
  103331. l.aabb.combine(ll.aabb, node.aabb);
  103332. t = llh - nh;
  103333. l.height = llh - (t & t >> 31) + 1;
  103334. } else {
  103335. // set N to L-L
  103336. l.child1 = node;
  103337. node.parent = l;
  103338. // [ L ]
  103339. // / \
  103340. // [ N ] [L-R]
  103341. // / \ / \
  103342. // [ L ] [ R ] [...] [...]
  103343. // set L-L
  103344. node.child1 = ll;
  103345. ll.parent = node;
  103346. // [ L ]
  103347. // / \
  103348. // [ N ] [L-R]
  103349. // / \ / \
  103350. // [L-L] [ R ] [...] [...]
  103351. // fix bounds and heights
  103352. node.aabb.combine(ll.aabb, r.aabb);
  103353. t = llh - rh;
  103354. node.height = llh - (t & t >> 31) + 1;
  103355. l.aabb.combine(node.aabb, lr.aabb);
  103356. t = nh - lrh;
  103357. l.height = nh - (t & t >> 31) + 1;
  103358. }
  103359. // set new parent of L
  103360. if (p != null) {
  103361. if (p.child1 == node) {
  103362. p.child1 = l;
  103363. } else {
  103364. p.child2 = l;
  103365. }
  103366. } else {
  103367. this.root = l;
  103368. }
  103369. l.parent = p;
  103370. return l;
  103371. } else if (balance < -1) {
  103372. var rl = r.child1;
  103373. var rr = r.child2;
  103374. var rlh = rl.height;
  103375. var rrh = rr.height;
  103376. // Is R-L higher than R-R?
  103377. if (rlh > rrh) {
  103378. // set N to R-R
  103379. r.child2 = node;
  103380. node.parent = r;
  103381. // [ R ]
  103382. // / \
  103383. // [R-L] [ N ]
  103384. // / \ / \
  103385. // [...] [...] [ L ] [ R ]
  103386. // set R-R
  103387. node.child2 = rr;
  103388. rr.parent = node;
  103389. // [ R ]
  103390. // / \
  103391. // [R-L] [ N ]
  103392. // / \ / \
  103393. // [...] [...] [ L ] [R-R]
  103394. // fix bounds and heights
  103395. node.aabb.combine(l.aabb, rr.aabb);
  103396. t = lh - rrh;
  103397. node.height = lh - (t & t >> 31) + 1;
  103398. r.aabb.combine(rl.aabb, node.aabb);
  103399. t = rlh - nh;
  103400. r.height = rlh - (t & t >> 31) + 1;
  103401. } else {
  103402. // set N to R-L
  103403. r.child1 = node;
  103404. node.parent = r;
  103405. // [ R ]
  103406. // / \
  103407. // [ N ] [R-R]
  103408. // / \ / \
  103409. // [ L ] [ R ] [...] [...]
  103410. // set R-L
  103411. node.child2 = rl;
  103412. rl.parent = node;
  103413. // [ R ]
  103414. // / \
  103415. // [ N ] [R-R]
  103416. // / \ / \
  103417. // [ L ] [R-L] [...] [...]
  103418. // fix bounds and heights
  103419. node.aabb.combine(l.aabb, rl.aabb);
  103420. t = lh - rlh;
  103421. node.height = lh - (t & t >> 31) + 1;
  103422. r.aabb.combine(node.aabb, rr.aabb);
  103423. t = nh - rrh;
  103424. r.height = nh - (t & t >> 31) + 1;
  103425. }
  103426. // set new parent of R
  103427. if (p != null) {
  103428. if (p.child1 == node) {
  103429. p.child1 = r;
  103430. } else {
  103431. p.child2 = r;
  103432. }
  103433. } else {
  103434. this.root = r;
  103435. }
  103436. r.parent = p;
  103437. return r;
  103438. }
  103439. return node;
  103440. },
  103441. fix: function (node) {
  103442. var c1 = node.child1;
  103443. var c2 = node.child2;
  103444. node.aabb.combine(c1.aabb, c2.aabb);
  103445. //var h1 = c1.height;
  103446. //var h2 = c2.height;
  103447. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103448. /*if( h1 < h2 ) {
  103449. node.height = h2+1;
  103450. }else{
  103451. node.height = h1+1;
  103452. }*/
  103453. }
  103454. }
  103455. /**
  103456. * A broad-phase algorithm using dynamic bounding volume tree.
  103457. * @author saharan
  103458. * @author lo-th
  103459. */
  103460. OIMO.DBVTBroadPhase = function () {
  103461. OIMO.BroadPhase.call(this);
  103462. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103463. this.tree = new OIMO.DBVT();
  103464. this.stack = [];
  103465. this.leaves = [];
  103466. this.numLeaves = 0;
  103467. };
  103468. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103469. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103470. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103471. return new OIMO.DBVTProxy(shape);
  103472. };
  103473. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103474. this.tree.insertLeaf(proxy.leaf);
  103475. this.leaves.push(proxy.leaf);
  103476. this.numLeaves++;
  103477. };
  103478. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103479. this.tree.deleteLeaf(proxy.leaf);
  103480. var n = this.leaves.indexOf(proxy.leaf);
  103481. if (n > -1) {
  103482. this.leaves.splice(n, 1);
  103483. this.numLeaves--;
  103484. }
  103485. };
  103486. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103487. if (this.numLeaves < 2) return;
  103488. var leaf, margin = 0.1, i = this.numLeaves;
  103489. while (i--) {
  103490. leaf = this.leaves[i];
  103491. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103492. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103493. this.tree.deleteLeaf(leaf);
  103494. this.tree.insertLeaf(leaf);
  103495. this.collide(leaf, this.tree.root);
  103496. }
  103497. }
  103498. };
  103499. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103500. var stackCount = 2;
  103501. var s1, s2, n1, n2, l1, l2;
  103502. this.stack[0] = node1;
  103503. this.stack[1] = node2;
  103504. while (stackCount > 0) {
  103505. n1 = this.stack[--stackCount];
  103506. n2 = this.stack[--stackCount];
  103507. l1 = n1.proxy != null;
  103508. l2 = n2.proxy != null;
  103509. this.numPairChecks++;
  103510. if (l1 && l2) {
  103511. s1 = n1.proxy.shape;
  103512. s2 = n2.proxy.shape;
  103513. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103514. this.addPair(s1, s2);
  103515. } else {
  103516. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103517. /*if(stackCount+4>=this.maxStack){// expand the stack
  103518. //this.maxStack<<=1;
  103519. this.maxStack*=2;
  103520. var newStack = [];// vector
  103521. newStack.length = this.maxStack;
  103522. for(var i=0;i<stackCount;i++){
  103523. newStack[i] = this.stack[i];
  103524. }
  103525. this.stack = newStack;
  103526. }*/
  103527. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103528. this.stack[stackCount++] = n1.child1;
  103529. this.stack[stackCount++] = n2;
  103530. this.stack[stackCount++] = n1.child2;
  103531. this.stack[stackCount++] = n2;
  103532. } else {
  103533. this.stack[stackCount++] = n1;
  103534. this.stack[stackCount++] = n2.child1;
  103535. this.stack[stackCount++] = n1;
  103536. this.stack[stackCount++] = n2.child2;
  103537. }
  103538. }
  103539. }
  103540. };
  103541. /**
  103542. * A node of the dynamic bounding volume tree.
  103543. * @author saharan
  103544. */
  103545. OIMO.DBVTNode = function () {
  103546. // The first child node of this node.
  103547. this.child1 = null;
  103548. // The second child node of this node.
  103549. this.child2 = null;
  103550. // The parent node of this tree.
  103551. this.parent = null;
  103552. // The proxy of this node. This has no value if this node is not leaf.
  103553. this.proxy = null;
  103554. // The maximum distance from leaf nodes.
  103555. this.height = 0;
  103556. // The AABB of this node.
  103557. this.aabb = new OIMO.AABB();
  103558. };
  103559. /**
  103560. * A proxy for dynamic bounding volume tree broad-phase.
  103561. * @author saharan
  103562. */
  103563. OIMO.DBVTProxy = function (shape) {
  103564. OIMO.Proxy.call(this, shape);
  103565. // The leaf of the proxy.
  103566. this.leaf = new OIMO.DBVTNode();
  103567. this.leaf.proxy = this;
  103568. };
  103569. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103570. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103571. OIMO.DBVTProxy.prototype.update = function () {
  103572. };
  103573. OIMO.World.prototype.add = function (obj) {
  103574. obj = obj || {};
  103575. var type = obj.type || "box";
  103576. if (typeof type === 'string') type = [type];// single shape
  103577. if (type[0].substring(0, 5) == 'joint') { // is joint
  103578. if (type[0] === 'joint') type[0] = 'jointHinge';
  103579. var axe1 = obj.axe1 || [1, 0, 0];
  103580. var axe2 = obj.axe2 || [1, 0, 0];
  103581. var pos1 = obj.pos1 || [0, 0, 0];
  103582. var pos2 = obj.pos2 || [0, 0, 0];
  103583. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103584. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103585. var min, max;
  103586. if (type[0] === "jointDistance") {
  103587. min = obj.min || 0;
  103588. max = obj.max || 10;
  103589. min = min * OIMO.INV_SCALE;
  103590. max = max * OIMO.INV_SCALE;
  103591. } else {
  103592. min = obj.min || 57.29578;
  103593. max = obj.max || 0;
  103594. min = min * OIMO.degtorad;
  103595. max = max * OIMO.degtorad;
  103596. }
  103597. var limit = obj.limit || null;
  103598. var spring = obj.spring || null;
  103599. var motor = obj.motor || null;
  103600. // joint setting
  103601. var jc = new OIMO.JointConfig();
  103602. jc.allowCollision = obj.collision || false;;
  103603. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103604. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103605. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103606. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103607. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103608. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103609. jc.body1 = obj.body1;
  103610. jc.body2 = obj.body2;
  103611. var joint;
  103612. switch (type[0]) {
  103613. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103614. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103615. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103616. break;
  103617. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103618. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103619. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103620. break;
  103621. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103622. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103623. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103624. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103625. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103626. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103627. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103628. break;
  103629. }
  103630. joint.name = obj.name || '';
  103631. // finaly add to physics world
  103632. this.addJoint(joint);
  103633. return joint;
  103634. } else { // is body
  103635. // I'm dynamique or not
  103636. var move = obj.move || false;
  103637. // I can sleep or not
  103638. var noSleep = obj.noSleep || false;
  103639. // My start position
  103640. var p = obj.pos || [0, 0, 0];
  103641. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103642. // My size
  103643. var s = obj.size || [1, 1, 1];
  103644. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103645. // My rotation in degre
  103646. var rot = obj.rot || [0, 0, 0];
  103647. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103648. var r = [];
  103649. for (var i = 0; i < rot.length / 3; i++) {
  103650. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103651. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103652. }
  103653. // My physics setting
  103654. var sc = new OIMO.ShapeConfig();
  103655. if (obj.sc !== undefined) sc = obj.sc;
  103656. if (obj.config) {
  103657. // The density of the shape.
  103658. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103659. // The coefficient of friction of the shape.
  103660. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103661. // The coefficient of restitution of the shape.
  103662. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103663. // The bits of the collision groups to which the shape belongs.
  103664. sc.belongsTo = obj.config[3] || 1;
  103665. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103666. // The bits of the collision groups with which the shape collides.
  103667. sc.collidesWith = obj.config[4] || 0xffffffff;
  103668. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103669. }
  103670. // direct physics setting
  103671. if (obj.density !== undefined) sc.density = obj.density;
  103672. if (obj.friction !== undefined) sc.friction = obj.friction;
  103673. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103674. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103675. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103676. if (obj.massPos) {
  103677. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103678. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103679. }
  103680. if (obj.massRot) {
  103681. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103682. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103683. }
  103684. // My rigidbody
  103685. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103686. // My shapes
  103687. var shapes = [];
  103688. //if( typeof type === 'string' ) type = [type];// single shape
  103689. var n, n2;
  103690. for (var i = 0; i < type.length; i++) {
  103691. n = i * 3;
  103692. n2 = i * 4;
  103693. switch (type[i]) {
  103694. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103695. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103696. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103697. }
  103698. body.addShape(shapes[i]);
  103699. if (i > 0) {
  103700. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103701. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103702. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103703. }
  103704. }
  103705. // I'm static or i move
  103706. if (move) {
  103707. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103708. else body.setupMass(0x1, true);
  103709. if (noSleep) body.allowSleep = false;
  103710. else body.allowSleep = true;
  103711. } else {
  103712. body.setupMass(0x2);
  103713. }
  103714. body.name = obj.name || ' ';
  103715. // finaly add to physics world
  103716. this.addRigidBody(body);
  103717. return body;
  103718. }
  103719. }
  103720. //UMD simplified
  103721. var root = this;
  103722. if (!root['OIMO']) {
  103723. if (true)
  103724. module.exports = OIMO;
  103725. else if (typeof define === 'function' && define.amd)
  103726. define([], function () {
  103727. return OIMO;
  103728. });
  103729. else if (typeof exports === 'object')
  103730. exports["OIMO"] = OIMO;
  103731. else {
  103732. root["OIMO"] = OIMO;
  103733. }
  103734. }
  103735. /***/ }),
  103736. /* 19 */
  103737. /***/ (function(module, exports, __webpack_require__) {
  103738. "use strict";
  103739. Object.defineProperty(exports, "__esModule", { value: true });
  103740. var babylonjs_1 = __webpack_require__(0);
  103741. var helper_1 = __webpack_require__(2);
  103742. var TemplateManager = (function () {
  103743. function TemplateManager(containerElement) {
  103744. this.containerElement = containerElement;
  103745. this.templates = {};
  103746. this.onInit = new babylonjs_1.Observable();
  103747. this.onLoaded = new babylonjs_1.Observable();
  103748. this.onStateChange = new babylonjs_1.Observable();
  103749. this.onAllLoaded = new babylonjs_1.Observable();
  103750. this.onEventTriggered = new babylonjs_1.Observable();
  103751. this.eventManager = new eventManager_1.EventManager(this);
  103752. }
  103753. TemplateManager.prototype.initTemplate = function (templates) {
  103754. var _this = this;
  103755. var internalInit = function (dependencyMap, name, parentTemplate) {
  103756. var template = _this.templates[name];
  103757. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103758. return internalInit(dependencyMap[childName], childName, template);
  103759. });
  103760. var addToParent = function () {
  103761. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103762. template.appendTo(containingElement);
  103763. _this.checkLoadedState();
  103764. };
  103765. if (parentTemplate && !parentTemplate.parent) {
  103766. parentTemplate.onAppended.add(function () {
  103767. addToParent();
  103768. });
  103769. }
  103770. else {
  103771. addToParent();
  103772. }
  103773. return template;
  103774. };
  103775. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103776. if (_this.templates['main']) {
  103777. internalInit(htmlTree, 'main');
  103778. }
  103779. else {
  103780. _this.checkLoadedState();
  103781. }
  103782. return;
  103783. });
  103784. };
  103785. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103786. var _this = this;
  103787. var promises = Object.keys(templates).map(function (name) {
  103788. if (!templates[name])
  103789. return Promise.resolve(false);
  103790. var template = new Template(name, templates[name]);
  103791. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103792. _this.templates[name] = template;
  103793. return template.initPromise;
  103794. });
  103795. return Promise.all(promises).then(function () {
  103796. var templateStructure = {};
  103797. var buildTree = function (parentObject, name) {
  103798. _this.templates[name].isInHtmlTree = true;
  103799. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103800. childNodes.forEach(function (element) {
  103801. parentObject[element] = {};
  103802. buildTree(parentObject[element], element);
  103803. });
  103804. };
  103805. if (_this.templates['main']) {
  103806. buildTree(templateStructure, "main");
  103807. }
  103808. return templateStructure;
  103809. });
  103810. };
  103811. TemplateManager.prototype.getCanvas = function () {
  103812. return this.containerElement.querySelector('canvas');
  103813. };
  103814. TemplateManager.prototype.getTemplate = function (name) {
  103815. return this.templates[name];
  103816. };
  103817. TemplateManager.prototype.checkLoadedState = function () {
  103818. var _this = this;
  103819. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103820. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103821. });
  103822. if (done) {
  103823. this.onAllLoaded.notifyObservers(this);
  103824. }
  103825. };
  103826. TemplateManager.prototype.dispose = function () {
  103827. var _this = this;
  103828. Object.keys(this.templates).forEach(function (template) {
  103829. _this.templates[template].dispose();
  103830. });
  103831. this.onInit.clear();
  103832. this.onAllLoaded.clear();
  103833. this.onEventTriggered.clear();
  103834. this.onLoaded.clear();
  103835. this.onStateChange.clear();
  103836. };
  103837. return TemplateManager;
  103838. }());
  103839. exports.TemplateManager = TemplateManager;
  103840. var Handlebars = __webpack_require__(20);
  103841. var eventManager_1 = __webpack_require__(21);
  103842. Handlebars.registerHelper('eachInMap', function (map, block) {
  103843. var out = '';
  103844. Object.keys(map).map(function (prop) {
  103845. var data = map[prop];
  103846. if (typeof data === 'object') {
  103847. data.id = data.id || prop;
  103848. out += block.fn(data);
  103849. }
  103850. else {
  103851. out += block.fn({ id: prop, value: data });
  103852. }
  103853. });
  103854. return out;
  103855. });
  103856. var Template = (function () {
  103857. function Template(name, _configuration) {
  103858. var _this = this;
  103859. this.name = name;
  103860. this._configuration = _configuration;
  103861. this.onInit = new babylonjs_1.Observable();
  103862. this.onLoaded = new babylonjs_1.Observable();
  103863. this.onAppended = new babylonjs_1.Observable();
  103864. this.onStateChange = new babylonjs_1.Observable();
  103865. this.onEventTriggered = new babylonjs_1.Observable();
  103866. this.loadRequests = [];
  103867. this.isLoaded = false;
  103868. this.isShown = false;
  103869. this.isInHtmlTree = false;
  103870. this.onInit.notifyObservers(this);
  103871. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103872. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103873. if (htmlTemplate) {
  103874. _this.htmlTemplate = htmlTemplate;
  103875. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103876. var config = _this._configuration.params || {};
  103877. var rawHtml = compiledTemplate(config);
  103878. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103879. _this.isLoaded = true;
  103880. _this.isShown = true;
  103881. _this.onLoaded.notifyObservers(_this);
  103882. }
  103883. return _this;
  103884. });
  103885. }
  103886. Template.prototype.updateParams = function (params) {
  103887. this._configuration.params = params;
  103888. if (this.isLoaded) {
  103889. this.dispose();
  103890. }
  103891. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103892. var config = this._configuration.params || {};
  103893. var rawHtml = compiledTemplate(config);
  103894. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103895. if (this.parent) {
  103896. this.appendTo(this.parent, true);
  103897. }
  103898. };
  103899. Object.defineProperty(Template.prototype, "configuration", {
  103900. get: function () {
  103901. return this._configuration;
  103902. },
  103903. enumerable: true,
  103904. configurable: true
  103905. });
  103906. Template.prototype.getChildElements = function () {
  103907. var childrenArray = [];
  103908. var children = this.fragment.children;
  103909. if (!children) {
  103910. children = this.fragment.querySelectorAll('*');
  103911. }
  103912. for (var i = 0; i < children.length; ++i) {
  103913. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103914. }
  103915. return childrenArray;
  103916. };
  103917. Template.prototype.appendTo = function (parent, forceRemove) {
  103918. var _this = this;
  103919. if (this.parent) {
  103920. if (forceRemove) {
  103921. this.parent.removeChild(this.fragment);
  103922. }
  103923. else {
  103924. return;
  103925. }
  103926. }
  103927. this.parent = parent;
  103928. if (this._configuration.id) {
  103929. this.parent.id = this._configuration.id;
  103930. }
  103931. this.fragment = this.parent.appendChild(this.fragment);
  103932. setTimeout(function () {
  103933. _this.registerEvents();
  103934. _this.onAppended.notifyObservers(_this);
  103935. });
  103936. };
  103937. Template.prototype.show = function (visibilityFunction) {
  103938. var _this = this;
  103939. if (this.isHiding)
  103940. return Promise.resolve(this);
  103941. return Promise.resolve().then(function () {
  103942. _this.isShowing = true;
  103943. if (visibilityFunction) {
  103944. return visibilityFunction(_this);
  103945. }
  103946. else {
  103947. _this.parent.style.display = 'flex';
  103948. return _this;
  103949. }
  103950. }).then(function () {
  103951. _this.isShown = true;
  103952. _this.isShowing = false;
  103953. _this.onStateChange.notifyObservers(_this);
  103954. return _this;
  103955. });
  103956. };
  103957. Template.prototype.hide = function (visibilityFunction) {
  103958. var _this = this;
  103959. if (this.isShowing)
  103960. return Promise.resolve(this);
  103961. return Promise.resolve().then(function () {
  103962. _this.isHiding = true;
  103963. if (visibilityFunction) {
  103964. return visibilityFunction(_this);
  103965. }
  103966. else {
  103967. _this.parent.style.display = 'hide';
  103968. return _this;
  103969. }
  103970. }).then(function () {
  103971. _this.isShown = false;
  103972. _this.isHiding = false;
  103973. _this.onStateChange.notifyObservers(_this);
  103974. return _this;
  103975. });
  103976. };
  103977. Template.prototype.dispose = function () {
  103978. this.onAppended.clear();
  103979. this.onEventTriggered.clear();
  103980. this.onInit.clear();
  103981. this.onLoaded.clear();
  103982. this.onStateChange.clear();
  103983. this.isLoaded = false;
  103984. this.parent.removeChild(this.fragment);
  103985. this.loadRequests.forEach(function (request) {
  103986. request.abort();
  103987. });
  103988. };
  103989. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  103990. var _this = this;
  103991. if (!templateConfig) {
  103992. return Promise.reject('No templateConfig provided');
  103993. }
  103994. else if (templateConfig.html !== undefined) {
  103995. return Promise.resolve(templateConfig.html);
  103996. }
  103997. else {
  103998. var location_1 = getTemplateLocation(templateConfig);
  103999. if (helper_1.isUrl(location_1)) {
  104000. return new Promise(function (resolve, reject) {
  104001. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  104002. resolve(data);
  104003. }, undefined, undefined, false, function (request, error) {
  104004. reject(error);
  104005. });
  104006. _this.loadRequests.push(fileRequest);
  104007. });
  104008. }
  104009. else {
  104010. location_1 = location_1.replace('#', '');
  104011. var element = document.getElementById(location_1);
  104012. if (element) {
  104013. return Promise.resolve(element.innerHTML);
  104014. }
  104015. else {
  104016. return Promise.reject('Template ID not found');
  104017. }
  104018. }
  104019. }
  104020. };
  104021. Template.prototype.registerEvents = function () {
  104022. var _this = this;
  104023. this.registeredEvents = this.registeredEvents || [];
  104024. if (this.registeredEvents.length) {
  104025. this.registeredEvents.forEach(function (evt) {
  104026. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  104027. });
  104028. }
  104029. if (this._configuration.events) {
  104030. var _loop_1 = function (eventName) {
  104031. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  104032. var functionToFire_1 = function (selector, event) {
  104033. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  104034. };
  104035. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  104036. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  104037. }
  104038. else if (typeof this_1._configuration.events[eventName] === 'object') {
  104039. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  104040. var event_1 = this_1._configuration.events[eventName] || {};
  104041. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  104042. if (selector && selector.indexOf('#') !== 0) {
  104043. selector = '#' + selector;
  104044. }
  104045. var htmlElement = _this.parent.querySelector(selector);
  104046. if (htmlElement) {
  104047. var binding = functionToFire_1.bind(_this, selector);
  104048. htmlElement.addEventListener(eventName, binding, false);
  104049. _this.registeredEvents.push({
  104050. htmlElement: htmlElement,
  104051. eventName: eventName,
  104052. function: binding
  104053. });
  104054. }
  104055. });
  104056. }
  104057. }
  104058. };
  104059. var this_1 = this;
  104060. for (var eventName in this._configuration.events) {
  104061. _loop_1(eventName);
  104062. }
  104063. }
  104064. };
  104065. return Template;
  104066. }());
  104067. exports.Template = Template;
  104068. function getTemplateLocation(templateConfig) {
  104069. if (!templateConfig || typeof templateConfig === 'string') {
  104070. return templateConfig;
  104071. }
  104072. else {
  104073. return templateConfig.location;
  104074. }
  104075. }
  104076. exports.getTemplateLocation = getTemplateLocation;
  104077. /***/ }),
  104078. /* 20 */
  104079. /***/ (function(module, exports, __webpack_require__) {
  104080. /**!
  104081. @license
  104082. handlebars v4.0.11
  104083. Copyright (C) 2011-2017 by Yehuda Katz
  104084. Permission is hereby granted, free of charge, to any person obtaining a copy
  104085. of this software and associated documentation files (the "Software"), to deal
  104086. in the Software without restriction, including without limitation the rights
  104087. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104088. copies of the Software, and to permit persons to whom the Software is
  104089. furnished to do so, subject to the following conditions:
  104090. The above copyright notice and this permission notice shall be included in
  104091. all copies or substantial portions of the Software.
  104092. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104093. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104094. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104095. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104096. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104097. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104098. THE SOFTWARE.
  104099. */
  104100. !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],
  104101. 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){
  104102. 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"]}])});
  104103. /***/ }),
  104104. /* 21 */
  104105. /***/ (function(module, exports, __webpack_require__) {
  104106. "use strict";
  104107. Object.defineProperty(exports, "__esModule", { value: true });
  104108. var EventManager = (function () {
  104109. function EventManager(templateManager) {
  104110. var _this = this;
  104111. this.templateManager = templateManager;
  104112. this.callbacksContainer = {};
  104113. this.templateManager.onEventTriggered.add(function (eventData) {
  104114. _this.eventTriggered(eventData);
  104115. });
  104116. }
  104117. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104118. if (!this.callbacksContainer[templateName]) {
  104119. this.callbacksContainer[templateName] = [];
  104120. }
  104121. this.callbacksContainer[templateName].push({
  104122. eventType: eventType,
  104123. callback: callback
  104124. });
  104125. };
  104126. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104127. var callbackDefs = this.callbacksContainer[templateName] || [];
  104128. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104129. };
  104130. EventManager.prototype.eventTriggered = function (data) {
  104131. var templateName = data.template.name;
  104132. var eventType = data.event.type;
  104133. var selector = data.selector;
  104134. var callbackDefs = this.callbacksContainer[templateName] || [];
  104135. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104136. callbackDef.callback(data);
  104137. });
  104138. };
  104139. return EventManager;
  104140. }());
  104141. exports.EventManager = EventManager;
  104142. /***/ }),
  104143. /* 22 */
  104144. /***/ (function(module, exports, __webpack_require__) {
  104145. "use strict";
  104146. Object.defineProperty(exports, "__esModule", { value: true });
  104147. var mappers_1 = __webpack_require__(1);
  104148. var types_1 = __webpack_require__(23);
  104149. var deepmerge = __webpack_require__(13);
  104150. var babylonjs_1 = __webpack_require__(0);
  104151. var ConfigurationLoader = (function () {
  104152. function ConfigurationLoader() {
  104153. this.configurationCache = {};
  104154. this.loadRequests = [];
  104155. }
  104156. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104157. var _this = this;
  104158. if (initConfig === void 0) { initConfig = {}; }
  104159. var loadedConfig = deepmerge({}, initConfig);
  104160. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104161. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104162. if (loadedConfig.configuration) {
  104163. var mapperType_1 = "json";
  104164. return Promise.resolve().then(function () {
  104165. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104166. var url = '';
  104167. if (typeof loadedConfig.configuration === "string") {
  104168. url = loadedConfig.configuration;
  104169. }
  104170. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104171. url = loadedConfig.configuration.url;
  104172. var type = loadedConfig.configuration.mapper;
  104173. if (!type) {
  104174. type = loadedConfig.configuration.url.split('.').pop();
  104175. }
  104176. mapperType_1 = type || mapperType_1;
  104177. }
  104178. return _this.loadFile(url);
  104179. }
  104180. else {
  104181. if (typeof loadedConfig.configuration === "object") {
  104182. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104183. return loadedConfig.configuration.payload || {};
  104184. }
  104185. return {};
  104186. }
  104187. }).then(function (data) {
  104188. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104189. var parsed = mapper.map(data);
  104190. var merged = deepmerge(loadedConfig, parsed);
  104191. if (callback)
  104192. callback(merged);
  104193. return merged;
  104194. });
  104195. }
  104196. else {
  104197. if (callback)
  104198. callback(loadedConfig);
  104199. return Promise.resolve(loadedConfig);
  104200. }
  104201. };
  104202. ConfigurationLoader.prototype.dispose = function () {
  104203. this.loadRequests.forEach(function (request) {
  104204. request.abort();
  104205. });
  104206. };
  104207. ConfigurationLoader.prototype.loadFile = function (url) {
  104208. var _this = this;
  104209. var cacheReference = this.configurationCache;
  104210. if (cacheReference[url]) {
  104211. return Promise.resolve(cacheReference[url]);
  104212. }
  104213. return new Promise(function (resolve, reject) {
  104214. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104215. reject(error);
  104216. });
  104217. _this.loadRequests.push(fileRequest);
  104218. });
  104219. };
  104220. return ConfigurationLoader;
  104221. }());
  104222. exports.ConfigurationLoader = ConfigurationLoader;
  104223. exports.configurationLoader = new ConfigurationLoader();
  104224. exports.default = exports.configurationLoader;
  104225. /***/ }),
  104226. /* 23 */
  104227. /***/ (function(module, exports, __webpack_require__) {
  104228. "use strict";
  104229. Object.defineProperty(exports, "__esModule", { value: true });
  104230. var minimal_1 = __webpack_require__(24);
  104231. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104232. var default_1 = __webpack_require__(25);
  104233. exports.defaultConfiguration = default_1.defaultConfiguration;
  104234. var getConfigurationType = function (type) {
  104235. switch (type) {
  104236. case 'default':
  104237. return default_1.defaultConfiguration;
  104238. case 'minimal':
  104239. return minimal_1.minimalConfiguration;
  104240. case 'none':
  104241. return {};
  104242. default:
  104243. return default_1.defaultConfiguration;
  104244. }
  104245. };
  104246. exports.getConfigurationType = getConfigurationType;
  104247. /***/ }),
  104248. /* 24 */
  104249. /***/ (function(module, exports, __webpack_require__) {
  104250. "use strict";
  104251. Object.defineProperty(exports, "__esModule", { value: true });
  104252. exports.minimalConfiguration = {
  104253. version: "0.1",
  104254. templates: {
  104255. main: {
  104256. html: __webpack_require__(6)
  104257. },
  104258. loadingScreen: {
  104259. html: __webpack_require__(7),
  104260. params: {
  104261. backgroundColor: "#000000",
  104262. loadingImage: __webpack_require__(8)
  104263. }
  104264. },
  104265. viewer: {
  104266. html: __webpack_require__(9),
  104267. },
  104268. overlay: {
  104269. html: __webpack_require__(10),
  104270. params: {
  104271. closeImage: __webpack_require__(11),
  104272. closeText: 'Close'
  104273. }
  104274. },
  104275. error: {
  104276. html: __webpack_require__(12)
  104277. }
  104278. },
  104279. engine: {
  104280. antialiasing: true
  104281. }
  104282. };
  104283. /***/ }),
  104284. /* 25 */
  104285. /***/ (function(module, exports, __webpack_require__) {
  104286. "use strict";
  104287. Object.defineProperty(exports, "__esModule", { value: true });
  104288. exports.defaultConfiguration = {
  104289. version: "3.2.0-alpha4",
  104290. templates: {
  104291. main: {
  104292. html: __webpack_require__(6)
  104293. },
  104294. loadingScreen: {
  104295. html: __webpack_require__(7),
  104296. params: {
  104297. backgroundColor: "#000000",
  104298. loadingImage: __webpack_require__(8)
  104299. }
  104300. },
  104301. viewer: {
  104302. html: __webpack_require__(9),
  104303. events: {
  104304. pointerout: true,
  104305. pointerdown: true,
  104306. pointerup: true
  104307. }
  104308. },
  104309. navBar: {
  104310. html: __webpack_require__(26),
  104311. params: {
  104312. buttons: {
  104313. "fullscreen-button": {
  104314. altText: "Fullscreen",
  104315. image: __webpack_require__(27)
  104316. }
  104317. },
  104318. visibilityTimeout: 2000
  104319. },
  104320. events: {
  104321. pointerdown: { 'fullscreen-button': true },
  104322. pointerover: true
  104323. }
  104324. },
  104325. overlay: {
  104326. html: __webpack_require__(10),
  104327. params: {
  104328. closeImage: __webpack_require__(11),
  104329. closeText: 'Close'
  104330. }
  104331. },
  104332. help: {
  104333. html: __webpack_require__(28)
  104334. },
  104335. share: {
  104336. html: __webpack_require__(29)
  104337. },
  104338. error: {
  104339. html: __webpack_require__(12)
  104340. }
  104341. },
  104342. camera: {
  104343. behaviors: {
  104344. autoRotate: 0,
  104345. framing: {
  104346. type: 2,
  104347. zoomOnBoundingInfo: true,
  104348. zoomStopsAnimation: false
  104349. }
  104350. }
  104351. },
  104352. skybox: {
  104353. pbr: true,
  104354. blur: 0.7,
  104355. infiniteDIstance: false,
  104356. },
  104357. ground: true,
  104358. engine: {
  104359. antialiasing: true
  104360. },
  104361. scene: {
  104362. imageProcessingConfiguration: {
  104363. exposure: 1.4,
  104364. contrast: 1.66,
  104365. toneMappingEnabled: true
  104366. }
  104367. }
  104368. };
  104369. /***/ }),
  104370. /* 26 */
  104371. /***/ (function(module, exports) {
  104372. 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>";
  104373. /***/ }),
  104374. /* 27 */
  104375. /***/ (function(module, exports) {
  104376. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104377. /***/ }),
  104378. /* 28 */
  104379. /***/ (function(module, exports) {
  104380. module.exports = "HELP";
  104381. /***/ }),
  104382. /* 29 */
  104383. /***/ (function(module, exports) {
  104384. module.exports = "SHARE";
  104385. /***/ }),
  104386. /* 30 */
  104387. /***/ (function(module, exports, __webpack_require__) {
  104388. "use strict";
  104389. Object.defineProperty(exports, "__esModule", { value: true });
  104390. var babylonjs_1 = __webpack_require__(0);
  104391. var modelAnimation_1 = __webpack_require__(31);
  104392. var ViewerModel = (function () {
  104393. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104394. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104395. this._modelConfiguration = _modelConfiguration;
  104396. this._scene = _scene;
  104397. this.onLoadedObservable = new babylonjs_1.Observable();
  104398. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104399. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104400. this._animations = [];
  104401. if (!disableAutoLoad) {
  104402. this._initLoad();
  104403. }
  104404. }
  104405. ViewerModel.prototype.load = function () {
  104406. if (this.loader) {
  104407. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104408. }
  104409. else {
  104410. this._initLoad();
  104411. }
  104412. };
  104413. ViewerModel.prototype.getAnimationNames = function () {
  104414. return this._animations.map(function (a) { return a.name; });
  104415. };
  104416. ViewerModel.prototype._getAnimationByName = function (name) {
  104417. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104418. if (filtered.length === 1) {
  104419. return filtered[0];
  104420. }
  104421. else {
  104422. return null;
  104423. }
  104424. };
  104425. ViewerModel.prototype.playAnimation = function (name) {
  104426. var animation = this._getAnimationByName(name);
  104427. if (animation) {
  104428. if (this.currentAnimation) {
  104429. this.currentAnimation.stop();
  104430. }
  104431. this.currentAnimation = animation;
  104432. animation.start();
  104433. return animation;
  104434. }
  104435. else {
  104436. throw new Error("animation not found - " + name);
  104437. }
  104438. };
  104439. ViewerModel.prototype._initLoad = function () {
  104440. var _this = this;
  104441. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104442. return babylonjs_1.Tools.Error("No model URL to load.");
  104443. }
  104444. var parts = this._modelConfiguration.url.split('/');
  104445. var filename = parts.pop() || this._modelConfiguration.url;
  104446. var base = parts.length ? parts.join('/') + '/' : './';
  104447. var plugin = this._modelConfiguration.loader;
  104448. var animationsArray = this._scene.animationGroups.slice();
  104449. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104450. meshes.forEach(function (mesh) {
  104451. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104452. });
  104453. _this.meshes = meshes;
  104454. _this.particleSystems = particleSystems;
  104455. _this.skeletons = skeletons;
  104456. if (_this.loader.name === 'gltf') {
  104457. _this._scene.animationGroups.forEach(function (ag) {
  104458. if (animationsArray.indexOf(ag) === -1) {
  104459. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104460. }
  104461. });
  104462. }
  104463. else {
  104464. skeletons.forEach(function (skeleton, idx) {
  104465. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104466. skeleton.getAnimatables().forEach(function (a) {
  104467. if (a.animations[0]) {
  104468. ag.addTargetedAnimation(a.animations[0], a);
  104469. }
  104470. });
  104471. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104472. });
  104473. }
  104474. if (_this._modelConfiguration.animation) {
  104475. if (_this._modelConfiguration.animation.playOnce) {
  104476. _this._animations.forEach(function (a) {
  104477. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104478. });
  104479. }
  104480. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104481. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104482. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104483. _this.playAnimation(animationName);
  104484. }
  104485. }
  104486. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104487. }, function (progressEvent) {
  104488. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104489. }, function (e, m, exception) {
  104490. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104491. }, plugin);
  104492. this.loader['animationStartMode'] = 0;
  104493. };
  104494. ViewerModel.prototype.dispose = function () {
  104495. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104496. this.skeletons.forEach(function (s) { return s.dispose(); });
  104497. this._animations.forEach(function (ag) { return ag.dispose(); });
  104498. this.meshes.forEach(function (m) { return m.dispose(); });
  104499. };
  104500. return ViewerModel;
  104501. }());
  104502. exports.ViewerModel = ViewerModel;
  104503. /***/ }),
  104504. /* 31 */
  104505. /***/ (function(module, exports, __webpack_require__) {
  104506. "use strict";
  104507. Object.defineProperty(exports, "__esModule", { value: true });
  104508. var AnimationPlayMode;
  104509. (function (AnimationPlayMode) {
  104510. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104511. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104512. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104513. var AnimationState;
  104514. (function (AnimationState) {
  104515. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104516. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104517. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104518. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104519. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104520. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104521. var GroupModelAnimation = (function () {
  104522. function GroupModelAnimation(_animationGroup) {
  104523. var _this = this;
  104524. this._animationGroup = _animationGroup;
  104525. this._state = AnimationState.INIT;
  104526. this._playMode = AnimationPlayMode.LOOP;
  104527. this._animationGroup.onAnimationEndObservable.add(function () {
  104528. _this.stop();
  104529. _this._state = AnimationState.ENDED;
  104530. });
  104531. }
  104532. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104533. get: function () {
  104534. return this._animationGroup.name;
  104535. },
  104536. enumerable: true,
  104537. configurable: true
  104538. });
  104539. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104540. get: function () {
  104541. return this._state;
  104542. },
  104543. enumerable: true,
  104544. configurable: true
  104545. });
  104546. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104547. get: function () {
  104548. return this._animationGroup.speedRatio;
  104549. },
  104550. set: function (value) {
  104551. this._animationGroup.speedRatio = value;
  104552. },
  104553. enumerable: true,
  104554. configurable: true
  104555. });
  104556. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104557. get: function () {
  104558. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104559. var keys = ta.animation.getKeys();
  104560. return keys[keys.length - 1].frame;
  104561. });
  104562. return Math.max.apply(null, animationFrames);
  104563. },
  104564. enumerable: true,
  104565. configurable: true
  104566. });
  104567. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104568. get: function () {
  104569. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104570. var animatable = this._animationGroup.animatables[i];
  104571. var animations = animatable.getAnimations();
  104572. if (!animations || !animations.length) {
  104573. continue;
  104574. }
  104575. for (var idx = 0; idx < animations.length; ++idx) {
  104576. if (animations[idx].currentFrame) {
  104577. return animations[idx].currentFrame;
  104578. }
  104579. }
  104580. }
  104581. return 0;
  104582. },
  104583. enumerable: true,
  104584. configurable: true
  104585. });
  104586. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104587. get: function () {
  104588. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104589. var animatable = this._animationGroup.animatables[i];
  104590. var animations = animatable.getAnimations();
  104591. if (!animations || !animations.length) {
  104592. continue;
  104593. }
  104594. for (var idx = 0; idx < animations.length; ++idx) {
  104595. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104596. return animations[idx].animation.framePerSecond;
  104597. }
  104598. }
  104599. }
  104600. return 0;
  104601. },
  104602. enumerable: true,
  104603. configurable: true
  104604. });
  104605. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104606. get: function () {
  104607. return this._playMode;
  104608. },
  104609. set: function (value) {
  104610. if (value === this._playMode) {
  104611. return;
  104612. }
  104613. this._playMode = value;
  104614. if (this.state === AnimationState.PLAYING) {
  104615. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104616. }
  104617. else {
  104618. this._animationGroup.reset();
  104619. this._state = AnimationState.INIT;
  104620. }
  104621. },
  104622. enumerable: true,
  104623. configurable: true
  104624. });
  104625. GroupModelAnimation.prototype.reset = function () {
  104626. this._animationGroup.reset();
  104627. };
  104628. GroupModelAnimation.prototype.restart = function () {
  104629. this._animationGroup.restart();
  104630. };
  104631. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104632. this._animationGroup['_animatables'].forEach(function (a) {
  104633. a.goToFrame(frameNumber);
  104634. });
  104635. };
  104636. GroupModelAnimation.prototype.start = function () {
  104637. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104638. if (this._animationGroup.isStarted) {
  104639. this._state = AnimationState.PLAYING;
  104640. }
  104641. };
  104642. GroupModelAnimation.prototype.pause = function () {
  104643. this._animationGroup.pause();
  104644. this._state = AnimationState.PAUSED;
  104645. };
  104646. GroupModelAnimation.prototype.stop = function () {
  104647. this._animationGroup.stop();
  104648. if (!this._animationGroup.isStarted) {
  104649. this._state = AnimationState.STOPPED;
  104650. }
  104651. };
  104652. GroupModelAnimation.prototype.dispose = function () {
  104653. this._animationGroup.dispose();
  104654. };
  104655. return GroupModelAnimation;
  104656. }());
  104657. exports.GroupModelAnimation = GroupModelAnimation;
  104658. /***/ }),
  104659. /* 32 */
  104660. /***/ (function(module, exports, __webpack_require__) {
  104661. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  104662. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  104663. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  104664. 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;
  104665. return c > 3 && r && Object.defineProperty(target, key, r), r;
  104666. };
  104667. var __extends = (this && this.__extends) || (function () {
  104668. var extendStatics = Object.setPrototypeOf ||
  104669. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104670. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104671. return function (d, b) {
  104672. extendStatics(d, b);
  104673. function __() { this.constructor = d; }
  104674. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104675. };
  104676. })();
  104677. (function universalModuleDefinition(root, factory) {
  104678. if(true)
  104679. module.exports = factory(__webpack_require__(0));
  104680. else if(typeof define === 'function' && define.amd)
  104681. define("babylonjs-loaders", ["babylonjs"], factory);
  104682. else if(typeof exports === 'object')
  104683. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  104684. else {
  104685. root["BABYLON"] = factory(root["BABYLON"]);
  104686. }
  104687. })(this, function(BABYLON) {
  104688. var BABYLON;
  104689. (function (BABYLON) {
  104690. var STLFileLoader = /** @class */ (function () {
  104691. function STLFileLoader() {
  104692. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104693. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104694. 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;
  104695. 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;
  104696. this.name = "stl";
  104697. // force data to come in as an ArrayBuffer
  104698. // we'll convert to string if it looks like it's an ASCII .stl
  104699. this.extensions = {
  104700. ".stl": { isBinary: true },
  104701. };
  104702. }
  104703. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104704. var matches;
  104705. if (this.isBinary(data)) {
  104706. // binary .stl
  104707. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104708. this.parseBinary(babylonMesh, data);
  104709. if (meshes) {
  104710. meshes.push(babylonMesh);
  104711. }
  104712. return true;
  104713. }
  104714. // ASCII .stl
  104715. // convert to string
  104716. var array_buffer = new Uint8Array(data);
  104717. var str = '';
  104718. for (var i = 0; i < data.byteLength; i++) {
  104719. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104720. }
  104721. data = str;
  104722. while (matches = this.solidPattern.exec(data)) {
  104723. var meshName = matches[1];
  104724. var meshNameFromEnd = matches[3];
  104725. if (meshName != meshNameFromEnd) {
  104726. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104727. return false;
  104728. }
  104729. // check meshesNames
  104730. if (meshesNames && meshName) {
  104731. if (meshesNames instanceof Array) {
  104732. if (!meshesNames.indexOf(meshName)) {
  104733. continue;
  104734. }
  104735. }
  104736. else {
  104737. if (meshName !== meshesNames) {
  104738. continue;
  104739. }
  104740. }
  104741. }
  104742. // stl mesh name can be empty as well
  104743. meshName = meshName || "stlmesh";
  104744. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104745. this.parseASCII(babylonMesh, matches[2]);
  104746. if (meshes) {
  104747. meshes.push(babylonMesh);
  104748. }
  104749. }
  104750. return true;
  104751. };
  104752. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104753. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104754. if (result) {
  104755. scene.createDefaultCameraOrLight();
  104756. }
  104757. return result;
  104758. };
  104759. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104760. var container = new BABYLON.AssetContainer(scene);
  104761. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104762. container.removeAllFromScene();
  104763. return container;
  104764. };
  104765. STLFileLoader.prototype.isBinary = function (data) {
  104766. // check if file size is correct for binary stl
  104767. var faceSize, nFaces, reader;
  104768. reader = new DataView(data);
  104769. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104770. nFaces = reader.getUint32(80, true);
  104771. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104772. return true;
  104773. }
  104774. // check characters higher than ASCII to confirm binary
  104775. var fileLength = reader.byteLength;
  104776. for (var index = 0; index < fileLength; index++) {
  104777. if (reader.getUint8(index) > 127) {
  104778. return true;
  104779. }
  104780. }
  104781. return false;
  104782. };
  104783. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104784. var reader = new DataView(data);
  104785. var faces = reader.getUint32(80, true);
  104786. var dataOffset = 84;
  104787. var faceLength = 12 * 4 + 2;
  104788. var offset = 0;
  104789. var positions = new Float32Array(faces * 3 * 3);
  104790. var normals = new Float32Array(faces * 3 * 3);
  104791. var indices = new Uint32Array(faces * 3);
  104792. var indicesCount = 0;
  104793. for (var face = 0; face < faces; face++) {
  104794. var start = dataOffset + face * faceLength;
  104795. var normalX = reader.getFloat32(start, true);
  104796. var normalY = reader.getFloat32(start + 4, true);
  104797. var normalZ = reader.getFloat32(start + 8, true);
  104798. for (var i = 1; i <= 3; i++) {
  104799. var vertexstart = start + i * 12;
  104800. // ordering is intentional to match ascii import
  104801. positions[offset] = reader.getFloat32(vertexstart, true);
  104802. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104803. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104804. normals[offset] = normalX;
  104805. normals[offset + 2] = normalY;
  104806. normals[offset + 1] = normalZ;
  104807. offset += 3;
  104808. }
  104809. indices[indicesCount] = indicesCount++;
  104810. indices[indicesCount] = indicesCount++;
  104811. indices[indicesCount] = indicesCount++;
  104812. }
  104813. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104814. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104815. mesh.setIndices(indices);
  104816. mesh.computeWorldMatrix(true);
  104817. };
  104818. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104819. var positions = [];
  104820. var normals = [];
  104821. var indices = [];
  104822. var indicesCount = 0;
  104823. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104824. var matches;
  104825. while (matches = this.facetsPattern.exec(solidData)) {
  104826. var facet = matches[1];
  104827. //one normal per face
  104828. var normalMatches = this.normalPattern.exec(facet);
  104829. this.normalPattern.lastIndex = 0;
  104830. if (!normalMatches) {
  104831. continue;
  104832. }
  104833. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104834. var vertexMatch;
  104835. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104836. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104837. normals.push(normal[0], normal[1], normal[2]);
  104838. }
  104839. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104840. this.vertexPattern.lastIndex = 0;
  104841. }
  104842. this.facetsPattern.lastIndex = 0;
  104843. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104844. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104845. mesh.setIndices(indices);
  104846. mesh.computeWorldMatrix(true);
  104847. };
  104848. return STLFileLoader;
  104849. }());
  104850. BABYLON.STLFileLoader = STLFileLoader;
  104851. if (BABYLON.SceneLoader) {
  104852. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104853. }
  104854. })(BABYLON || (BABYLON = {}));
  104855. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104856. var BABYLON;
  104857. (function (BABYLON) {
  104858. /**
  104859. * Class reading and parsing the MTL file bundled with the obj file.
  104860. */
  104861. var MTLFileLoader = /** @class */ (function () {
  104862. function MTLFileLoader() {
  104863. // All material loaded from the mtl will be set here
  104864. this.materials = [];
  104865. }
  104866. /**
  104867. * This function will read the mtl file and create each material described inside
  104868. * This function could be improve by adding :
  104869. * -some component missing (Ni, Tf...)
  104870. * -including the specific options available
  104871. *
  104872. * @param scene
  104873. * @param data
  104874. * @param rootUrl
  104875. */
  104876. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104877. //Split the lines from the file
  104878. var lines = data.split('\n');
  104879. //Space char
  104880. var delimiter_pattern = /\s+/;
  104881. //Array with RGB colors
  104882. var color;
  104883. //New material
  104884. var material = null;
  104885. //Look at each line
  104886. for (var i = 0; i < lines.length; i++) {
  104887. var line = lines[i].trim();
  104888. // Blank line or comment
  104889. if (line.length === 0 || line.charAt(0) === '#') {
  104890. continue;
  104891. }
  104892. //Get the first parameter (keyword)
  104893. var pos = line.indexOf(' ');
  104894. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104895. key = key.toLowerCase();
  104896. //Get the data following the key
  104897. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104898. //This mtl keyword will create the new material
  104899. if (key === "newmtl") {
  104900. //Check if it is the first material.
  104901. // Materials specifications are described after this keyword.
  104902. if (material) {
  104903. //Add the previous material in the material array.
  104904. this.materials.push(material);
  104905. }
  104906. //Create a new material.
  104907. // value is the name of the material read in the mtl file
  104908. material = new BABYLON.StandardMaterial(value, scene);
  104909. }
  104910. else if (key === "kd" && material) {
  104911. // Diffuse color (color under white light) using RGB values
  104912. //value = "r g b"
  104913. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104914. //color = [r,g,b]
  104915. //Set tghe color into the material
  104916. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104917. }
  104918. else if (key === "ka" && material) {
  104919. // Ambient color (color under shadow) using RGB values
  104920. //value = "r g b"
  104921. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104922. //color = [r,g,b]
  104923. //Set tghe color into the material
  104924. material.ambientColor = BABYLON.Color3.FromArray(color);
  104925. }
  104926. else if (key === "ks" && material) {
  104927. // Specular color (color when light is reflected from shiny surface) using RGB values
  104928. //value = "r g b"
  104929. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104930. //color = [r,g,b]
  104931. //Set the color into the material
  104932. material.specularColor = BABYLON.Color3.FromArray(color);
  104933. }
  104934. else if (key === "ke" && material) {
  104935. // Emissive color using RGB values
  104936. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104937. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104938. }
  104939. else if (key === "ns" && material) {
  104940. //value = "Integer"
  104941. material.specularPower = parseFloat(value);
  104942. }
  104943. else if (key === "d" && material) {
  104944. //d is dissolve for current material. It mean alpha for BABYLON
  104945. material.alpha = parseFloat(value);
  104946. //Texture
  104947. //This part can be improved by adding the possible options of texture
  104948. }
  104949. else if (key === "map_ka" && material) {
  104950. // ambient texture map with a loaded image
  104951. //We must first get the folder of the image
  104952. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104953. }
  104954. else if (key === "map_kd" && material) {
  104955. // Diffuse texture map with a loaded image
  104956. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104957. }
  104958. else if (key === "map_ks" && material) {
  104959. // Specular texture map with a loaded image
  104960. //We must first get the folder of the image
  104961. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104962. }
  104963. else if (key === "map_ns") {
  104964. //Specular
  104965. //Specular highlight component
  104966. //We must first get the folder of the image
  104967. //
  104968. //Not supported by BABYLON
  104969. //
  104970. // continue;
  104971. }
  104972. else if (key === "map_bump" && material) {
  104973. //The bump texture
  104974. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104975. }
  104976. else if (key === "map_d" && material) {
  104977. // The dissolve of the material
  104978. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104979. //Options for illumination
  104980. }
  104981. else if (key === "illum") {
  104982. //Illumination
  104983. if (value === "0") {
  104984. //That mean Kd == Kd
  104985. }
  104986. else if (value === "1") {
  104987. //Color on and Ambient on
  104988. }
  104989. else if (value === "2") {
  104990. //Highlight on
  104991. }
  104992. else if (value === "3") {
  104993. //Reflection on and Ray trace on
  104994. }
  104995. else if (value === "4") {
  104996. //Transparency: Glass on, Reflection: Ray trace on
  104997. }
  104998. else if (value === "5") {
  104999. //Reflection: Fresnel on and Ray trace on
  105000. }
  105001. else if (value === "6") {
  105002. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105003. }
  105004. else if (value === "7") {
  105005. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105006. }
  105007. else if (value === "8") {
  105008. //Reflection on and Ray trace off
  105009. }
  105010. else if (value === "9") {
  105011. //Transparency: Glass on, Reflection: Ray trace off
  105012. }
  105013. else if (value === "10") {
  105014. //Casts shadows onto invisible surfaces
  105015. }
  105016. }
  105017. else {
  105018. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105019. }
  105020. }
  105021. //At the end of the file, add the last material
  105022. if (material) {
  105023. this.materials.push(material);
  105024. }
  105025. };
  105026. /**
  105027. * Gets the texture for the material.
  105028. *
  105029. * If the material is imported from input file,
  105030. * We sanitize the url to ensure it takes the textre from aside the material.
  105031. *
  105032. * @param rootUrl The root url to load from
  105033. * @param value The value stored in the mtl
  105034. * @return The Texture
  105035. */
  105036. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105037. if (!value) {
  105038. return null;
  105039. }
  105040. var url = rootUrl;
  105041. // Load from input file.
  105042. if (rootUrl === "file:") {
  105043. var lastDelimiter = value.lastIndexOf("\\");
  105044. if (lastDelimiter === -1) {
  105045. lastDelimiter = value.lastIndexOf("/");
  105046. }
  105047. if (lastDelimiter > -1) {
  105048. url += value.substr(lastDelimiter + 1);
  105049. }
  105050. else {
  105051. url += value;
  105052. }
  105053. }
  105054. else {
  105055. url += value;
  105056. }
  105057. return new BABYLON.Texture(url, scene);
  105058. };
  105059. return MTLFileLoader;
  105060. }());
  105061. BABYLON.MTLFileLoader = MTLFileLoader;
  105062. var OBJFileLoader = /** @class */ (function () {
  105063. function OBJFileLoader() {
  105064. this.name = "obj";
  105065. this.extensions = ".obj";
  105066. this.obj = /^o/;
  105067. this.group = /^g/;
  105068. this.mtllib = /^mtllib /;
  105069. this.usemtl = /^usemtl /;
  105070. this.smooth = /^s /;
  105071. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105072. // vn float float float
  105073. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105074. // vt float float
  105075. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105076. // f vertex vertex vertex ...
  105077. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105078. // f vertex/uvs vertex/uvs vertex/uvs ...
  105079. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105080. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105081. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105082. // f vertex//normal vertex//normal vertex//normal ...
  105083. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105084. }
  105085. /**
  105086. * Calls synchronously the MTL file attached to this obj.
  105087. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105088. * Without this function materials are not displayed in the first frame (but displayed after).
  105089. * In consequence it is impossible to get material information in your HTML file
  105090. *
  105091. * @param url The URL of the MTL file
  105092. * @param rootUrl
  105093. * @param onSuccess Callback function to be called when the MTL file is loaded
  105094. * @private
  105095. */
  105096. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105097. //The complete path to the mtl file
  105098. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105099. // Loads through the babylon tools to allow fileInput search.
  105100. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105101. };
  105102. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105103. //get the meshes from OBJ file
  105104. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105105. //Push meshes from OBJ file into the variable mesh of this function
  105106. if (meshes) {
  105107. loadedMeshes.forEach(function (mesh) {
  105108. meshes.push(mesh);
  105109. });
  105110. }
  105111. return true;
  105112. };
  105113. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105114. //Get the 3D model
  105115. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105116. };
  105117. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105118. var container = new BABYLON.AssetContainer(scene);
  105119. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105120. container.removeAllFromScene();
  105121. return container;
  105122. };
  105123. /**
  105124. * Read the OBJ file and create an Array of meshes.
  105125. * Each mesh contains all information given by the OBJ and the MTL file.
  105126. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105127. *
  105128. * @param meshesNames
  105129. * @param scene BABYLON.Scene The scene where are displayed the data
  105130. * @param data String The content of the obj file
  105131. * @param rootUrl String The path to the folder
  105132. * @returns Array<AbstractMesh>
  105133. * @private
  105134. */
  105135. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105136. var positions = []; //values for the positions of vertices
  105137. var normals = []; //Values for the normals
  105138. var uvs = []; //Values for the textures
  105139. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105140. var handledMesh; //The current mesh of meshes array
  105141. var indicesForBabylon = []; //The list of indices for VertexData
  105142. var wrappedPositionForBabylon = []; //The list of position in vectors
  105143. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105144. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105145. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105146. var curPositionInIndices = 0;
  105147. var hasMeshes = false; //Meshes are defined in the file
  105148. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105149. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105150. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105151. var triangles = []; //Indices from new triangles coming from polygons
  105152. var materialNameFromObj = ""; //The name of the current material
  105153. var fileToLoad = ""; //The name of the mtlFile to load
  105154. var materialsFromMTLFile = new MTLFileLoader();
  105155. var objMeshName = ""; //The name of the current obj mesh
  105156. var increment = 1; //Id for meshes created by the multimaterial
  105157. var isFirstMaterial = true;
  105158. /**
  105159. * Search for obj in the given array.
  105160. * This function is called to check if a couple of data already exists in an array.
  105161. *
  105162. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105163. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105164. * @param obj Array<number>
  105165. * @returns {boolean}
  105166. */
  105167. var isInArray = function (arr, obj) {
  105168. if (!arr[obj[0]])
  105169. arr[obj[0]] = { normals: [], idx: [] };
  105170. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105171. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105172. };
  105173. var isInArrayUV = function (arr, obj) {
  105174. if (!arr[obj[0]])
  105175. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105176. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105177. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105178. return arr[obj[0]].idx[idx];
  105179. }
  105180. return -1;
  105181. };
  105182. /**
  105183. * This function set the data for each triangle.
  105184. * Data are position, normals and uvs
  105185. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105186. * If the tuple already exist, add only their indice
  105187. *
  105188. * @param indicePositionFromObj Integer The index in positions array
  105189. * @param indiceUvsFromObj Integer The index in uvs array
  105190. * @param indiceNormalFromObj Integer The index in normals array
  105191. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105192. * @param textureVectorFromOBJ Vector3 The value of uvs
  105193. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105194. */
  105195. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105196. //Check if this tuple already exists in the list of tuples
  105197. var _index;
  105198. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105199. _index = isInArrayUV(tuplePosNorm, [
  105200. indicePositionFromObj,
  105201. indiceNormalFromObj,
  105202. indiceUvsFromObj
  105203. ]);
  105204. }
  105205. else {
  105206. _index = isInArray(tuplePosNorm, [
  105207. indicePositionFromObj,
  105208. indiceNormalFromObj
  105209. ]);
  105210. }
  105211. //If it not exists
  105212. if (_index == -1) {
  105213. //Add an new indice.
  105214. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105215. //We add vertices data in this order
  105216. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105217. //Push the position of vertice for Babylon
  105218. //Each element is a BABYLON.Vector3(x,y,z)
  105219. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105220. //Push the uvs for Babylon
  105221. //Each element is a BABYLON.Vector3(u,v)
  105222. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105223. //Push the normals for Babylon
  105224. //Each element is a BABYLON.Vector3(x,y,z)
  105225. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105226. //Add the tuple in the comparison list
  105227. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105228. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105229. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105230. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105231. }
  105232. else {
  105233. //The tuple already exists
  105234. //Add the index of the already existing tuple
  105235. //At this index we can get the value of position, normal and uvs of vertex
  105236. indicesForBabylon.push(_index);
  105237. }
  105238. };
  105239. /**
  105240. * Transform BABYLON.Vector() object onto 3 digits in an array
  105241. */
  105242. var unwrapData = function () {
  105243. //Every array has the same length
  105244. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105245. //Push the x, y, z values of each element in the unwrapped array
  105246. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105247. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105248. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105249. }
  105250. // Reset arrays for the next new meshes
  105251. wrappedPositionForBabylon = [];
  105252. wrappedNormalsForBabylon = [];
  105253. wrappedUvsForBabylon = [];
  105254. tuplePosNorm = [];
  105255. curPositionInIndices = 0;
  105256. };
  105257. /**
  105258. * Create triangles from polygons by recursion
  105259. * The best to understand how it works is to draw it in the same time you get the recursion.
  105260. * It is important to notice that a triangle is a polygon
  105261. * We get 4 patterns of face defined in OBJ File :
  105262. * facePattern1 = ["1","2","3","4","5","6"]
  105263. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105264. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105265. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105266. * Each pattern is divided by the same method
  105267. * @param face Array[String] The indices of elements
  105268. * @param v Integer The variable to increment
  105269. */
  105270. var getTriangles = function (face, v) {
  105271. //Work for each element of the array
  105272. if (v + 1 < face.length) {
  105273. //Add on the triangle variable the indexes to obtain triangles
  105274. triangles.push(face[0], face[v], face[v + 1]);
  105275. //Incrementation for recursion
  105276. v += 1;
  105277. //Recursion
  105278. getTriangles(face, v);
  105279. }
  105280. //Result obtained after 2 iterations:
  105281. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105282. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105283. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105284. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105285. };
  105286. /**
  105287. * Create triangles and push the data for each polygon for the pattern 1
  105288. * In this pattern we get vertice positions
  105289. * @param face
  105290. * @param v
  105291. */
  105292. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105293. //Get the indices of triangles for each polygon
  105294. getTriangles(face, v);
  105295. //For each element in the triangles array.
  105296. //This var could contains 1 to an infinity of triangles
  105297. for (var k = 0; k < triangles.length; k++) {
  105298. // Set position indice
  105299. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105300. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105301. positions[indicePositionFromObj], //Get the vectors data
  105302. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105303. );
  105304. }
  105305. //Reset variable for the next line
  105306. triangles = [];
  105307. };
  105308. /**
  105309. * Create triangles and push the data for each polygon for the pattern 2
  105310. * In this pattern we get vertice positions and uvsu
  105311. * @param face
  105312. * @param v
  105313. */
  105314. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105315. //Get the indices of triangles for each polygon
  105316. getTriangles(face, v);
  105317. for (var k = 0; k < triangles.length; k++) {
  105318. //triangle[k] = "1/1"
  105319. //Split the data for getting position and uv
  105320. var point = triangles[k].split("/"); // ["1", "1"]
  105321. //Set position indice
  105322. var indicePositionFromObj = parseInt(point[0]) - 1;
  105323. //Set uv indice
  105324. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105325. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105326. positions[indicePositionFromObj], //Get the values for each element
  105327. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105328. );
  105329. }
  105330. //Reset variable for the next line
  105331. triangles = [];
  105332. };
  105333. /**
  105334. * Create triangles and push the data for each polygon for the pattern 3
  105335. * In this pattern we get vertice positions, uvs and normals
  105336. * @param face
  105337. * @param v
  105338. */
  105339. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105340. //Get the indices of triangles for each polygon
  105341. getTriangles(face, v);
  105342. for (var k = 0; k < triangles.length; k++) {
  105343. //triangle[k] = "1/1/1"
  105344. //Split the data for getting position, uv, and normals
  105345. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105346. // Set position indice
  105347. var indicePositionFromObj = parseInt(point[0]) - 1;
  105348. // Set uv indice
  105349. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105350. // Set normal indice
  105351. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105352. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105353. );
  105354. }
  105355. //Reset variable for the next line
  105356. triangles = [];
  105357. };
  105358. /**
  105359. * Create triangles and push the data for each polygon for the pattern 4
  105360. * In this pattern we get vertice positions and normals
  105361. * @param face
  105362. * @param v
  105363. */
  105364. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105365. getTriangles(face, v);
  105366. for (var k = 0; k < triangles.length; k++) {
  105367. //triangle[k] = "1//1"
  105368. //Split the data for getting position and normals
  105369. var point = triangles[k].split("//"); // ["1", "1"]
  105370. // We check indices, and normals
  105371. var indicePositionFromObj = parseInt(point[0]) - 1;
  105372. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105373. setData(indicePositionFromObj, 1, //Default value for uv
  105374. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105375. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105376. }
  105377. //Reset variable for the next line
  105378. triangles = [];
  105379. };
  105380. var addPreviousObjMesh = function () {
  105381. //Check if it is not the first mesh. Otherwise we don't have data.
  105382. if (meshesFromObj.length > 0) {
  105383. //Get the previous mesh for applying the data about the faces
  105384. //=> in obj file, faces definition append after the name of the mesh
  105385. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105386. //Set the data into Array for the mesh
  105387. unwrapData();
  105388. // Reverse tab. Otherwise face are displayed in the wrong sens
  105389. indicesForBabylon.reverse();
  105390. //Set the information for the mesh
  105391. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105392. handledMesh.indices = indicesForBabylon.slice();
  105393. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105394. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105395. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105396. //Reset the array for the next mesh
  105397. indicesForBabylon = [];
  105398. unwrappedPositionsForBabylon = [];
  105399. unwrappedNormalsForBabylon = [];
  105400. unwrappedUVForBabylon = [];
  105401. }
  105402. };
  105403. //Main function
  105404. //Split the file into lines
  105405. var lines = data.split('\n');
  105406. //Look at each line
  105407. for (var i = 0; i < lines.length; i++) {
  105408. var line = lines[i].trim();
  105409. var result;
  105410. //Comment or newLine
  105411. if (line.length === 0 || line.charAt(0) === '#') {
  105412. continue;
  105413. //Get information about one position possible for the vertices
  105414. }
  105415. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105416. //Create a Vector3 with the position x, y, z
  105417. //Value of result:
  105418. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105419. //Add the Vector in the list of positions
  105420. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105421. }
  105422. else if ((result = this.normalPattern.exec(line)) !== null) {
  105423. //Create a Vector3 with the normals x, y, z
  105424. //Value of result
  105425. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105426. //Add the Vector in the list of normals
  105427. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105428. }
  105429. else if ((result = this.uvPattern.exec(line)) !== null) {
  105430. //Create a Vector2 with the normals u, v
  105431. //Value of result
  105432. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105433. //Add the Vector in the list of uvs
  105434. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105435. //Identify patterns of faces
  105436. //Face could be defined in different type of pattern
  105437. }
  105438. else if ((result = this.facePattern3.exec(line)) !== null) {
  105439. //Value of result:
  105440. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105441. //Set the data for this face
  105442. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105443. 1);
  105444. }
  105445. else if ((result = this.facePattern4.exec(line)) !== null) {
  105446. //Value of result:
  105447. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105448. //Set the data for this face
  105449. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105450. 1);
  105451. }
  105452. else if ((result = this.facePattern2.exec(line)) !== null) {
  105453. //Value of result:
  105454. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105455. //Set the data for this face
  105456. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105457. 1);
  105458. }
  105459. else if ((result = this.facePattern1.exec(line)) !== null) {
  105460. //Value of result
  105461. //["f 1 2 3", "1 2 3"...]
  105462. //Set the data for this face
  105463. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105464. 1);
  105465. //Define a mesh or an object
  105466. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105467. }
  105468. else if (this.group.test(line) || this.obj.test(line)) {
  105469. //Create a new mesh corresponding to the name of the group.
  105470. //Definition of the mesh
  105471. var objMesh =
  105472. //Set the name of the current obj mesh
  105473. {
  105474. name: line.substring(2).trim(),
  105475. indices: undefined,
  105476. positions: undefined,
  105477. normals: undefined,
  105478. uvs: undefined,
  105479. materialName: ""
  105480. };
  105481. addPreviousObjMesh();
  105482. //Push the last mesh created with only the name
  105483. meshesFromObj.push(objMesh);
  105484. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105485. hasMeshes = true;
  105486. isFirstMaterial = true;
  105487. increment = 1;
  105488. //Keyword for applying a material
  105489. }
  105490. else if (this.usemtl.test(line)) {
  105491. //Get the name of the material
  105492. materialNameFromObj = line.substring(7).trim();
  105493. //If this new material is in the same mesh
  105494. if (!isFirstMaterial) {
  105495. //Set the data for the previous mesh
  105496. addPreviousObjMesh();
  105497. //Create a new mesh
  105498. var objMesh =
  105499. //Set the name of the current obj mesh
  105500. {
  105501. name: objMeshName + "_mm" + increment.toString(),
  105502. indices: undefined,
  105503. positions: undefined,
  105504. normals: undefined,
  105505. uvs: undefined,
  105506. materialName: materialNameFromObj
  105507. };
  105508. increment++;
  105509. //If meshes are already defined
  105510. meshesFromObj.push(objMesh);
  105511. }
  105512. //Set the material name if the previous line define a mesh
  105513. if (hasMeshes && isFirstMaterial) {
  105514. //Set the material name to the previous mesh (1 material per mesh)
  105515. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105516. isFirstMaterial = false;
  105517. }
  105518. //Keyword for loading the mtl file
  105519. }
  105520. else if (this.mtllib.test(line)) {
  105521. //Get the name of mtl file
  105522. fileToLoad = line.substring(7).trim();
  105523. //Apply smoothing
  105524. }
  105525. else if (this.smooth.test(line)) {
  105526. // smooth shading => apply smoothing
  105527. //Toda y I don't know it work with babylon and with obj.
  105528. //With the obj file an integer is set
  105529. }
  105530. else {
  105531. //If there is another possibility
  105532. console.log("Unhandled expression at line : " + line);
  105533. }
  105534. }
  105535. //At the end of the file, add the last mesh into the meshesFromObj array
  105536. if (hasMeshes) {
  105537. //Set the data for the last mesh
  105538. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105539. //Reverse indices for displaying faces in the good sens
  105540. indicesForBabylon.reverse();
  105541. //Get the good array
  105542. unwrapData();
  105543. //Set array
  105544. handledMesh.indices = indicesForBabylon;
  105545. handledMesh.positions = unwrappedPositionsForBabylon;
  105546. handledMesh.normals = unwrappedNormalsForBabylon;
  105547. handledMesh.uvs = unwrappedUVForBabylon;
  105548. }
  105549. //If any o or g keyword found, create a mesj with a random id
  105550. if (!hasMeshes) {
  105551. // reverse tab of indices
  105552. indicesForBabylon.reverse();
  105553. //Get positions normals uvs
  105554. unwrapData();
  105555. //Set data for one mesh
  105556. meshesFromObj.push({
  105557. name: BABYLON.Geometry.RandomId(),
  105558. indices: indicesForBabylon,
  105559. positions: unwrappedPositionsForBabylon,
  105560. normals: unwrappedNormalsForBabylon,
  105561. uvs: unwrappedUVForBabylon,
  105562. materialName: materialNameFromObj
  105563. });
  105564. }
  105565. //Create a BABYLON.Mesh list
  105566. var babylonMeshesArray = []; //The mesh for babylon
  105567. var materialToUse = new Array();
  105568. //Set data for each mesh
  105569. for (var j = 0; j < meshesFromObj.length; j++) {
  105570. //check meshesNames (stlFileLoader)
  105571. if (meshesNames && meshesFromObj[j].name) {
  105572. if (meshesNames instanceof Array) {
  105573. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105574. continue;
  105575. }
  105576. }
  105577. else {
  105578. if (meshesFromObj[j].name !== meshesNames) {
  105579. continue;
  105580. }
  105581. }
  105582. }
  105583. //Get the current mesh
  105584. //Set the data with VertexBuffer for each mesh
  105585. handledMesh = meshesFromObj[j];
  105586. //Create a BABYLON.Mesh with the name of the obj mesh
  105587. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105588. //Push the name of the material to an array
  105589. //This is indispensable for the importMesh function
  105590. materialToUse.push(meshesFromObj[j].materialName);
  105591. var vertexData = new BABYLON.VertexData(); //The container for the values
  105592. //Set the data for the babylonMesh
  105593. vertexData.positions = handledMesh.positions;
  105594. vertexData.normals = handledMesh.normals;
  105595. vertexData.uvs = handledMesh.uvs;
  105596. vertexData.indices = handledMesh.indices;
  105597. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105598. vertexData.applyToMesh(babylonMesh);
  105599. //Push the mesh into an array
  105600. babylonMeshesArray.push(babylonMesh);
  105601. }
  105602. //load the materials
  105603. //Check if we have a file to load
  105604. if (fileToLoad !== "") {
  105605. //Load the file synchronously
  105606. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105607. //Create materials thanks MTLLoader function
  105608. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105609. //Look at each material loaded in the mtl file
  105610. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105611. //Three variables to get all meshes with the same material
  105612. var startIndex = 0;
  105613. var _indices = [];
  105614. var _index;
  105615. //The material from MTL file is used in the meshes loaded
  105616. //Push the indice in an array
  105617. //Check if the material is not used for another mesh
  105618. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105619. _indices.push(_index);
  105620. startIndex = _index + 1;
  105621. }
  105622. //If the material is not used dispose it
  105623. if (_index == -1 && _indices.length == 0) {
  105624. //If the material is not needed, remove it
  105625. materialsFromMTLFile.materials[n].dispose();
  105626. }
  105627. else {
  105628. for (var o = 0; o < _indices.length; o++) {
  105629. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105630. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105631. }
  105632. }
  105633. }
  105634. });
  105635. }
  105636. //Return an array with all BABYLON.Mesh
  105637. return babylonMeshesArray;
  105638. };
  105639. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105640. return OBJFileLoader;
  105641. }());
  105642. BABYLON.OBJFileLoader = OBJFileLoader;
  105643. if (BABYLON.SceneLoader) {
  105644. //Add this loader into the register plugin
  105645. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105646. }
  105647. })(BABYLON || (BABYLON = {}));
  105648. //# sourceMappingURL=babylon.objFileLoader.js.map
  105649. var BABYLON;
  105650. (function (BABYLON) {
  105651. var GLTFLoaderCoordinateSystemMode;
  105652. (function (GLTFLoaderCoordinateSystemMode) {
  105653. /**
  105654. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105655. */
  105656. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105657. /**
  105658. * Sets the useRightHandedSystem flag on the scene.
  105659. */
  105660. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105661. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105662. var GLTFLoaderAnimationStartMode;
  105663. (function (GLTFLoaderAnimationStartMode) {
  105664. /**
  105665. * No animation will start.
  105666. */
  105667. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105668. /**
  105669. * The first animation will start.
  105670. */
  105671. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105672. /**
  105673. * All animations will start.
  105674. */
  105675. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105676. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105677. var GLTFLoaderState;
  105678. (function (GLTFLoaderState) {
  105679. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  105680. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  105681. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  105682. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105683. var GLTFFileLoader = /** @class */ (function () {
  105684. function GLTFFileLoader() {
  105685. // #region Common options
  105686. /**
  105687. * Raised when the asset has been parsed.
  105688. * The data.json property stores the glTF JSON.
  105689. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  105690. */
  105691. this.onParsedObservable = new BABYLON.Observable();
  105692. // #endregion
  105693. // #region V2 options
  105694. /**
  105695. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  105696. */
  105697. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105698. /**
  105699. * The animation start mode (NONE, FIRST, ALL).
  105700. */
  105701. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105702. /**
  105703. * Set to true to compile materials before raising the success callback.
  105704. */
  105705. this.compileMaterials = false;
  105706. /**
  105707. * Set to true to also compile materials with clip planes.
  105708. */
  105709. this.useClipPlane = false;
  105710. /**
  105711. * Set to true to compile shadow generators before raising the success callback.
  105712. */
  105713. this.compileShadowGenerators = false;
  105714. /**
  105715. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105716. */
  105717. this.onMeshLoadedObservable = new BABYLON.Observable();
  105718. /**
  105719. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  105720. */
  105721. this.onTextureLoadedObservable = new BABYLON.Observable();
  105722. /**
  105723. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105724. */
  105725. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105726. /**
  105727. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  105728. */
  105729. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  105730. /**
  105731. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105732. * For assets with LODs, raised when all of the LODs are complete.
  105733. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105734. */
  105735. this.onCompleteObservable = new BABYLON.Observable();
  105736. /**
  105737. * Raised when the loader is disposed.
  105738. */
  105739. this.onDisposeObservable = new BABYLON.Observable();
  105740. /**
  105741. * Raised after a loader extension is created.
  105742. * Set additional options for a loader extension in this event.
  105743. */
  105744. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105745. // #endregion
  105746. this._loader = null;
  105747. this.name = "gltf";
  105748. this.extensions = {
  105749. ".gltf": { isBinary: false },
  105750. ".glb": { isBinary: true }
  105751. };
  105752. }
  105753. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105754. set: function (callback) {
  105755. if (this._onParsedObserver) {
  105756. this.onParsedObservable.remove(this._onParsedObserver);
  105757. }
  105758. this._onParsedObserver = this.onParsedObservable.add(callback);
  105759. },
  105760. enumerable: true,
  105761. configurable: true
  105762. });
  105763. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105764. set: function (callback) {
  105765. if (this._onMeshLoadedObserver) {
  105766. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105767. }
  105768. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105769. },
  105770. enumerable: true,
  105771. configurable: true
  105772. });
  105773. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105774. set: function (callback) {
  105775. if (this._onTextureLoadedObserver) {
  105776. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105777. }
  105778. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105779. },
  105780. enumerable: true,
  105781. configurable: true
  105782. });
  105783. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105784. set: function (callback) {
  105785. if (this._onMaterialLoadedObserver) {
  105786. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105787. }
  105788. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105789. },
  105790. enumerable: true,
  105791. configurable: true
  105792. });
  105793. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  105794. set: function (callback) {
  105795. if (this._onAnimationGroupLoadedObserver) {
  105796. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  105797. }
  105798. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  105799. },
  105800. enumerable: true,
  105801. configurable: true
  105802. });
  105803. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105804. set: function (callback) {
  105805. if (this._onCompleteObserver) {
  105806. this.onCompleteObservable.remove(this._onCompleteObserver);
  105807. }
  105808. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105809. },
  105810. enumerable: true,
  105811. configurable: true
  105812. });
  105813. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105814. set: function (callback) {
  105815. if (this._onDisposeObserver) {
  105816. this.onDisposeObservable.remove(this._onDisposeObserver);
  105817. }
  105818. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105819. },
  105820. enumerable: true,
  105821. configurable: true
  105822. });
  105823. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105824. set: function (callback) {
  105825. if (this._onExtensionLoadedObserver) {
  105826. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105827. }
  105828. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105829. },
  105830. enumerable: true,
  105831. configurable: true
  105832. });
  105833. /**
  105834. * Gets a promise that resolves when the asset is completely loaded.
  105835. * @returns A promise that resolves when the asset is completely loaded.
  105836. */
  105837. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105838. var _this = this;
  105839. return new Promise(function (resolve) {
  105840. _this.onCompleteObservable.add(function () {
  105841. resolve();
  105842. }, undefined, undefined, undefined, true);
  105843. });
  105844. };
  105845. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105846. /**
  105847. * The loader state or null if not active.
  105848. */
  105849. get: function () {
  105850. return this._loader ? this._loader.state : null;
  105851. },
  105852. enumerable: true,
  105853. configurable: true
  105854. });
  105855. /**
  105856. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105857. */
  105858. GLTFFileLoader.prototype.dispose = function () {
  105859. if (this._loader) {
  105860. this._loader.dispose();
  105861. this._loader = null;
  105862. }
  105863. this.onMeshLoadedObservable.clear();
  105864. this.onTextureLoadedObservable.clear();
  105865. this.onMaterialLoadedObservable.clear();
  105866. this.onDisposeObservable.notifyObservers(this);
  105867. this.onDisposeObservable.clear();
  105868. };
  105869. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105870. var _this = this;
  105871. return Promise.resolve().then(function () {
  105872. var loaderData = _this._parse(data);
  105873. _this._loader = _this._getLoader(loaderData);
  105874. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105875. });
  105876. };
  105877. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105878. var _this = this;
  105879. return Promise.resolve().then(function () {
  105880. var loaderData = _this._parse(data);
  105881. _this._loader = _this._getLoader(loaderData);
  105882. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105883. });
  105884. };
  105885. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105886. var _this = this;
  105887. return Promise.resolve().then(function () {
  105888. var loaderData = _this._parse(data);
  105889. _this._loader = _this._getLoader(loaderData);
  105890. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105891. var container = new BABYLON.AssetContainer(scene);
  105892. Array.prototype.push.apply(container.meshes, result.meshes);
  105893. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105894. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105895. container.removeAllFromScene();
  105896. return container;
  105897. });
  105898. });
  105899. };
  105900. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105901. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105902. };
  105903. GLTFFileLoader.prototype.createPlugin = function () {
  105904. return new GLTFFileLoader();
  105905. };
  105906. GLTFFileLoader.prototype._parse = function (data) {
  105907. var parsedData;
  105908. if (data instanceof ArrayBuffer) {
  105909. parsedData = GLTFFileLoader._parseBinary(data);
  105910. }
  105911. else {
  105912. parsedData = {
  105913. json: JSON.parse(data),
  105914. bin: null
  105915. };
  105916. }
  105917. this.onParsedObservable.notifyObservers(parsedData);
  105918. this.onParsedObservable.clear();
  105919. return parsedData;
  105920. };
  105921. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105922. var _this = this;
  105923. var loaderVersion = { major: 2, minor: 0 };
  105924. var asset = loaderData.json.asset || {};
  105925. var version = GLTFFileLoader._parseVersion(asset.version);
  105926. if (!version) {
  105927. throw new Error("Invalid version: " + asset.version);
  105928. }
  105929. if (asset.minVersion !== undefined) {
  105930. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105931. if (!minVersion) {
  105932. throw new Error("Invalid minimum version: " + asset.minVersion);
  105933. }
  105934. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105935. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105936. }
  105937. }
  105938. var createLoaders = {
  105939. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105940. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105941. };
  105942. var createLoader = createLoaders[version.major];
  105943. if (!createLoader) {
  105944. throw new Error("Unsupported version: " + asset.version);
  105945. }
  105946. var loader = createLoader();
  105947. loader.coordinateSystemMode = this.coordinateSystemMode;
  105948. loader.animationStartMode = this.animationStartMode;
  105949. loader.compileMaterials = this.compileMaterials;
  105950. loader.useClipPlane = this.useClipPlane;
  105951. loader.compileShadowGenerators = this.compileShadowGenerators;
  105952. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  105953. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  105954. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  105955. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  105956. loader.onCompleteObservable.add(function () {
  105957. _this.onMeshLoadedObservable.clear();
  105958. _this.onTextureLoadedObservable.clear();
  105959. _this.onMaterialLoadedObservable.clear();
  105960. _this.onCompleteObservable.notifyObservers(_this);
  105961. _this.onCompleteObservable.clear();
  105962. });
  105963. return loader;
  105964. };
  105965. GLTFFileLoader._parseBinary = function (data) {
  105966. var Binary = {
  105967. Magic: 0x46546C67
  105968. };
  105969. var binaryReader = new BinaryReader(data);
  105970. var magic = binaryReader.readUint32();
  105971. if (magic !== Binary.Magic) {
  105972. throw new Error("Unexpected magic: " + magic);
  105973. }
  105974. var version = binaryReader.readUint32();
  105975. switch (version) {
  105976. case 1: return GLTFFileLoader._parseV1(binaryReader);
  105977. case 2: return GLTFFileLoader._parseV2(binaryReader);
  105978. }
  105979. throw new Error("Unsupported version: " + version);
  105980. };
  105981. GLTFFileLoader._parseV1 = function (binaryReader) {
  105982. var ContentFormat = {
  105983. JSON: 0
  105984. };
  105985. var length = binaryReader.readUint32();
  105986. if (length != binaryReader.getLength()) {
  105987. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105988. }
  105989. var contentLength = binaryReader.readUint32();
  105990. var contentFormat = binaryReader.readUint32();
  105991. var content;
  105992. switch (contentFormat) {
  105993. case ContentFormat.JSON: {
  105994. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105995. break;
  105996. }
  105997. default: {
  105998. throw new Error("Unexpected content format: " + contentFormat);
  105999. }
  106000. }
  106001. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106002. var body = binaryReader.readUint8Array(bytesRemaining);
  106003. return {
  106004. json: content,
  106005. bin: body
  106006. };
  106007. };
  106008. GLTFFileLoader._parseV2 = function (binaryReader) {
  106009. var ChunkFormat = {
  106010. JSON: 0x4E4F534A,
  106011. BIN: 0x004E4942
  106012. };
  106013. var length = binaryReader.readUint32();
  106014. if (length !== binaryReader.getLength()) {
  106015. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106016. }
  106017. // JSON chunk
  106018. var chunkLength = binaryReader.readUint32();
  106019. var chunkFormat = binaryReader.readUint32();
  106020. if (chunkFormat !== ChunkFormat.JSON) {
  106021. throw new Error("First chunk format is not JSON");
  106022. }
  106023. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106024. // Look for BIN chunk
  106025. var bin = null;
  106026. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106027. var chunkLength_1 = binaryReader.readUint32();
  106028. var chunkFormat_1 = binaryReader.readUint32();
  106029. switch (chunkFormat_1) {
  106030. case ChunkFormat.JSON: {
  106031. throw new Error("Unexpected JSON chunk");
  106032. }
  106033. case ChunkFormat.BIN: {
  106034. bin = binaryReader.readUint8Array(chunkLength_1);
  106035. break;
  106036. }
  106037. default: {
  106038. // ignore unrecognized chunkFormat
  106039. binaryReader.skipBytes(chunkLength_1);
  106040. break;
  106041. }
  106042. }
  106043. }
  106044. return {
  106045. json: json,
  106046. bin: bin
  106047. };
  106048. };
  106049. GLTFFileLoader._parseVersion = function (version) {
  106050. if (version === "1.0" || version === "1.0.1") {
  106051. return {
  106052. major: 1,
  106053. minor: 0
  106054. };
  106055. }
  106056. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106057. if (!match) {
  106058. return null;
  106059. }
  106060. return {
  106061. major: parseInt(match[1]),
  106062. minor: parseInt(match[2])
  106063. };
  106064. };
  106065. GLTFFileLoader._compareVersion = function (a, b) {
  106066. if (a.major > b.major)
  106067. return 1;
  106068. if (a.major < b.major)
  106069. return -1;
  106070. if (a.minor > b.minor)
  106071. return 1;
  106072. if (a.minor < b.minor)
  106073. return -1;
  106074. return 0;
  106075. };
  106076. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106077. var result = "";
  106078. var length = buffer.byteLength;
  106079. for (var i = 0; i < length; i++) {
  106080. result += String.fromCharCode(buffer[i]);
  106081. }
  106082. return result;
  106083. };
  106084. // #endregion
  106085. // #region V1 options
  106086. GLTFFileLoader.IncrementalLoading = true;
  106087. GLTFFileLoader.HomogeneousCoordinates = false;
  106088. return GLTFFileLoader;
  106089. }());
  106090. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106091. var BinaryReader = /** @class */ (function () {
  106092. function BinaryReader(arrayBuffer) {
  106093. this._arrayBuffer = arrayBuffer;
  106094. this._dataView = new DataView(arrayBuffer);
  106095. this._byteOffset = 0;
  106096. }
  106097. BinaryReader.prototype.getPosition = function () {
  106098. return this._byteOffset;
  106099. };
  106100. BinaryReader.prototype.getLength = function () {
  106101. return this._arrayBuffer.byteLength;
  106102. };
  106103. BinaryReader.prototype.readUint32 = function () {
  106104. var value = this._dataView.getUint32(this._byteOffset, true);
  106105. this._byteOffset += 4;
  106106. return value;
  106107. };
  106108. BinaryReader.prototype.readUint8Array = function (length) {
  106109. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106110. this._byteOffset += length;
  106111. return value;
  106112. };
  106113. BinaryReader.prototype.skipBytes = function (length) {
  106114. this._byteOffset += length;
  106115. };
  106116. return BinaryReader;
  106117. }());
  106118. if (BABYLON.SceneLoader) {
  106119. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106120. }
  106121. })(BABYLON || (BABYLON = {}));
  106122. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106123. var BABYLON;
  106124. (function (BABYLON) {
  106125. var GLTF1;
  106126. (function (GLTF1) {
  106127. /**
  106128. * Enums
  106129. */
  106130. var EComponentType;
  106131. (function (EComponentType) {
  106132. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106133. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106134. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106135. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106136. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106137. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106138. var EShaderType;
  106139. (function (EShaderType) {
  106140. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106141. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106142. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106143. var EParameterType;
  106144. (function (EParameterType) {
  106145. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106146. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106147. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106148. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106149. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106150. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106151. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106152. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106153. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106154. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106155. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106156. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106157. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106158. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106159. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106160. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106161. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106162. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106163. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106164. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106165. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106166. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106167. var ETextureWrapMode;
  106168. (function (ETextureWrapMode) {
  106169. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106170. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106171. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106172. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106173. var ETextureFilterType;
  106174. (function (ETextureFilterType) {
  106175. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106176. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106177. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106178. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106179. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106180. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106181. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106182. var ETextureFormat;
  106183. (function (ETextureFormat) {
  106184. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106185. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106186. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106187. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106188. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106189. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106190. var ECullingType;
  106191. (function (ECullingType) {
  106192. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106193. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106194. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106195. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106196. var EBlendingFunction;
  106197. (function (EBlendingFunction) {
  106198. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106199. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106200. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106201. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106202. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106203. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106204. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106205. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106206. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106207. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106208. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106209. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106210. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106211. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106212. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106213. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106214. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106215. })(BABYLON || (BABYLON = {}));
  106216. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106217. var BABYLON;
  106218. (function (BABYLON) {
  106219. var GLTF1;
  106220. (function (GLTF1) {
  106221. /**
  106222. * Tokenizer. Used for shaders compatibility
  106223. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106224. */
  106225. var ETokenType;
  106226. (function (ETokenType) {
  106227. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106228. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106229. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106230. })(ETokenType || (ETokenType = {}));
  106231. var Tokenizer = /** @class */ (function () {
  106232. function Tokenizer(toParse) {
  106233. this._pos = 0;
  106234. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106235. this._toParse = toParse;
  106236. this._maxPos = toParse.length;
  106237. }
  106238. Tokenizer.prototype.getNextToken = function () {
  106239. if (this.isEnd())
  106240. return ETokenType.END_OF_INPUT;
  106241. this.currentString = this.read();
  106242. this.currentToken = ETokenType.UNKNOWN;
  106243. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106244. this.currentToken = ETokenType.IDENTIFIER;
  106245. this.currentIdentifier = this.currentString;
  106246. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106247. this.currentIdentifier += this.currentString;
  106248. this.forward();
  106249. }
  106250. }
  106251. return this.currentToken;
  106252. };
  106253. Tokenizer.prototype.peek = function () {
  106254. return this._toParse[this._pos];
  106255. };
  106256. Tokenizer.prototype.read = function () {
  106257. return this._toParse[this._pos++];
  106258. };
  106259. Tokenizer.prototype.forward = function () {
  106260. this._pos++;
  106261. };
  106262. Tokenizer.prototype.isEnd = function () {
  106263. return this._pos >= this._maxPos;
  106264. };
  106265. return Tokenizer;
  106266. }());
  106267. /**
  106268. * Values
  106269. */
  106270. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106271. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106272. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106273. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106274. /**
  106275. * Parse
  106276. */
  106277. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106278. for (var buf in parsedBuffers) {
  106279. var parsedBuffer = parsedBuffers[buf];
  106280. gltfRuntime.buffers[buf] = parsedBuffer;
  106281. gltfRuntime.buffersCount++;
  106282. }
  106283. };
  106284. var parseShaders = function (parsedShaders, gltfRuntime) {
  106285. for (var sha in parsedShaders) {
  106286. var parsedShader = parsedShaders[sha];
  106287. gltfRuntime.shaders[sha] = parsedShader;
  106288. gltfRuntime.shaderscount++;
  106289. }
  106290. };
  106291. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106292. for (var object in parsedObjects) {
  106293. var parsedObject = parsedObjects[object];
  106294. gltfRuntime[runtimeProperty][object] = parsedObject;
  106295. }
  106296. };
  106297. /**
  106298. * Utils
  106299. */
  106300. var normalizeUVs = function (buffer) {
  106301. if (!buffer) {
  106302. return;
  106303. }
  106304. for (var i = 0; i < buffer.length / 2; i++) {
  106305. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106306. }
  106307. };
  106308. var getAttribute = function (attributeParameter) {
  106309. if (attributeParameter.semantic === "NORMAL") {
  106310. return "normal";
  106311. }
  106312. else if (attributeParameter.semantic === "POSITION") {
  106313. return "position";
  106314. }
  106315. else if (attributeParameter.semantic === "JOINT") {
  106316. return "matricesIndices";
  106317. }
  106318. else if (attributeParameter.semantic === "WEIGHT") {
  106319. return "matricesWeights";
  106320. }
  106321. else if (attributeParameter.semantic === "COLOR") {
  106322. return "color";
  106323. }
  106324. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106325. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106326. return "uv" + (channel === 0 ? "" : channel + 1);
  106327. }
  106328. return null;
  106329. };
  106330. /**
  106331. * Loads and creates animations
  106332. */
  106333. var loadAnimations = function (gltfRuntime) {
  106334. for (var anim in gltfRuntime.animations) {
  106335. var animation = gltfRuntime.animations[anim];
  106336. if (!animation.channels || !animation.samplers) {
  106337. continue;
  106338. }
  106339. var lastAnimation = null;
  106340. for (var i = 0; i < animation.channels.length; i++) {
  106341. // Get parameters and load buffers
  106342. var channel = animation.channels[i];
  106343. var sampler = animation.samplers[channel.sampler];
  106344. if (!sampler) {
  106345. continue;
  106346. }
  106347. var inputData = null;
  106348. var outputData = null;
  106349. if (animation.parameters) {
  106350. inputData = animation.parameters[sampler.input];
  106351. outputData = animation.parameters[sampler.output];
  106352. }
  106353. else {
  106354. inputData = sampler.input;
  106355. outputData = sampler.output;
  106356. }
  106357. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106358. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106359. var targetID = channel.target.id;
  106360. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106361. if (targetNode === null) {
  106362. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106363. }
  106364. if (targetNode === null) {
  106365. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106366. continue;
  106367. }
  106368. var isBone = targetNode instanceof BABYLON.Bone;
  106369. // Get target path (position, rotation or scaling)
  106370. var targetPath = channel.target.path;
  106371. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106372. if (targetPathIndex !== -1) {
  106373. targetPath = babylonAnimationPaths[targetPathIndex];
  106374. }
  106375. // Determine animation type
  106376. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106377. if (!isBone) {
  106378. if (targetPath === "rotationQuaternion") {
  106379. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106380. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106381. }
  106382. else {
  106383. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106384. }
  106385. }
  106386. // Create animation and key frames
  106387. var babylonAnimation = null;
  106388. var keys = [];
  106389. var arrayOffset = 0;
  106390. var modifyKey = false;
  106391. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106392. babylonAnimation = lastAnimation;
  106393. modifyKey = true;
  106394. }
  106395. if (!modifyKey) {
  106396. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106397. }
  106398. // For each frame
  106399. for (var j = 0; j < bufferInput.length; j++) {
  106400. var value = null;
  106401. if (targetPath === "rotationQuaternion") {
  106402. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106403. arrayOffset += 4;
  106404. }
  106405. else {
  106406. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106407. arrayOffset += 3;
  106408. }
  106409. if (isBone) {
  106410. var bone = targetNode;
  106411. var translation = BABYLON.Vector3.Zero();
  106412. var rotationQuaternion = new BABYLON.Quaternion();
  106413. var scaling = BABYLON.Vector3.Zero();
  106414. // Warning on decompose
  106415. var mat = bone.getBaseMatrix();
  106416. if (modifyKey && lastAnimation) {
  106417. mat = lastAnimation.getKeys()[j].value;
  106418. }
  106419. mat.decompose(scaling, rotationQuaternion, translation);
  106420. if (targetPath === "position") {
  106421. translation = value;
  106422. }
  106423. else if (targetPath === "rotationQuaternion") {
  106424. rotationQuaternion = value;
  106425. }
  106426. else {
  106427. scaling = value;
  106428. }
  106429. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106430. }
  106431. if (!modifyKey) {
  106432. keys.push({
  106433. frame: bufferInput[j],
  106434. value: value
  106435. });
  106436. }
  106437. else if (lastAnimation) {
  106438. lastAnimation.getKeys()[j].value = value;
  106439. }
  106440. }
  106441. // Finish
  106442. if (!modifyKey && babylonAnimation) {
  106443. babylonAnimation.setKeys(keys);
  106444. targetNode.animations.push(babylonAnimation);
  106445. }
  106446. lastAnimation = babylonAnimation;
  106447. gltfRuntime.scene.stopAnimation(targetNode);
  106448. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106449. }
  106450. }
  106451. };
  106452. /**
  106453. * Returns the bones transformation matrix
  106454. */
  106455. var configureBoneTransformation = function (node) {
  106456. var mat = null;
  106457. if (node.translation || node.rotation || node.scale) {
  106458. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106459. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106460. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106461. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106462. }
  106463. else {
  106464. mat = BABYLON.Matrix.FromArray(node.matrix);
  106465. }
  106466. return mat;
  106467. };
  106468. /**
  106469. * Returns the parent bone
  106470. */
  106471. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106472. // Try to find
  106473. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106474. if (newSkeleton.bones[i].name === jointName) {
  106475. return newSkeleton.bones[i];
  106476. }
  106477. }
  106478. // Not found, search in gltf nodes
  106479. var nodes = gltfRuntime.nodes;
  106480. for (var nde in nodes) {
  106481. var node = nodes[nde];
  106482. if (!node.jointName) {
  106483. continue;
  106484. }
  106485. var children = node.children;
  106486. for (var i = 0; i < children.length; i++) {
  106487. var child = gltfRuntime.nodes[children[i]];
  106488. if (!child.jointName) {
  106489. continue;
  106490. }
  106491. if (child.jointName === jointName) {
  106492. var mat = configureBoneTransformation(node);
  106493. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106494. bone.id = nde;
  106495. return bone;
  106496. }
  106497. }
  106498. }
  106499. return null;
  106500. };
  106501. /**
  106502. * Returns the appropriate root node
  106503. */
  106504. var getNodeToRoot = function (nodesToRoot, id) {
  106505. for (var i = 0; i < nodesToRoot.length; i++) {
  106506. var nodeToRoot = nodesToRoot[i];
  106507. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106508. var child = nodeToRoot.node.children[j];
  106509. if (child === id) {
  106510. return nodeToRoot.bone;
  106511. }
  106512. }
  106513. }
  106514. return null;
  106515. };
  106516. /**
  106517. * Returns the node with the joint name
  106518. */
  106519. var getJointNode = function (gltfRuntime, jointName) {
  106520. var nodes = gltfRuntime.nodes;
  106521. var node = nodes[jointName];
  106522. if (node) {
  106523. return {
  106524. node: node,
  106525. id: jointName
  106526. };
  106527. }
  106528. for (var nde in nodes) {
  106529. node = nodes[nde];
  106530. if (node.jointName === jointName) {
  106531. return {
  106532. node: node,
  106533. id: nde
  106534. };
  106535. }
  106536. }
  106537. return null;
  106538. };
  106539. /**
  106540. * Checks if a nodes is in joints
  106541. */
  106542. var nodeIsInJoints = function (skins, id) {
  106543. for (var i = 0; i < skins.jointNames.length; i++) {
  106544. if (skins.jointNames[i] === id) {
  106545. return true;
  106546. }
  106547. }
  106548. return false;
  106549. };
  106550. /**
  106551. * Fills the nodes to root for bones and builds hierarchy
  106552. */
  106553. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106554. // Creates nodes for root
  106555. for (var nde in gltfRuntime.nodes) {
  106556. var node = gltfRuntime.nodes[nde];
  106557. var id = nde;
  106558. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106559. continue;
  106560. }
  106561. // Create node to root bone
  106562. var mat = configureBoneTransformation(node);
  106563. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106564. bone.id = id;
  106565. nodesToRoot.push({ bone: bone, node: node, id: id });
  106566. }
  106567. // Parenting
  106568. for (var i = 0; i < nodesToRoot.length; i++) {
  106569. var nodeToRoot = nodesToRoot[i];
  106570. var children = nodeToRoot.node.children;
  106571. for (var j = 0; j < children.length; j++) {
  106572. var child = null;
  106573. for (var k = 0; k < nodesToRoot.length; k++) {
  106574. if (nodesToRoot[k].id === children[j]) {
  106575. child = nodesToRoot[k];
  106576. break;
  106577. }
  106578. }
  106579. if (child) {
  106580. child.bone._parent = nodeToRoot.bone;
  106581. nodeToRoot.bone.children.push(child.bone);
  106582. }
  106583. }
  106584. }
  106585. };
  106586. /**
  106587. * Imports a skeleton
  106588. */
  106589. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106590. if (!newSkeleton) {
  106591. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106592. }
  106593. if (!skins.babylonSkeleton) {
  106594. return newSkeleton;
  106595. }
  106596. // Find the root bones
  106597. var nodesToRoot = [];
  106598. var nodesToRootToAdd = [];
  106599. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106600. newSkeleton.bones = [];
  106601. // Joints
  106602. for (var i = 0; i < skins.jointNames.length; i++) {
  106603. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106604. if (!jointNode) {
  106605. continue;
  106606. }
  106607. var node = jointNode.node;
  106608. if (!node) {
  106609. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106610. continue;
  106611. }
  106612. var id = jointNode.id;
  106613. // Optimize, if the bone already exists...
  106614. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106615. if (existingBone) {
  106616. newSkeleton.bones.push(existingBone);
  106617. continue;
  106618. }
  106619. // Search for parent bone
  106620. var foundBone = false;
  106621. var parentBone = null;
  106622. for (var j = 0; j < i; j++) {
  106623. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106624. if (!jointNode_1) {
  106625. continue;
  106626. }
  106627. var joint = jointNode_1.node;
  106628. if (!joint) {
  106629. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106630. continue;
  106631. }
  106632. var children = joint.children;
  106633. if (!children) {
  106634. continue;
  106635. }
  106636. foundBone = false;
  106637. for (var k = 0; k < children.length; k++) {
  106638. if (children[k] === id) {
  106639. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106640. foundBone = true;
  106641. break;
  106642. }
  106643. }
  106644. if (foundBone) {
  106645. break;
  106646. }
  106647. }
  106648. // Create bone
  106649. var mat = configureBoneTransformation(node);
  106650. if (!parentBone && nodesToRoot.length > 0) {
  106651. parentBone = getNodeToRoot(nodesToRoot, id);
  106652. if (parentBone) {
  106653. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106654. nodesToRootToAdd.push(parentBone);
  106655. }
  106656. }
  106657. }
  106658. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106659. bone.id = id;
  106660. }
  106661. // Polish
  106662. var bones = newSkeleton.bones;
  106663. newSkeleton.bones = [];
  106664. for (var i = 0; i < skins.jointNames.length; i++) {
  106665. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106666. if (!jointNode) {
  106667. continue;
  106668. }
  106669. for (var j = 0; j < bones.length; j++) {
  106670. if (bones[j].id === jointNode.id) {
  106671. newSkeleton.bones.push(bones[j]);
  106672. break;
  106673. }
  106674. }
  106675. }
  106676. newSkeleton.prepare();
  106677. // Finish
  106678. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106679. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106680. }
  106681. return newSkeleton;
  106682. };
  106683. /**
  106684. * Imports a mesh and its geometries
  106685. */
  106686. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106687. if (!newMesh) {
  106688. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106689. newMesh.id = id;
  106690. }
  106691. if (!node.babylonNode) {
  106692. return newMesh;
  106693. }
  106694. var subMaterials = [];
  106695. var vertexData = null;
  106696. var verticesStarts = new Array();
  106697. var verticesCounts = new Array();
  106698. var indexStarts = new Array();
  106699. var indexCounts = new Array();
  106700. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106701. var meshID = meshes[meshIndex];
  106702. var mesh = gltfRuntime.meshes[meshID];
  106703. if (!mesh) {
  106704. continue;
  106705. }
  106706. // Positions, normals and UVs
  106707. for (var i = 0; i < mesh.primitives.length; i++) {
  106708. // Temporary vertex data
  106709. var tempVertexData = new BABYLON.VertexData();
  106710. var primitive = mesh.primitives[i];
  106711. if (primitive.mode !== 4) {
  106712. // continue;
  106713. }
  106714. var attributes = primitive.attributes;
  106715. var accessor = null;
  106716. var buffer = null;
  106717. // Set positions, normal and uvs
  106718. for (var semantic in attributes) {
  106719. // Link accessor and buffer view
  106720. accessor = gltfRuntime.accessors[attributes[semantic]];
  106721. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106722. if (semantic === "NORMAL") {
  106723. tempVertexData.normals = new Float32Array(buffer.length);
  106724. tempVertexData.normals.set(buffer);
  106725. }
  106726. else if (semantic === "POSITION") {
  106727. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106728. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106729. for (var j = 0; j < buffer.length; j += 4) {
  106730. tempVertexData.positions[j] = buffer[j];
  106731. tempVertexData.positions[j + 1] = buffer[j + 1];
  106732. tempVertexData.positions[j + 2] = buffer[j + 2];
  106733. }
  106734. }
  106735. else {
  106736. tempVertexData.positions = new Float32Array(buffer.length);
  106737. tempVertexData.positions.set(buffer);
  106738. }
  106739. verticesCounts.push(tempVertexData.positions.length);
  106740. }
  106741. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106742. var channel = Number(semantic.split("_")[1]);
  106743. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106744. var uvs = new Float32Array(buffer.length);
  106745. uvs.set(buffer);
  106746. normalizeUVs(uvs);
  106747. tempVertexData.set(uvs, uvKind);
  106748. }
  106749. else if (semantic === "JOINT") {
  106750. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106751. tempVertexData.matricesIndices.set(buffer);
  106752. }
  106753. else if (semantic === "WEIGHT") {
  106754. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106755. tempVertexData.matricesWeights.set(buffer);
  106756. }
  106757. else if (semantic === "COLOR") {
  106758. tempVertexData.colors = new Float32Array(buffer.length);
  106759. tempVertexData.colors.set(buffer);
  106760. }
  106761. }
  106762. // Indices
  106763. accessor = gltfRuntime.accessors[primitive.indices];
  106764. if (accessor) {
  106765. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106766. tempVertexData.indices = new Int32Array(buffer.length);
  106767. tempVertexData.indices.set(buffer);
  106768. indexCounts.push(tempVertexData.indices.length);
  106769. }
  106770. else {
  106771. // Set indices on the fly
  106772. var indices = [];
  106773. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106774. indices.push(j);
  106775. }
  106776. tempVertexData.indices = new Int32Array(indices);
  106777. indexCounts.push(tempVertexData.indices.length);
  106778. }
  106779. if (!vertexData) {
  106780. vertexData = tempVertexData;
  106781. }
  106782. else {
  106783. vertexData.merge(tempVertexData);
  106784. }
  106785. // Sub material
  106786. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106787. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106788. // Update vertices start and index start
  106789. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106790. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106791. }
  106792. }
  106793. var material;
  106794. if (subMaterials.length > 1) {
  106795. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106796. material.subMaterials = subMaterials;
  106797. }
  106798. else {
  106799. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106800. }
  106801. if (subMaterials.length === 1) {
  106802. material = subMaterials[0];
  106803. }
  106804. if (!newMesh.material) {
  106805. newMesh.material = material;
  106806. }
  106807. // Apply geometry
  106808. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106809. newMesh.computeWorldMatrix(true);
  106810. // Apply submeshes
  106811. newMesh.subMeshes = [];
  106812. var index = 0;
  106813. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106814. var meshID = meshes[meshIndex];
  106815. var mesh = gltfRuntime.meshes[meshID];
  106816. if (!mesh) {
  106817. continue;
  106818. }
  106819. for (var i = 0; i < mesh.primitives.length; i++) {
  106820. if (mesh.primitives[i].mode !== 4) {
  106821. //continue;
  106822. }
  106823. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106824. index++;
  106825. }
  106826. }
  106827. // Finish
  106828. return newMesh;
  106829. };
  106830. /**
  106831. * Configure node transformation from position, rotation and scaling
  106832. */
  106833. var configureNode = function (newNode, position, rotation, scaling) {
  106834. if (newNode.position) {
  106835. newNode.position = position;
  106836. }
  106837. if (newNode.rotationQuaternion || newNode.rotation) {
  106838. newNode.rotationQuaternion = rotation;
  106839. }
  106840. if (newNode.scaling) {
  106841. newNode.scaling = scaling;
  106842. }
  106843. };
  106844. /**
  106845. * Configures node from transformation matrix
  106846. */
  106847. var configureNodeFromMatrix = function (newNode, node, parent) {
  106848. if (node.matrix) {
  106849. var position = new BABYLON.Vector3(0, 0, 0);
  106850. var rotation = new BABYLON.Quaternion();
  106851. var scaling = new BABYLON.Vector3(0, 0, 0);
  106852. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106853. mat.decompose(scaling, rotation, position);
  106854. configureNode(newNode, position, rotation, scaling);
  106855. }
  106856. else if (node.translation && node.rotation && node.scale) {
  106857. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106858. }
  106859. newNode.computeWorldMatrix(true);
  106860. };
  106861. /**
  106862. * Imports a node
  106863. */
  106864. var importNode = function (gltfRuntime, node, id, parent) {
  106865. var lastNode = null;
  106866. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106867. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106868. return null;
  106869. }
  106870. }
  106871. // Meshes
  106872. if (node.skin) {
  106873. if (node.meshes) {
  106874. var skin = gltfRuntime.skins[node.skin];
  106875. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106876. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106877. if (newMesh.skeleton === null) {
  106878. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106879. if (!skin.babylonSkeleton) {
  106880. skin.babylonSkeleton = newMesh.skeleton;
  106881. }
  106882. }
  106883. lastNode = newMesh;
  106884. }
  106885. }
  106886. else if (node.meshes) {
  106887. /**
  106888. * Improve meshes property
  106889. */
  106890. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106891. lastNode = newMesh;
  106892. }
  106893. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106894. var light = gltfRuntime.lights[node.light];
  106895. if (light) {
  106896. if (light.type === "ambient") {
  106897. var ambienLight = light[light.type];
  106898. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106899. hemiLight.name = node.name || "";
  106900. if (ambienLight.color) {
  106901. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106902. }
  106903. lastNode = hemiLight;
  106904. }
  106905. else if (light.type === "directional") {
  106906. var directionalLight = light[light.type];
  106907. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106908. dirLight.name = node.name || "";
  106909. if (directionalLight.color) {
  106910. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106911. }
  106912. lastNode = dirLight;
  106913. }
  106914. else if (light.type === "point") {
  106915. var pointLight = light[light.type];
  106916. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106917. ptLight.name = node.name || "";
  106918. if (pointLight.color) {
  106919. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106920. }
  106921. lastNode = ptLight;
  106922. }
  106923. else if (light.type === "spot") {
  106924. var spotLight = light[light.type];
  106925. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106926. spLight.name = node.name || "";
  106927. if (spotLight.color) {
  106928. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106929. }
  106930. if (spotLight.fallOfAngle) {
  106931. spLight.angle = spotLight.fallOfAngle;
  106932. }
  106933. if (spotLight.fallOffExponent) {
  106934. spLight.exponent = spotLight.fallOffExponent;
  106935. }
  106936. lastNode = spLight;
  106937. }
  106938. }
  106939. }
  106940. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106941. var camera = gltfRuntime.cameras[node.camera];
  106942. if (camera) {
  106943. if (camera.type === "orthographic") {
  106944. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106945. orthoCamera.name = node.name || "";
  106946. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106947. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106948. lastNode = orthoCamera;
  106949. }
  106950. else if (camera.type === "perspective") {
  106951. var perspectiveCamera = camera[camera.type];
  106952. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106953. persCamera.name = node.name || "";
  106954. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106955. if (!perspectiveCamera.aspectRatio) {
  106956. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106957. }
  106958. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106959. persCamera.maxZ = perspectiveCamera.zfar;
  106960. persCamera.minZ = perspectiveCamera.znear;
  106961. }
  106962. lastNode = persCamera;
  106963. }
  106964. }
  106965. }
  106966. // Empty node
  106967. if (!node.jointName) {
  106968. if (node.babylonNode) {
  106969. return node.babylonNode;
  106970. }
  106971. else if (lastNode === null) {
  106972. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106973. node.babylonNode = dummy;
  106974. lastNode = dummy;
  106975. }
  106976. }
  106977. if (lastNode !== null) {
  106978. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106979. configureNodeFromMatrix(lastNode, node, parent);
  106980. }
  106981. else {
  106982. var translation = node.translation || [0, 0, 0];
  106983. var rotation = node.rotation || [0, 0, 0, 1];
  106984. var scale = node.scale || [1, 1, 1];
  106985. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106986. }
  106987. lastNode.updateCache(true);
  106988. node.babylonNode = lastNode;
  106989. }
  106990. return lastNode;
  106991. };
  106992. /**
  106993. * Traverses nodes and creates them
  106994. */
  106995. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106996. if (meshIncluded === void 0) { meshIncluded = false; }
  106997. var node = gltfRuntime.nodes[id];
  106998. var newNode = null;
  106999. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107000. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107001. meshIncluded = true;
  107002. }
  107003. else {
  107004. meshIncluded = false;
  107005. }
  107006. }
  107007. else {
  107008. meshIncluded = true;
  107009. }
  107010. if (!node.jointName && meshIncluded) {
  107011. newNode = importNode(gltfRuntime, node, id, parent);
  107012. if (newNode !== null) {
  107013. newNode.id = id;
  107014. newNode.parent = parent;
  107015. }
  107016. }
  107017. if (node.children) {
  107018. for (var i = 0; i < node.children.length; i++) {
  107019. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107020. }
  107021. }
  107022. };
  107023. /**
  107024. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107025. */
  107026. var postLoad = function (gltfRuntime) {
  107027. // Nodes
  107028. var currentScene = gltfRuntime.currentScene;
  107029. if (currentScene) {
  107030. for (var i = 0; i < currentScene.nodes.length; i++) {
  107031. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107032. }
  107033. }
  107034. else {
  107035. for (var thing in gltfRuntime.scenes) {
  107036. currentScene = gltfRuntime.scenes[thing];
  107037. for (var i = 0; i < currentScene.nodes.length; i++) {
  107038. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107039. }
  107040. }
  107041. }
  107042. // Set animations
  107043. loadAnimations(gltfRuntime);
  107044. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107045. var skeleton = gltfRuntime.scene.skeletons[i];
  107046. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107047. }
  107048. };
  107049. /**
  107050. * onBind shaderrs callback to set uniforms and matrices
  107051. */
  107052. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107053. var materialValues = material.values || technique.parameters;
  107054. for (var unif in unTreatedUniforms) {
  107055. var uniform = unTreatedUniforms[unif];
  107056. var type = uniform.type;
  107057. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107058. if (uniform.semantic && !uniform.source && !uniform.node) {
  107059. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107060. }
  107061. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107062. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107063. if (source === null) {
  107064. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107065. }
  107066. if (source === null) {
  107067. continue;
  107068. }
  107069. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107070. }
  107071. }
  107072. else {
  107073. var value = materialValues[technique.uniforms[unif]];
  107074. if (!value) {
  107075. continue;
  107076. }
  107077. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107078. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107079. if (texture === null || texture === undefined) {
  107080. continue;
  107081. }
  107082. shaderMaterial.getEffect().setTexture(unif, texture);
  107083. }
  107084. else {
  107085. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107086. }
  107087. }
  107088. }
  107089. onSuccess(shaderMaterial);
  107090. };
  107091. /**
  107092. * Prepare uniforms to send the only one time
  107093. * Loads the appropriate textures
  107094. */
  107095. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107096. var materialValues = material.values || technique.parameters;
  107097. var techniqueUniforms = technique.uniforms;
  107098. /**
  107099. * Prepare values here (not matrices)
  107100. */
  107101. for (var unif in unTreatedUniforms) {
  107102. var uniform = unTreatedUniforms[unif];
  107103. var type = uniform.type;
  107104. var value = materialValues[techniqueUniforms[unif]];
  107105. if (value === undefined) {
  107106. // In case the value is the same for all materials
  107107. value = uniform.value;
  107108. }
  107109. if (!value) {
  107110. continue;
  107111. }
  107112. var onLoadTexture = function (uniformName) {
  107113. return function (texture) {
  107114. if (uniform.value && uniformName) {
  107115. // Static uniform
  107116. shaderMaterial.setTexture(uniformName, texture);
  107117. delete unTreatedUniforms[uniformName];
  107118. }
  107119. };
  107120. };
  107121. // Texture (sampler2D)
  107122. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107123. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107124. }
  107125. else {
  107126. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107127. // Static uniform
  107128. delete unTreatedUniforms[unif];
  107129. }
  107130. }
  107131. }
  107132. };
  107133. /**
  107134. * Shader compilation failed
  107135. */
  107136. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107137. return function (effect, error) {
  107138. shaderMaterial.dispose(true);
  107139. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107140. };
  107141. };
  107142. /**
  107143. * Shader compilation success
  107144. */
  107145. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107146. return function (_) {
  107147. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107148. shaderMaterial.onBind = function (mesh) {
  107149. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107150. };
  107151. };
  107152. };
  107153. /**
  107154. * Returns the appropriate uniform if already handled by babylon
  107155. */
  107156. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107157. for (var unif in technique.uniforms) {
  107158. var uniform = technique.uniforms[unif];
  107159. var uniformParameter = technique.parameters[uniform];
  107160. if (tokenizer.currentIdentifier === unif) {
  107161. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107162. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107163. if (transformIndex !== -1) {
  107164. delete unTreatedUniforms[unif];
  107165. return babylonTransforms[transformIndex];
  107166. }
  107167. }
  107168. }
  107169. }
  107170. return tokenizer.currentIdentifier;
  107171. };
  107172. /**
  107173. * All shaders loaded. Create materials one by one
  107174. */
  107175. var importMaterials = function (gltfRuntime) {
  107176. // Create materials
  107177. for (var mat in gltfRuntime.materials) {
  107178. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107179. }
  107180. };
  107181. /**
  107182. * Implementation of the base glTF spec
  107183. */
  107184. var GLTFLoaderBase = /** @class */ (function () {
  107185. function GLTFLoaderBase() {
  107186. }
  107187. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107188. var gltfRuntime = {
  107189. extensions: {},
  107190. accessors: {},
  107191. buffers: {},
  107192. bufferViews: {},
  107193. meshes: {},
  107194. lights: {},
  107195. cameras: {},
  107196. nodes: {},
  107197. images: {},
  107198. textures: {},
  107199. shaders: {},
  107200. programs: {},
  107201. samplers: {},
  107202. techniques: {},
  107203. materials: {},
  107204. animations: {},
  107205. skins: {},
  107206. extensionsUsed: [],
  107207. scenes: {},
  107208. buffersCount: 0,
  107209. shaderscount: 0,
  107210. scene: scene,
  107211. rootUrl: rootUrl,
  107212. loadedBufferCount: 0,
  107213. loadedBufferViews: {},
  107214. loadedShaderCount: 0,
  107215. importOnlyMeshes: false,
  107216. dummyNodes: []
  107217. };
  107218. // Parse
  107219. if (parsedData.extensions) {
  107220. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107221. }
  107222. if (parsedData.extensionsUsed) {
  107223. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107224. }
  107225. if (parsedData.buffers) {
  107226. parseBuffers(parsedData.buffers, gltfRuntime);
  107227. }
  107228. if (parsedData.bufferViews) {
  107229. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107230. }
  107231. if (parsedData.accessors) {
  107232. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107233. }
  107234. if (parsedData.meshes) {
  107235. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107236. }
  107237. if (parsedData.lights) {
  107238. parseObject(parsedData.lights, "lights", gltfRuntime);
  107239. }
  107240. if (parsedData.cameras) {
  107241. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107242. }
  107243. if (parsedData.nodes) {
  107244. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107245. }
  107246. if (parsedData.images) {
  107247. parseObject(parsedData.images, "images", gltfRuntime);
  107248. }
  107249. if (parsedData.textures) {
  107250. parseObject(parsedData.textures, "textures", gltfRuntime);
  107251. }
  107252. if (parsedData.shaders) {
  107253. parseShaders(parsedData.shaders, gltfRuntime);
  107254. }
  107255. if (parsedData.programs) {
  107256. parseObject(parsedData.programs, "programs", gltfRuntime);
  107257. }
  107258. if (parsedData.samplers) {
  107259. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107260. }
  107261. if (parsedData.techniques) {
  107262. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107263. }
  107264. if (parsedData.materials) {
  107265. parseObject(parsedData.materials, "materials", gltfRuntime);
  107266. }
  107267. if (parsedData.animations) {
  107268. parseObject(parsedData.animations, "animations", gltfRuntime);
  107269. }
  107270. if (parsedData.skins) {
  107271. parseObject(parsedData.skins, "skins", gltfRuntime);
  107272. }
  107273. if (parsedData.scenes) {
  107274. gltfRuntime.scenes = parsedData.scenes;
  107275. }
  107276. if (parsedData.scene && parsedData.scenes) {
  107277. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107278. }
  107279. return gltfRuntime;
  107280. };
  107281. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107282. var buffer = gltfRuntime.buffers[id];
  107283. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107284. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107285. }
  107286. else {
  107287. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107288. if (request) {
  107289. onError(request.status + " " + request.statusText);
  107290. }
  107291. });
  107292. }
  107293. };
  107294. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107295. var texture = gltfRuntime.textures[id];
  107296. if (!texture || !texture.source) {
  107297. onError("");
  107298. return;
  107299. }
  107300. if (texture.babylonTexture) {
  107301. onSuccess(null);
  107302. return;
  107303. }
  107304. var source = gltfRuntime.images[texture.source];
  107305. if (BABYLON.Tools.IsBase64(source.uri)) {
  107306. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107307. }
  107308. else {
  107309. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107310. if (request) {
  107311. onError(request.status + " " + request.statusText);
  107312. }
  107313. });
  107314. }
  107315. };
  107316. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107317. var texture = gltfRuntime.textures[id];
  107318. if (texture.babylonTexture) {
  107319. onSuccess(texture.babylonTexture);
  107320. return;
  107321. }
  107322. var sampler = gltfRuntime.samplers[texture.sampler];
  107323. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107324. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107325. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107326. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107327. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107328. var blob = new Blob([buffer]);
  107329. var blobURL = URL.createObjectURL(blob);
  107330. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107331. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107332. if (sampler.wrapS !== undefined) {
  107333. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107334. }
  107335. if (sampler.wrapT !== undefined) {
  107336. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107337. }
  107338. newTexture.name = id;
  107339. texture.babylonTexture = newTexture;
  107340. onSuccess(newTexture);
  107341. };
  107342. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107343. var shader = gltfRuntime.shaders[id];
  107344. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107345. var shaderString = atob(shader.uri.split(",")[1]);
  107346. onSuccess(shaderString);
  107347. }
  107348. else {
  107349. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107350. if (request) {
  107351. onError(request.status + " " + request.statusText);
  107352. }
  107353. });
  107354. }
  107355. };
  107356. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107357. var material = gltfRuntime.materials[id];
  107358. if (!material.technique) {
  107359. if (onError) {
  107360. onError("No technique found.");
  107361. }
  107362. return;
  107363. }
  107364. var technique = gltfRuntime.techniques[material.technique];
  107365. if (!technique) {
  107366. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107367. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107368. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107369. onSuccess(defaultMaterial);
  107370. return;
  107371. }
  107372. var program = gltfRuntime.programs[technique.program];
  107373. var states = technique.states;
  107374. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107375. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107376. var newVertexShader = "";
  107377. var newPixelShader = "";
  107378. var vertexTokenizer = new Tokenizer(vertexShader);
  107379. var pixelTokenizer = new Tokenizer(pixelShader);
  107380. var unTreatedUniforms = {};
  107381. var uniforms = [];
  107382. var attributes = [];
  107383. var samplers = [];
  107384. // Fill uniform, sampler2D and attributes
  107385. for (var unif in technique.uniforms) {
  107386. var uniform = technique.uniforms[unif];
  107387. var uniformParameter = technique.parameters[uniform];
  107388. unTreatedUniforms[unif] = uniformParameter;
  107389. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107390. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107391. if (transformIndex !== -1) {
  107392. uniforms.push(babylonTransforms[transformIndex]);
  107393. delete unTreatedUniforms[unif];
  107394. }
  107395. else {
  107396. uniforms.push(unif);
  107397. }
  107398. }
  107399. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107400. samplers.push(unif);
  107401. }
  107402. else {
  107403. uniforms.push(unif);
  107404. }
  107405. }
  107406. for (var attr in technique.attributes) {
  107407. var attribute = technique.attributes[attr];
  107408. var attributeParameter = technique.parameters[attribute];
  107409. if (attributeParameter.semantic) {
  107410. attributes.push(getAttribute(attributeParameter));
  107411. }
  107412. }
  107413. // Configure vertex shader
  107414. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107415. var tokenType = vertexTokenizer.currentToken;
  107416. if (tokenType !== ETokenType.IDENTIFIER) {
  107417. newVertexShader += vertexTokenizer.currentString;
  107418. continue;
  107419. }
  107420. var foundAttribute = false;
  107421. for (var attr in technique.attributes) {
  107422. var attribute = technique.attributes[attr];
  107423. var attributeParameter = technique.parameters[attribute];
  107424. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107425. newVertexShader += getAttribute(attributeParameter);
  107426. foundAttribute = true;
  107427. break;
  107428. }
  107429. }
  107430. if (foundAttribute) {
  107431. continue;
  107432. }
  107433. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107434. }
  107435. // Configure pixel shader
  107436. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107437. var tokenType = pixelTokenizer.currentToken;
  107438. if (tokenType !== ETokenType.IDENTIFIER) {
  107439. newPixelShader += pixelTokenizer.currentString;
  107440. continue;
  107441. }
  107442. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107443. }
  107444. // Create shader material
  107445. var shaderPath = {
  107446. vertex: program.vertexShader + id,
  107447. fragment: program.fragmentShader + id
  107448. };
  107449. var options = {
  107450. attributes: attributes,
  107451. uniforms: uniforms,
  107452. samplers: samplers,
  107453. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107454. };
  107455. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107456. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107457. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107458. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107459. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107460. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107461. if (states && states.functions) {
  107462. var functions = states.functions;
  107463. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107464. shaderMaterial.backFaceCulling = false;
  107465. }
  107466. var blendFunc = functions.blendFuncSeparate;
  107467. if (blendFunc) {
  107468. 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) {
  107469. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107470. }
  107471. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107472. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107473. }
  107474. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107475. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107476. }
  107477. 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) {
  107478. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107479. }
  107480. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107481. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107482. }
  107483. 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) {
  107484. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107485. }
  107486. }
  107487. }
  107488. };
  107489. return GLTFLoaderBase;
  107490. }());
  107491. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107492. /**
  107493. * glTF V1 Loader
  107494. */
  107495. var GLTFLoader = /** @class */ (function () {
  107496. function GLTFLoader() {
  107497. // #region Stubs for IGLTFLoader interface
  107498. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107499. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107500. this.compileMaterials = false;
  107501. this.useClipPlane = false;
  107502. this.compileShadowGenerators = false;
  107503. this.onDisposeObservable = new BABYLON.Observable();
  107504. this.onMeshLoadedObservable = new BABYLON.Observable();
  107505. this.onTextureLoadedObservable = new BABYLON.Observable();
  107506. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107507. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107508. this.onCompleteObservable = new BABYLON.Observable();
  107509. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107510. this.state = null;
  107511. }
  107512. GLTFLoader.RegisterExtension = function (extension) {
  107513. if (GLTFLoader.Extensions[extension.name]) {
  107514. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107515. return;
  107516. }
  107517. GLTFLoader.Extensions[extension.name] = extension;
  107518. };
  107519. GLTFLoader.prototype.dispose = function () { };
  107520. // #endregion
  107521. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107522. var _this = this;
  107523. scene.useRightHandedSystem = true;
  107524. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107525. gltfRuntime.importOnlyMeshes = true;
  107526. if (meshesNames === "") {
  107527. gltfRuntime.importMeshesNames = [];
  107528. }
  107529. else if (typeof meshesNames === "string") {
  107530. gltfRuntime.importMeshesNames = [meshesNames];
  107531. }
  107532. else if (meshesNames && !(meshesNames instanceof Array)) {
  107533. gltfRuntime.importMeshesNames = [meshesNames];
  107534. }
  107535. else {
  107536. gltfRuntime.importMeshesNames = [];
  107537. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107538. }
  107539. // Create nodes
  107540. _this._createNodes(gltfRuntime);
  107541. var meshes = new Array();
  107542. var skeletons = new Array();
  107543. // Fill arrays of meshes and skeletons
  107544. for (var nde in gltfRuntime.nodes) {
  107545. var node = gltfRuntime.nodes[nde];
  107546. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107547. meshes.push(node.babylonNode);
  107548. }
  107549. }
  107550. for (var skl in gltfRuntime.skins) {
  107551. var skin = gltfRuntime.skins[skl];
  107552. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107553. skeletons.push(skin.babylonSkeleton);
  107554. }
  107555. }
  107556. // Load buffers, shaders, materials, etc.
  107557. _this._loadBuffersAsync(gltfRuntime, function () {
  107558. _this._loadShadersAsync(gltfRuntime, function () {
  107559. importMaterials(gltfRuntime);
  107560. postLoad(gltfRuntime);
  107561. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107562. onSuccess(meshes, [], skeletons);
  107563. }
  107564. });
  107565. }, onProgress);
  107566. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107567. onSuccess(meshes, [], skeletons);
  107568. }
  107569. }, onError);
  107570. return true;
  107571. };
  107572. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107573. var _this = this;
  107574. return new Promise(function (resolve, reject) {
  107575. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107576. resolve({
  107577. meshes: meshes,
  107578. particleSystems: particleSystems,
  107579. skeletons: skeletons
  107580. });
  107581. }, onProgress, function (message) {
  107582. reject(new Error(message));
  107583. });
  107584. });
  107585. };
  107586. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107587. var _this = this;
  107588. scene.useRightHandedSystem = true;
  107589. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107590. // Load runtime extensios
  107591. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107592. // Create nodes
  107593. _this._createNodes(gltfRuntime);
  107594. // Load buffers, shaders, materials, etc.
  107595. _this._loadBuffersAsync(gltfRuntime, function () {
  107596. _this._loadShadersAsync(gltfRuntime, function () {
  107597. importMaterials(gltfRuntime);
  107598. postLoad(gltfRuntime);
  107599. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107600. onSuccess();
  107601. }
  107602. });
  107603. });
  107604. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107605. onSuccess();
  107606. }
  107607. }, onError);
  107608. }, onError);
  107609. };
  107610. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107611. var _this = this;
  107612. return new Promise(function (resolve, reject) {
  107613. _this._loadAsync(scene, data, rootUrl, function () {
  107614. resolve();
  107615. }, onProgress, function (message) {
  107616. reject(new Error(message));
  107617. });
  107618. });
  107619. };
  107620. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107621. var hasShaders = false;
  107622. var processShader = function (sha, shader) {
  107623. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107624. gltfRuntime.loadedShaderCount++;
  107625. if (shaderString) {
  107626. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107627. }
  107628. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107629. onload();
  107630. }
  107631. }, function () {
  107632. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107633. });
  107634. };
  107635. for (var sha in gltfRuntime.shaders) {
  107636. hasShaders = true;
  107637. var shader = gltfRuntime.shaders[sha];
  107638. if (shader) {
  107639. processShader.bind(this, sha, shader)();
  107640. }
  107641. else {
  107642. BABYLON.Tools.Error("No shader named: " + sha);
  107643. }
  107644. }
  107645. if (!hasShaders) {
  107646. onload();
  107647. }
  107648. };
  107649. ;
  107650. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107651. var hasBuffers = false;
  107652. var processBuffer = function (buf, buffer) {
  107653. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107654. gltfRuntime.loadedBufferCount++;
  107655. if (bufferView) {
  107656. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107657. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107658. }
  107659. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107660. }
  107661. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107662. onLoad();
  107663. }
  107664. }, function () {
  107665. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107666. });
  107667. };
  107668. for (var buf in gltfRuntime.buffers) {
  107669. hasBuffers = true;
  107670. var buffer = gltfRuntime.buffers[buf];
  107671. if (buffer) {
  107672. processBuffer.bind(this, buf, buffer)();
  107673. }
  107674. else {
  107675. BABYLON.Tools.Error("No buffer named: " + buf);
  107676. }
  107677. }
  107678. if (!hasBuffers) {
  107679. onLoad();
  107680. }
  107681. };
  107682. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107683. var currentScene = gltfRuntime.currentScene;
  107684. if (currentScene) {
  107685. // Only one scene even if multiple scenes are defined
  107686. for (var i = 0; i < currentScene.nodes.length; i++) {
  107687. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107688. }
  107689. }
  107690. else {
  107691. // Load all scenes
  107692. for (var thing in gltfRuntime.scenes) {
  107693. currentScene = gltfRuntime.scenes[thing];
  107694. for (var i = 0; i < currentScene.nodes.length; i++) {
  107695. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107696. }
  107697. }
  107698. }
  107699. };
  107700. GLTFLoader.Extensions = {};
  107701. return GLTFLoader;
  107702. }());
  107703. GLTF1.GLTFLoader = GLTFLoader;
  107704. ;
  107705. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107706. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107707. })(BABYLON || (BABYLON = {}));
  107708. //# sourceMappingURL=babylon.glTFLoader.js.map
  107709. var BABYLON;
  107710. (function (BABYLON) {
  107711. var GLTF1;
  107712. (function (GLTF1) {
  107713. /**
  107714. * Utils functions for GLTF
  107715. */
  107716. var GLTFUtils = /** @class */ (function () {
  107717. function GLTFUtils() {
  107718. }
  107719. /**
  107720. * Sets the given "parameter" matrix
  107721. * @param scene: the {BABYLON.Scene} object
  107722. * @param source: the source node where to pick the matrix
  107723. * @param parameter: the GLTF technique parameter
  107724. * @param uniformName: the name of the shader's uniform
  107725. * @param shaderMaterial: the shader material
  107726. */
  107727. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107728. var mat = null;
  107729. if (parameter.semantic === "MODEL") {
  107730. mat = source.getWorldMatrix();
  107731. }
  107732. else if (parameter.semantic === "PROJECTION") {
  107733. mat = scene.getProjectionMatrix();
  107734. }
  107735. else if (parameter.semantic === "VIEW") {
  107736. mat = scene.getViewMatrix();
  107737. }
  107738. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107739. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107740. }
  107741. else if (parameter.semantic === "MODELVIEW") {
  107742. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107743. }
  107744. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107745. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107746. }
  107747. else if (parameter.semantic === "MODELINVERSE") {
  107748. mat = source.getWorldMatrix().invert();
  107749. }
  107750. else if (parameter.semantic === "VIEWINVERSE") {
  107751. mat = scene.getViewMatrix().invert();
  107752. }
  107753. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107754. mat = scene.getProjectionMatrix().invert();
  107755. }
  107756. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107757. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107758. }
  107759. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107760. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107761. }
  107762. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107763. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107764. }
  107765. else {
  107766. debugger;
  107767. }
  107768. if (mat) {
  107769. switch (parameter.type) {
  107770. case GLTF1.EParameterType.FLOAT_MAT2:
  107771. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107772. break;
  107773. case GLTF1.EParameterType.FLOAT_MAT3:
  107774. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107775. break;
  107776. case GLTF1.EParameterType.FLOAT_MAT4:
  107777. shaderMaterial.setMatrix(uniformName, mat);
  107778. break;
  107779. default: break;
  107780. }
  107781. }
  107782. };
  107783. /**
  107784. * Sets the given "parameter" matrix
  107785. * @param shaderMaterial: the shader material
  107786. * @param uniform: the name of the shader's uniform
  107787. * @param value: the value of the uniform
  107788. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107789. */
  107790. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107791. switch (type) {
  107792. case GLTF1.EParameterType.FLOAT:
  107793. shaderMaterial.setFloat(uniform, value);
  107794. return true;
  107795. case GLTF1.EParameterType.FLOAT_VEC2:
  107796. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107797. return true;
  107798. case GLTF1.EParameterType.FLOAT_VEC3:
  107799. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107800. return true;
  107801. case GLTF1.EParameterType.FLOAT_VEC4:
  107802. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107803. return true;
  107804. default: return false;
  107805. }
  107806. };
  107807. /**
  107808. * Returns the wrap mode of the texture
  107809. * @param mode: the mode value
  107810. */
  107811. GLTFUtils.GetWrapMode = function (mode) {
  107812. switch (mode) {
  107813. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107814. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107815. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107816. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107817. }
  107818. };
  107819. /**
  107820. * Returns the byte stride giving an accessor
  107821. * @param accessor: the GLTF accessor objet
  107822. */
  107823. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107824. // Needs this function since "byteStride" isn't requiered in glTF format
  107825. var type = accessor.type;
  107826. switch (type) {
  107827. case "VEC2": return 2;
  107828. case "VEC3": return 3;
  107829. case "VEC4": return 4;
  107830. case "MAT2": return 4;
  107831. case "MAT3": return 9;
  107832. case "MAT4": return 16;
  107833. default: return 1;
  107834. }
  107835. };
  107836. /**
  107837. * Returns the texture filter mode giving a mode value
  107838. * @param mode: the filter mode value
  107839. */
  107840. GLTFUtils.GetTextureFilterMode = function (mode) {
  107841. switch (mode) {
  107842. case GLTF1.ETextureFilterType.LINEAR:
  107843. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107844. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107845. case GLTF1.ETextureFilterType.NEAREST:
  107846. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107847. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107848. }
  107849. };
  107850. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107851. var byteOffset = bufferView.byteOffset + byteOffset;
  107852. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107853. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107854. throw new Error("Buffer access is out of range");
  107855. }
  107856. var buffer = loadedBufferView.buffer;
  107857. byteOffset += loadedBufferView.byteOffset;
  107858. switch (componentType) {
  107859. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107860. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107861. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107862. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107863. default: return new Float32Array(buffer, byteOffset, byteLength);
  107864. }
  107865. };
  107866. /**
  107867. * Returns a buffer from its accessor
  107868. * @param gltfRuntime: the GLTF runtime
  107869. * @param accessor: the GLTF accessor
  107870. */
  107871. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107872. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107873. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107874. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107875. };
  107876. /**
  107877. * Decodes a buffer view into a string
  107878. * @param view: the buffer view
  107879. */
  107880. GLTFUtils.DecodeBufferToText = function (view) {
  107881. var result = "";
  107882. var length = view.byteLength;
  107883. for (var i = 0; i < length; ++i) {
  107884. result += String.fromCharCode(view[i]);
  107885. }
  107886. return result;
  107887. };
  107888. /**
  107889. * Returns the default material of gltf. Related to
  107890. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107891. * @param scene: the Babylon.js scene
  107892. */
  107893. GLTFUtils.GetDefaultMaterial = function (scene) {
  107894. if (!GLTFUtils._DefaultMaterial) {
  107895. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107896. "precision highp float;",
  107897. "",
  107898. "uniform mat4 worldView;",
  107899. "uniform mat4 projection;",
  107900. "",
  107901. "attribute vec3 position;",
  107902. "",
  107903. "void main(void)",
  107904. "{",
  107905. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107906. "}"
  107907. ].join("\n");
  107908. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107909. "precision highp float;",
  107910. "",
  107911. "uniform vec4 u_emission;",
  107912. "",
  107913. "void main(void)",
  107914. "{",
  107915. " gl_FragColor = u_emission;",
  107916. "}"
  107917. ].join("\n");
  107918. var shaderPath = {
  107919. vertex: "GLTFDefaultMaterial",
  107920. fragment: "GLTFDefaultMaterial"
  107921. };
  107922. var options = {
  107923. attributes: ["position"],
  107924. uniforms: ["worldView", "projection", "u_emission"],
  107925. samplers: new Array(),
  107926. needAlphaBlending: false
  107927. };
  107928. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107929. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107930. }
  107931. return GLTFUtils._DefaultMaterial;
  107932. };
  107933. // The GLTF default material
  107934. GLTFUtils._DefaultMaterial = null;
  107935. return GLTFUtils;
  107936. }());
  107937. GLTF1.GLTFUtils = GLTFUtils;
  107938. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107939. })(BABYLON || (BABYLON = {}));
  107940. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107941. var BABYLON;
  107942. (function (BABYLON) {
  107943. var GLTF1;
  107944. (function (GLTF1) {
  107945. var GLTFLoaderExtension = /** @class */ (function () {
  107946. function GLTFLoaderExtension(name) {
  107947. this._name = name;
  107948. }
  107949. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107950. get: function () {
  107951. return this._name;
  107952. },
  107953. enumerable: true,
  107954. configurable: true
  107955. });
  107956. /**
  107957. * Defines an override for loading the runtime
  107958. * Return true to stop further extensions from loading the runtime
  107959. */
  107960. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107961. return false;
  107962. };
  107963. /**
  107964. * Defines an onverride for creating gltf runtime
  107965. * Return true to stop further extensions from creating the runtime
  107966. */
  107967. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107968. return false;
  107969. };
  107970. /**
  107971. * Defines an override for loading buffers
  107972. * Return true to stop further extensions from loading this buffer
  107973. */
  107974. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107975. return false;
  107976. };
  107977. /**
  107978. * Defines an override for loading texture buffers
  107979. * Return true to stop further extensions from loading this texture data
  107980. */
  107981. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107982. return false;
  107983. };
  107984. /**
  107985. * Defines an override for creating textures
  107986. * Return true to stop further extensions from loading this texture
  107987. */
  107988. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107989. return false;
  107990. };
  107991. /**
  107992. * Defines an override for loading shader strings
  107993. * Return true to stop further extensions from loading this shader data
  107994. */
  107995. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107996. return false;
  107997. };
  107998. /**
  107999. * Defines an override for loading materials
  108000. * Return true to stop further extensions from loading this material
  108001. */
  108002. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108003. return false;
  108004. };
  108005. // ---------
  108006. // Utilities
  108007. // ---------
  108008. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108009. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108010. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108011. }, function () {
  108012. setTimeout(function () {
  108013. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108014. });
  108015. });
  108016. };
  108017. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108018. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108019. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108020. }, function () {
  108021. setTimeout(function () {
  108022. onSuccess();
  108023. });
  108024. });
  108025. };
  108026. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108027. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108028. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108029. }, function () {
  108030. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108031. });
  108032. };
  108033. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108034. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  108035. };
  108036. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108037. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108038. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108039. }, function () {
  108040. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108041. });
  108042. };
  108043. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108044. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108045. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108046. }, function () {
  108047. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108048. });
  108049. };
  108050. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108051. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108052. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108053. }, function () {
  108054. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108055. });
  108056. };
  108057. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108058. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108059. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108060. }, function () {
  108061. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108062. });
  108063. };
  108064. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108065. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108066. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108067. if (func(loaderExtension)) {
  108068. return;
  108069. }
  108070. }
  108071. defaultFunc();
  108072. };
  108073. return GLTFLoaderExtension;
  108074. }());
  108075. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108076. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108077. })(BABYLON || (BABYLON = {}));
  108078. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108079. var BABYLON;
  108080. (function (BABYLON) {
  108081. var GLTF1;
  108082. (function (GLTF1) {
  108083. var BinaryExtensionBufferName = "binary_glTF";
  108084. ;
  108085. ;
  108086. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108087. __extends(GLTFBinaryExtension, _super);
  108088. function GLTFBinaryExtension() {
  108089. return _super.call(this, "KHR_binary_glTF") || this;
  108090. }
  108091. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108092. var extensionsUsed = data.json.extensionsUsed;
  108093. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108094. return false;
  108095. }
  108096. this._bin = data.bin;
  108097. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108098. return true;
  108099. };
  108100. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108101. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108102. return false;
  108103. }
  108104. if (id !== BinaryExtensionBufferName) {
  108105. return false;
  108106. }
  108107. onSuccess(this._bin);
  108108. return true;
  108109. };
  108110. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108111. var texture = gltfRuntime.textures[id];
  108112. var source = gltfRuntime.images[texture.source];
  108113. if (!source.extensions || !(this.name in source.extensions)) {
  108114. return false;
  108115. }
  108116. var sourceExt = source.extensions[this.name];
  108117. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108118. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108119. onSuccess(buffer);
  108120. return true;
  108121. };
  108122. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108123. var shader = gltfRuntime.shaders[id];
  108124. if (!shader.extensions || !(this.name in shader.extensions)) {
  108125. return false;
  108126. }
  108127. var binaryExtensionShader = shader.extensions[this.name];
  108128. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108129. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108130. setTimeout(function () {
  108131. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108132. onSuccess(shaderString);
  108133. });
  108134. return true;
  108135. };
  108136. return GLTFBinaryExtension;
  108137. }(GLTF1.GLTFLoaderExtension));
  108138. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108139. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108140. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108141. })(BABYLON || (BABYLON = {}));
  108142. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108143. var BABYLON;
  108144. (function (BABYLON) {
  108145. var GLTF1;
  108146. (function (GLTF1) {
  108147. ;
  108148. ;
  108149. ;
  108150. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108151. __extends(GLTFMaterialsCommonExtension, _super);
  108152. function GLTFMaterialsCommonExtension() {
  108153. return _super.call(this, "KHR_materials_common") || this;
  108154. }
  108155. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108156. if (!gltfRuntime.extensions)
  108157. return false;
  108158. var extension = gltfRuntime.extensions[this.name];
  108159. if (!extension)
  108160. return false;
  108161. // Create lights
  108162. var lights = extension.lights;
  108163. if (lights) {
  108164. for (var thing in lights) {
  108165. var light = lights[thing];
  108166. switch (light.type) {
  108167. case "ambient":
  108168. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108169. var ambient = light.ambient;
  108170. if (ambient) {
  108171. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108172. }
  108173. break;
  108174. case "point":
  108175. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108176. var point = light.point;
  108177. if (point) {
  108178. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108179. }
  108180. break;
  108181. case "directional":
  108182. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108183. var directional = light.directional;
  108184. if (directional) {
  108185. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108186. }
  108187. break;
  108188. case "spot":
  108189. var spot = light.spot;
  108190. if (spot) {
  108191. 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);
  108192. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108193. }
  108194. break;
  108195. default:
  108196. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108197. break;
  108198. }
  108199. }
  108200. }
  108201. return false;
  108202. };
  108203. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108204. var material = gltfRuntime.materials[id];
  108205. if (!material || !material.extensions)
  108206. return false;
  108207. var extension = material.extensions[this.name];
  108208. if (!extension)
  108209. return false;
  108210. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108211. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108212. if (extension.technique === "CONSTANT") {
  108213. standardMaterial.disableLighting = true;
  108214. }
  108215. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108216. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108217. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108218. // Ambient
  108219. if (typeof extension.values.ambient === "string") {
  108220. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108221. }
  108222. else {
  108223. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108224. }
  108225. // Diffuse
  108226. if (typeof extension.values.diffuse === "string") {
  108227. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108228. }
  108229. else {
  108230. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108231. }
  108232. // Emission
  108233. if (typeof extension.values.emission === "string") {
  108234. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108235. }
  108236. else {
  108237. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108238. }
  108239. // Specular
  108240. if (typeof extension.values.specular === "string") {
  108241. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108242. }
  108243. else {
  108244. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108245. }
  108246. return true;
  108247. };
  108248. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108249. // Create buffer from texture url
  108250. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108251. // Create texture from buffer
  108252. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108253. }, onError);
  108254. };
  108255. return GLTFMaterialsCommonExtension;
  108256. }(GLTF1.GLTFLoaderExtension));
  108257. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108258. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108259. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108260. })(BABYLON || (BABYLON = {}));
  108261. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108262. var BABYLON;
  108263. (function (BABYLON) {
  108264. var GLTF2;
  108265. (function (GLTF2) {
  108266. var ArrayItem = /** @class */ (function () {
  108267. function ArrayItem() {
  108268. }
  108269. ArrayItem.Assign = function (values) {
  108270. if (values) {
  108271. for (var index = 0; index < values.length; index++) {
  108272. values[index]._index = index;
  108273. }
  108274. }
  108275. };
  108276. return ArrayItem;
  108277. }());
  108278. GLTF2.ArrayItem = ArrayItem;
  108279. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108280. })(BABYLON || (BABYLON = {}));
  108281. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108282. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108283. var BABYLON;
  108284. (function (BABYLON) {
  108285. var GLTF2;
  108286. (function (GLTF2) {
  108287. var GLTFLoader = /** @class */ (function () {
  108288. function GLTFLoader() {
  108289. this._completePromises = new Array();
  108290. this._disposed = false;
  108291. this._state = null;
  108292. this._extensions = {};
  108293. this._defaultSampler = {};
  108294. this._requests = new Array();
  108295. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108296. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108297. this.compileMaterials = false;
  108298. this.useClipPlane = false;
  108299. this.compileShadowGenerators = false;
  108300. this.onDisposeObservable = new BABYLON.Observable();
  108301. this.onMeshLoadedObservable = new BABYLON.Observable();
  108302. this.onTextureLoadedObservable = new BABYLON.Observable();
  108303. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108304. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108305. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108306. this.onCompleteObservable = new BABYLON.Observable();
  108307. }
  108308. GLTFLoader._Register = function (name, factory) {
  108309. if (GLTFLoader._Factories[name]) {
  108310. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108311. return;
  108312. }
  108313. GLTFLoader._Factories[name] = factory;
  108314. // Keep the order of registration so that extensions registered first are called first.
  108315. GLTFLoader._Names.push(name);
  108316. };
  108317. Object.defineProperty(GLTFLoader.prototype, "state", {
  108318. get: function () {
  108319. return this._state;
  108320. },
  108321. enumerable: true,
  108322. configurable: true
  108323. });
  108324. GLTFLoader.prototype.dispose = function () {
  108325. if (this._disposed) {
  108326. return;
  108327. }
  108328. this._disposed = true;
  108329. this.onDisposeObservable.notifyObservers(this);
  108330. this.onDisposeObservable.clear();
  108331. this._clear();
  108332. };
  108333. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108334. var _this = this;
  108335. return Promise.resolve().then(function () {
  108336. var nodes = null;
  108337. if (meshesNames) {
  108338. var nodeMap_1 = {};
  108339. if (_this._gltf.nodes) {
  108340. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108341. var node = _a[_i];
  108342. if (node.name) {
  108343. nodeMap_1[node.name] = node;
  108344. }
  108345. }
  108346. }
  108347. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108348. nodes = names.map(function (name) {
  108349. var node = nodeMap_1[name];
  108350. if (!node) {
  108351. throw new Error("Failed to find node '" + name + "'");
  108352. }
  108353. return node;
  108354. });
  108355. }
  108356. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108357. return {
  108358. meshes: _this._getMeshes(),
  108359. particleSystems: [],
  108360. skeletons: _this._getSkeletons(),
  108361. };
  108362. });
  108363. });
  108364. };
  108365. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108366. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108367. };
  108368. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108369. var _this = this;
  108370. return Promise.resolve().then(function () {
  108371. _this._loadExtensions();
  108372. _this._babylonScene = scene;
  108373. _this._rootUrl = rootUrl;
  108374. _this._progressCallback = onProgress;
  108375. _this._state = BABYLON.GLTFLoaderState.Loading;
  108376. _this._loadData(data);
  108377. _this._checkExtensions();
  108378. var promises = new Array();
  108379. if (nodes) {
  108380. promises.push(_this._loadNodesAsync(nodes));
  108381. }
  108382. else {
  108383. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108384. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108385. }
  108386. if (_this.compileMaterials) {
  108387. promises.push(_this._compileMaterialsAsync());
  108388. }
  108389. if (_this.compileShadowGenerators) {
  108390. promises.push(_this._compileShadowGeneratorsAsync());
  108391. }
  108392. var resultPromise = Promise.all(promises).then(function () {
  108393. _this._state = BABYLON.GLTFLoaderState.Ready;
  108394. _this._startAnimations();
  108395. });
  108396. resultPromise.then(function () {
  108397. _this._rootBabylonMesh.setEnabled(true);
  108398. BABYLON.Tools.SetImmediate(function () {
  108399. if (!_this._disposed) {
  108400. Promise.all(_this._completePromises).then(function () {
  108401. _this._state = BABYLON.GLTFLoaderState.Complete;
  108402. _this.onCompleteObservable.notifyObservers(_this);
  108403. _this.onCompleteObservable.clear();
  108404. _this._clear();
  108405. }).catch(function (error) {
  108406. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108407. _this._clear();
  108408. });
  108409. }
  108410. });
  108411. });
  108412. return resultPromise;
  108413. }).catch(function (error) {
  108414. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108415. _this._clear();
  108416. throw error;
  108417. });
  108418. };
  108419. GLTFLoader.prototype._loadExtensions = function () {
  108420. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108421. var name_1 = _a[_i];
  108422. var extension = GLTFLoader._Factories[name_1](this);
  108423. this._extensions[name_1] = extension;
  108424. this.onExtensionLoadedObservable.notifyObservers(extension);
  108425. }
  108426. this.onExtensionLoadedObservable.clear();
  108427. };
  108428. GLTFLoader.prototype._loadData = function (data) {
  108429. this._gltf = data.json;
  108430. this._setupData();
  108431. if (data.bin) {
  108432. var buffers = this._gltf.buffers;
  108433. if (buffers && buffers[0] && !buffers[0].uri) {
  108434. var binaryBuffer = buffers[0];
  108435. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108436. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108437. }
  108438. binaryBuffer._data = Promise.resolve(data.bin);
  108439. }
  108440. else {
  108441. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108442. }
  108443. }
  108444. };
  108445. GLTFLoader.prototype._setupData = function () {
  108446. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108447. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108448. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108449. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108450. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108451. GLTF2.ArrayItem.Assign(this._gltf.images);
  108452. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108453. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108454. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108455. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108456. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108457. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108458. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108459. if (this._gltf.nodes) {
  108460. var nodeParents = {};
  108461. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108462. var node = _a[_i];
  108463. if (node.children) {
  108464. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108465. var index = _c[_b];
  108466. nodeParents[index] = node._index;
  108467. }
  108468. }
  108469. }
  108470. var rootNode = this._createRootNode();
  108471. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108472. var node = _e[_d];
  108473. var parentIndex = nodeParents[node._index];
  108474. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108475. }
  108476. }
  108477. };
  108478. GLTFLoader.prototype._checkExtensions = function () {
  108479. if (this._gltf.extensionsRequired) {
  108480. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108481. var name_2 = _a[_i];
  108482. var extension = this._extensions[name_2];
  108483. if (!extension || !extension.enabled) {
  108484. throw new Error("Require extension " + name_2 + " is not available");
  108485. }
  108486. }
  108487. }
  108488. };
  108489. GLTFLoader.prototype._createRootNode = function () {
  108490. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108491. this._rootBabylonMesh.setEnabled(false);
  108492. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108493. switch (this.coordinateSystemMode) {
  108494. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108495. if (!this._babylonScene.useRightHandedSystem) {
  108496. rootNode.rotation = [0, 1, 0, 0];
  108497. rootNode.scale = [1, 1, -1];
  108498. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108499. }
  108500. break;
  108501. }
  108502. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108503. this._babylonScene.useRightHandedSystem = true;
  108504. break;
  108505. }
  108506. default: {
  108507. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108508. }
  108509. }
  108510. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108511. return rootNode;
  108512. };
  108513. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108514. var promises = new Array();
  108515. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108516. var node = nodes_1[_i];
  108517. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108518. }
  108519. promises.push(this._loadAnimationsAsync());
  108520. return Promise.all(promises).then(function () { });
  108521. };
  108522. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108523. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108524. if (promise) {
  108525. return promise;
  108526. }
  108527. var promises = new Array();
  108528. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108529. var index = _a[_i];
  108530. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108531. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108532. }
  108533. promises.push(this._loadAnimationsAsync());
  108534. return Promise.all(promises).then(function () { });
  108535. };
  108536. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  108537. if (node._babylonMesh) {
  108538. callback(node._babylonMesh);
  108539. }
  108540. if (node._primitiveBabylonMeshes) {
  108541. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108542. var babylonMesh = _a[_i];
  108543. callback(babylonMesh);
  108544. }
  108545. }
  108546. };
  108547. GLTFLoader.prototype._getMeshes = function () {
  108548. var meshes = new Array();
  108549. // Root mesh is always first.
  108550. meshes.push(this._rootBabylonMesh);
  108551. var nodes = this._gltf.nodes;
  108552. if (nodes) {
  108553. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108554. var node = nodes_2[_i];
  108555. this._forEachNodeMesh(node, function (mesh) {
  108556. meshes.push(mesh);
  108557. });
  108558. }
  108559. }
  108560. return meshes;
  108561. };
  108562. GLTFLoader.prototype._getSkeletons = function () {
  108563. var skeletons = new Array();
  108564. var skins = this._gltf.skins;
  108565. if (skins) {
  108566. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108567. var skin = skins_1[_i];
  108568. if (skin._babylonSkeleton) {
  108569. skeletons.push(skin._babylonSkeleton);
  108570. }
  108571. }
  108572. }
  108573. return skeletons;
  108574. };
  108575. GLTFLoader.prototype._startAnimations = function () {
  108576. var animations = this._gltf.animations;
  108577. if (!animations) {
  108578. return;
  108579. }
  108580. switch (this.animationStartMode) {
  108581. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108582. // do nothing
  108583. break;
  108584. }
  108585. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108586. var animation = animations[0];
  108587. animation._babylonAnimationGroup.start(true);
  108588. break;
  108589. }
  108590. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108591. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108592. var animation = animations_1[_i];
  108593. animation._babylonAnimationGroup.start(true);
  108594. }
  108595. break;
  108596. }
  108597. default: {
  108598. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108599. return;
  108600. }
  108601. }
  108602. };
  108603. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108604. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108605. if (promise) {
  108606. return promise;
  108607. }
  108608. if (node._babylonMesh) {
  108609. throw new Error(context + ": Invalid recursive node hierarchy");
  108610. }
  108611. var promises = new Array();
  108612. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108613. node._babylonMesh = babylonMesh;
  108614. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108615. node._babylonAnimationTargets.push(babylonMesh);
  108616. GLTFLoader._LoadTransform(node, babylonMesh);
  108617. if (node.mesh != undefined) {
  108618. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108619. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108620. }
  108621. if (node.children) {
  108622. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108623. var index = _a[_i];
  108624. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108625. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108626. }
  108627. }
  108628. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108629. return Promise.all(promises).then(function () { });
  108630. };
  108631. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108632. // TODO: instancing
  108633. var _this = this;
  108634. var promises = new Array();
  108635. var primitives = mesh.primitives;
  108636. if (!primitives || primitives.length === 0) {
  108637. throw new Error(context + ": Primitives are missing");
  108638. }
  108639. GLTF2.ArrayItem.Assign(primitives);
  108640. if (primitives.length === 1) {
  108641. var primitive = primitives[0];
  108642. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108643. }
  108644. else {
  108645. node._primitiveBabylonMeshes = [];
  108646. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108647. var primitive = primitives_1[_i];
  108648. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108649. node._primitiveBabylonMeshes.push(babylonMesh);
  108650. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108651. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108652. }
  108653. }
  108654. if (node.skin != undefined) {
  108655. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108656. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108657. }
  108658. return Promise.all(promises).then(function () {
  108659. _this._forEachNodeMesh(node, function (babylonMesh) {
  108660. babylonMesh._refreshBoundingInfo(true);
  108661. });
  108662. });
  108663. };
  108664. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108665. var _this = this;
  108666. var promises = new Array();
  108667. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108668. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  108669. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  108670. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  108671. }));
  108672. if (primitive.material == undefined) {
  108673. babylonMesh.material = this._getDefaultMaterial();
  108674. }
  108675. else {
  108676. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108677. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  108678. babylonMesh.material = babylonMaterial;
  108679. }));
  108680. }
  108681. return Promise.all(promises).then(function () { });
  108682. };
  108683. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108684. var _this = this;
  108685. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108686. if (promise) {
  108687. return promise;
  108688. }
  108689. var attributes = primitive.attributes;
  108690. if (!attributes) {
  108691. throw new Error(context + ": Attributes are missing");
  108692. }
  108693. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  108694. // TODO: handle other primitive modes
  108695. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  108696. }
  108697. var promises = new Array();
  108698. var babylonVertexData = new BABYLON.VertexData();
  108699. if (primitive.indices == undefined) {
  108700. var positionAccessorIndex = attributes["POSITION"];
  108701. if (positionAccessorIndex != undefined) {
  108702. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  108703. babylonVertexData.indices = new Uint32Array(accessor.count);
  108704. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  108705. babylonVertexData.indices[i] = i;
  108706. }
  108707. }
  108708. }
  108709. else {
  108710. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108711. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  108712. babylonVertexData.indices = data;
  108713. }));
  108714. }
  108715. var loadAttribute = function (attribute, kind) {
  108716. if (attributes[attribute] == undefined) {
  108717. return;
  108718. }
  108719. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108720. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108721. babylonMesh._delayInfo.push(kind);
  108722. }
  108723. if (attribute === "COLOR_0") {
  108724. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  108725. babylonMesh.hasVertexAlpha = true;
  108726. }
  108727. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108728. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108729. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  108730. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  108731. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  108732. }
  108733. babylonVertexData.set(attributeData, kind);
  108734. }));
  108735. };
  108736. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108737. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108738. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108739. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108740. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108741. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108742. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108743. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108744. return Promise.all(promises).then(function () {
  108745. return babylonVertexData;
  108746. });
  108747. };
  108748. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108749. if (!primitive.targets) {
  108750. return;
  108751. }
  108752. if (node._numMorphTargets == undefined) {
  108753. node._numMorphTargets = primitive.targets.length;
  108754. }
  108755. else if (primitive.targets.length !== node._numMorphTargets) {
  108756. throw new Error(context + ": Primitives do not have the same number of targets");
  108757. }
  108758. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108759. for (var index = 0; index < primitive.targets.length; index++) {
  108760. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108761. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108762. // TODO: tell the target whether it has positions, normals, tangents
  108763. }
  108764. };
  108765. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108766. if (!primitive.targets) {
  108767. return Promise.resolve();
  108768. }
  108769. var promises = new Array();
  108770. var morphTargetManager = babylonMesh.morphTargetManager;
  108771. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108772. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108773. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108774. }
  108775. return Promise.all(promises).then(function () { });
  108776. };
  108777. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108778. var _this = this;
  108779. var promises = new Array();
  108780. var loadAttribute = function (attribute, setData) {
  108781. if (attributes[attribute] == undefined) {
  108782. return;
  108783. }
  108784. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108785. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108786. setData(data);
  108787. }));
  108788. };
  108789. loadAttribute("POSITION", function (data) {
  108790. if (babylonVertexData.positions) {
  108791. for (var i = 0; i < data.length; i++) {
  108792. data[i] += babylonVertexData.positions[i];
  108793. }
  108794. babylonMorphTarget.setPositions(data);
  108795. }
  108796. });
  108797. loadAttribute("NORMAL", function (data) {
  108798. if (babylonVertexData.normals) {
  108799. for (var i = 0; i < data.length; i++) {
  108800. data[i] += babylonVertexData.normals[i];
  108801. }
  108802. babylonMorphTarget.setNormals(data);
  108803. }
  108804. });
  108805. loadAttribute("TANGENT", function (data) {
  108806. if (babylonVertexData.tangents) {
  108807. // Tangent data for morph targets is stored as xyz delta.
  108808. // The vertexData.tangent is stored as xyzw.
  108809. // So we need to skip every fourth vertexData.tangent.
  108810. for (var i = 0, j = 0; i < data.length; i++) {
  108811. data[i] += babylonVertexData.tangents[j++];
  108812. if ((i + 1) % 3 == 0) {
  108813. j++;
  108814. }
  108815. }
  108816. babylonMorphTarget.setTangents(data);
  108817. }
  108818. });
  108819. return Promise.all(promises).then(function () { });
  108820. };
  108821. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108822. if (accessor.componentType == 5126 /* FLOAT */) {
  108823. return data;
  108824. }
  108825. var factor = 1;
  108826. if (accessor.normalized) {
  108827. switch (accessor.componentType) {
  108828. case 5121 /* UNSIGNED_BYTE */: {
  108829. factor = 1 / 255;
  108830. break;
  108831. }
  108832. case 5123 /* UNSIGNED_SHORT */: {
  108833. factor = 1 / 65535;
  108834. break;
  108835. }
  108836. default: {
  108837. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  108838. }
  108839. }
  108840. }
  108841. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108842. for (var i = 0; i < result.length; i++) {
  108843. result[i] = data[i] * factor;
  108844. }
  108845. return result;
  108846. };
  108847. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108848. var result = new Float32Array(data.length / 3 * 4);
  108849. var offset = 0;
  108850. for (var i = 0; i < result.length; i++) {
  108851. if ((i + 1) % 4 === 0) {
  108852. result[i] = 1;
  108853. }
  108854. else {
  108855. result[i] = data[offset++];
  108856. }
  108857. }
  108858. return result;
  108859. };
  108860. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108861. var position = BABYLON.Vector3.Zero();
  108862. var rotation = BABYLON.Quaternion.Identity();
  108863. var scaling = BABYLON.Vector3.One();
  108864. if (node.matrix) {
  108865. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108866. matrix.decompose(scaling, rotation, position);
  108867. }
  108868. else {
  108869. if (node.translation)
  108870. position = BABYLON.Vector3.FromArray(node.translation);
  108871. if (node.rotation)
  108872. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108873. if (node.scale)
  108874. scaling = BABYLON.Vector3.FromArray(node.scale);
  108875. }
  108876. babylonNode.position = position;
  108877. babylonNode.rotationQuaternion = rotation;
  108878. babylonNode.scaling = scaling;
  108879. };
  108880. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108881. var _this = this;
  108882. var assignSkeleton = function () {
  108883. _this._forEachNodeMesh(node, function (babylonMesh) {
  108884. babylonMesh.skeleton = skin._babylonSkeleton;
  108885. });
  108886. node._babylonMesh.parent = _this._rootBabylonMesh;
  108887. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108888. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108889. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108890. };
  108891. if (skin._loaded) {
  108892. return skin._loaded.then(function () {
  108893. assignSkeleton();
  108894. });
  108895. }
  108896. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108897. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108898. var skeletonId = "skeleton" + skin._index;
  108899. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108900. skin._babylonSkeleton = babylonSkeleton;
  108901. _this._loadBones(context, skin, inverseBindMatricesData);
  108902. assignSkeleton();
  108903. }));
  108904. };
  108905. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108906. if (skin.inverseBindMatrices == undefined) {
  108907. return Promise.resolve(null);
  108908. }
  108909. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108910. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108911. return data;
  108912. });
  108913. };
  108914. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108915. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108916. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108917. node._babylonAnimationTargets.push(babylonBone);
  108918. return babylonBone;
  108919. };
  108920. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108921. var babylonBones = {};
  108922. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108923. var index = _a[_i];
  108924. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108925. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108926. }
  108927. };
  108928. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108929. var babylonBone = babylonBones[node._index];
  108930. if (babylonBone) {
  108931. return babylonBone;
  108932. }
  108933. var boneIndex = skin.joints.indexOf(node._index);
  108934. var baseMatrix = BABYLON.Matrix.Identity();
  108935. if (inverseBindMatricesData && boneIndex !== -1) {
  108936. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108937. baseMatrix.invertToRef(baseMatrix);
  108938. }
  108939. var babylonParentBone = null;
  108940. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108941. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108942. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108943. }
  108944. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108945. babylonBones[node._index] = babylonBone;
  108946. return babylonBone;
  108947. };
  108948. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108949. return node.matrix ?
  108950. BABYLON.Matrix.FromArray(node.matrix) :
  108951. 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());
  108952. };
  108953. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108954. var animations = this._gltf.animations;
  108955. if (!animations) {
  108956. return Promise.resolve();
  108957. }
  108958. var promises = new Array();
  108959. for (var index = 0; index < animations.length; index++) {
  108960. var animation = animations[index];
  108961. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108962. }
  108963. return Promise.all(promises).then(function () { });
  108964. };
  108965. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108966. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108967. animation._babylonAnimationGroup = babylonAnimationGroup;
  108968. var promises = new Array();
  108969. GLTF2.ArrayItem.Assign(animation.channels);
  108970. GLTF2.ArrayItem.Assign(animation.samplers);
  108971. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108972. var channel = _a[_i];
  108973. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108974. }
  108975. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  108976. return Promise.all(promises).then(function () {
  108977. babylonAnimationGroup.normalize();
  108978. });
  108979. };
  108980. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108981. var _this = this;
  108982. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108983. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  108984. return Promise.resolve();
  108985. }
  108986. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108987. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108988. var targetPath;
  108989. var animationType;
  108990. switch (channel.target.path) {
  108991. case "translation" /* TRANSLATION */: {
  108992. targetPath = "position";
  108993. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108994. break;
  108995. }
  108996. case "rotation" /* ROTATION */: {
  108997. targetPath = "rotationQuaternion";
  108998. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108999. break;
  109000. }
  109001. case "scale" /* SCALE */: {
  109002. targetPath = "scaling";
  109003. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109004. break;
  109005. }
  109006. case "weights" /* WEIGHTS */: {
  109007. targetPath = "influence";
  109008. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109009. break;
  109010. }
  109011. default: {
  109012. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109013. }
  109014. }
  109015. var outputBufferOffset = 0;
  109016. var getNextOutputValue;
  109017. switch (targetPath) {
  109018. case "position": {
  109019. getNextOutputValue = function () {
  109020. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109021. outputBufferOffset += 3;
  109022. return value;
  109023. };
  109024. break;
  109025. }
  109026. case "rotationQuaternion": {
  109027. getNextOutputValue = function () {
  109028. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109029. outputBufferOffset += 4;
  109030. return value;
  109031. };
  109032. break;
  109033. }
  109034. case "scaling": {
  109035. getNextOutputValue = function () {
  109036. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109037. outputBufferOffset += 3;
  109038. return value;
  109039. };
  109040. break;
  109041. }
  109042. case "influence": {
  109043. getNextOutputValue = function () {
  109044. var value = new Array(targetNode._numMorphTargets);
  109045. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109046. value[i] = data.output[outputBufferOffset++];
  109047. }
  109048. return value;
  109049. };
  109050. break;
  109051. }
  109052. }
  109053. var getNextKey;
  109054. switch (data.interpolation) {
  109055. case "STEP" /* STEP */: {
  109056. getNextKey = function (frameIndex) { return ({
  109057. frame: data.input[frameIndex],
  109058. value: getNextOutputValue(),
  109059. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109060. }); };
  109061. break;
  109062. }
  109063. case "LINEAR" /* LINEAR */: {
  109064. getNextKey = function (frameIndex) { return ({
  109065. frame: data.input[frameIndex],
  109066. value: getNextOutputValue()
  109067. }); };
  109068. break;
  109069. }
  109070. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109071. getNextKey = function (frameIndex) { return ({
  109072. frame: data.input[frameIndex],
  109073. inTangent: getNextOutputValue(),
  109074. value: getNextOutputValue(),
  109075. outTangent: getNextOutputValue()
  109076. }); };
  109077. break;
  109078. }
  109079. }
  109080. var keys;
  109081. if (data.input.length === 1) {
  109082. var key = getNextKey(0);
  109083. keys = [
  109084. { frame: key.frame, value: key.value },
  109085. { frame: key.frame + 1, value: key.value }
  109086. ];
  109087. }
  109088. else {
  109089. keys = new Array(data.input.length);
  109090. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109091. keys[frameIndex] = getNextKey(frameIndex);
  109092. }
  109093. }
  109094. if (targetPath === "influence") {
  109095. var _loop_1 = function (targetIndex) {
  109096. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109097. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109098. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109099. frame: key.frame,
  109100. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109101. value: key.value[targetIndex],
  109102. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109103. }); }));
  109104. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  109105. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109106. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109107. });
  109108. };
  109109. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109110. _loop_1(targetIndex);
  109111. }
  109112. }
  109113. else {
  109114. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109115. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109116. babylonAnimation.setKeys(keys);
  109117. if (targetNode._babylonAnimationTargets) {
  109118. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109119. var target = _a[_i];
  109120. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109121. }
  109122. }
  109123. }
  109124. });
  109125. };
  109126. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109127. if (sampler._data) {
  109128. return sampler._data;
  109129. }
  109130. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109131. switch (interpolation) {
  109132. case "STEP" /* STEP */:
  109133. case "LINEAR" /* LINEAR */:
  109134. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109135. break;
  109136. }
  109137. default: {
  109138. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109139. }
  109140. }
  109141. var inputData;
  109142. var outputData;
  109143. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109144. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109145. sampler._data = Promise.all([
  109146. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109147. inputData = data;
  109148. }),
  109149. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109150. outputData = data;
  109151. })
  109152. ]).then(function () {
  109153. return {
  109154. input: inputData,
  109155. interpolation: interpolation,
  109156. output: outputData,
  109157. };
  109158. });
  109159. return sampler._data;
  109160. };
  109161. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109162. if (buffer._data) {
  109163. return buffer._data;
  109164. }
  109165. if (!buffer.uri) {
  109166. throw new Error(context + ": Uri is missing");
  109167. }
  109168. buffer._data = this._loadUriAsync(context, buffer.uri);
  109169. return buffer._data;
  109170. };
  109171. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109172. if (bufferView._data) {
  109173. return bufferView._data;
  109174. }
  109175. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109176. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109177. try {
  109178. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109179. }
  109180. catch (e) {
  109181. throw new Error(context + ": " + e.message);
  109182. }
  109183. });
  109184. return bufferView._data;
  109185. };
  109186. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109187. var _this = this;
  109188. if (accessor.sparse) {
  109189. throw new Error(context + ": Sparse accessors are not currently supported");
  109190. }
  109191. if (accessor._data) {
  109192. return accessor._data;
  109193. }
  109194. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109195. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109196. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109197. var byteOffset = accessor.byteOffset || 0;
  109198. var byteStride = bufferView.byteStride;
  109199. if (byteStride === 0) {
  109200. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109201. }
  109202. try {
  109203. switch (accessor.componentType) {
  109204. case 5120 /* BYTE */: {
  109205. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109206. }
  109207. case 5121 /* UNSIGNED_BYTE */: {
  109208. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109209. }
  109210. case 5122 /* SHORT */: {
  109211. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109212. }
  109213. case 5123 /* UNSIGNED_SHORT */: {
  109214. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109215. }
  109216. case 5125 /* UNSIGNED_INT */: {
  109217. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109218. }
  109219. case 5126 /* FLOAT */: {
  109220. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109221. }
  109222. default: {
  109223. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109224. }
  109225. }
  109226. }
  109227. catch (e) {
  109228. throw new Error(context + ": " + e.messsage);
  109229. }
  109230. });
  109231. return accessor._data;
  109232. };
  109233. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109234. byteOffset += data.byteOffset;
  109235. var targetLength = count * numComponents;
  109236. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109237. return new typedArray(data.buffer, byteOffset, targetLength);
  109238. }
  109239. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109240. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109241. var targetBuffer = new typedArray(targetLength);
  109242. var sourceIndex = 0;
  109243. var targetIndex = 0;
  109244. while (targetIndex < targetLength) {
  109245. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109246. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109247. targetIndex++;
  109248. }
  109249. sourceIndex += elementStride;
  109250. }
  109251. return targetBuffer;
  109252. };
  109253. GLTFLoader.prototype._getDefaultMaterial = function () {
  109254. var id = "__gltf_default";
  109255. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109256. if (!babylonMaterial) {
  109257. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109258. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109259. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109260. babylonMaterial.metallic = 1;
  109261. babylonMaterial.roughness = 1;
  109262. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109263. }
  109264. return babylonMaterial;
  109265. };
  109266. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109267. var promises = new Array();
  109268. var babylonMaterial = material._babylonMaterial;
  109269. // Ensure metallic workflow
  109270. babylonMaterial.metallic = 1;
  109271. babylonMaterial.roughness = 1;
  109272. var properties = material.pbrMetallicRoughness;
  109273. if (properties) {
  109274. if (properties.baseColorFactor) {
  109275. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109276. babylonMaterial.alpha = properties.baseColorFactor[3];
  109277. }
  109278. else {
  109279. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109280. }
  109281. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109282. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109283. if (properties.baseColorTexture) {
  109284. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109285. babylonMaterial.albedoTexture = texture;
  109286. }));
  109287. }
  109288. if (properties.metallicRoughnessTexture) {
  109289. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109290. babylonMaterial.metallicTexture = texture;
  109291. }));
  109292. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109293. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109294. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109295. }
  109296. }
  109297. this._loadMaterialAlphaProperties(context, material);
  109298. return Promise.all(promises).then(function () { });
  109299. };
  109300. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109301. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109302. if (promise) {
  109303. return promise;
  109304. }
  109305. material._babylonMeshes = material._babylonMeshes || [];
  109306. material._babylonMeshes.push(babylonMesh);
  109307. if (!material._loaded) {
  109308. var promises = new Array();
  109309. var babylonMaterial = this._createMaterial(material);
  109310. material._babylonMaterial = babylonMaterial;
  109311. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109312. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109313. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109314. material._loaded = Promise.all(promises).then(function () { });
  109315. }
  109316. assign(material._babylonMaterial);
  109317. return material._loaded;
  109318. };
  109319. GLTFLoader.prototype._createMaterial = function (material) {
  109320. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109321. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109322. return babylonMaterial;
  109323. };
  109324. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109325. var promises = new Array();
  109326. var babylonMaterial = material._babylonMaterial;
  109327. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109328. if (material.doubleSided) {
  109329. babylonMaterial.backFaceCulling = false;
  109330. babylonMaterial.twoSidedLighting = true;
  109331. }
  109332. if (material.normalTexture) {
  109333. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109334. babylonMaterial.bumpTexture = texture;
  109335. }));
  109336. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109337. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109338. if (material.normalTexture.scale != undefined) {
  109339. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109340. }
  109341. }
  109342. if (material.occlusionTexture) {
  109343. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109344. babylonMaterial.ambientTexture = texture;
  109345. }));
  109346. babylonMaterial.useAmbientInGrayScale = true;
  109347. if (material.occlusionTexture.strength != undefined) {
  109348. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109349. }
  109350. }
  109351. if (material.emissiveTexture) {
  109352. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109353. babylonMaterial.emissiveTexture = texture;
  109354. }));
  109355. }
  109356. return Promise.all(promises).then(function () { });
  109357. };
  109358. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109359. var babylonMaterial = material._babylonMaterial;
  109360. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109361. switch (alphaMode) {
  109362. case "OPAQUE" /* OPAQUE */: {
  109363. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109364. break;
  109365. }
  109366. case "MASK" /* MASK */: {
  109367. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109368. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109369. if (babylonMaterial.alpha) {
  109370. if (babylonMaterial.alpha === 0) {
  109371. babylonMaterial.alphaCutOff = 1;
  109372. }
  109373. else {
  109374. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109375. }
  109376. babylonMaterial.alpha = 1;
  109377. }
  109378. if (babylonMaterial.albedoTexture) {
  109379. babylonMaterial.albedoTexture.hasAlpha = true;
  109380. }
  109381. break;
  109382. }
  109383. case "BLEND" /* BLEND */: {
  109384. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109385. if (babylonMaterial.albedoTexture) {
  109386. babylonMaterial.albedoTexture.hasAlpha = true;
  109387. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109388. }
  109389. break;
  109390. }
  109391. default: {
  109392. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109393. }
  109394. }
  109395. };
  109396. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109397. var _this = this;
  109398. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109399. context = "#/textures/" + textureInfo.index;
  109400. var promises = new Array();
  109401. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109402. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109403. var deferred = new BABYLON.Deferred();
  109404. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109405. if (!_this._disposed) {
  109406. deferred.resolve();
  109407. }
  109408. }, function (message, exception) {
  109409. if (!_this._disposed) {
  109410. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109411. }
  109412. });
  109413. promises.push(deferred.promise);
  109414. babylonTexture.name = texture.name || "texture" + texture._index;
  109415. babylonTexture.wrapU = samplerData.wrapU;
  109416. babylonTexture.wrapV = samplerData.wrapV;
  109417. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109418. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109419. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109420. babylonTexture.updateURL(objectURL);
  109421. }));
  109422. assign(babylonTexture);
  109423. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109424. return Promise.all(promises).then(function () { });
  109425. };
  109426. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109427. if (!sampler._data) {
  109428. sampler._data = {
  109429. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109430. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109431. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109432. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109433. };
  109434. }
  109435. ;
  109436. return sampler._data;
  109437. };
  109438. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109439. if (image._objectURL) {
  109440. return image._objectURL;
  109441. }
  109442. var promise;
  109443. if (image.uri) {
  109444. promise = this._loadUriAsync(context, image.uri);
  109445. }
  109446. else {
  109447. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109448. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109449. }
  109450. image._objectURL = promise.then(function (data) {
  109451. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109452. });
  109453. return image._objectURL;
  109454. };
  109455. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109456. var _this = this;
  109457. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109458. if (promise) {
  109459. return promise;
  109460. }
  109461. if (!GLTFLoader._ValidateUri(uri)) {
  109462. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109463. }
  109464. if (BABYLON.Tools.IsBase64(uri)) {
  109465. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109466. }
  109467. return new Promise(function (resolve, reject) {
  109468. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109469. if (!_this._disposed) {
  109470. resolve(new Uint8Array(data));
  109471. }
  109472. }, function (event) {
  109473. if (!_this._disposed) {
  109474. try {
  109475. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109476. request._lengthComputable = event.lengthComputable;
  109477. request._loaded = event.loaded;
  109478. request._total = event.total;
  109479. _this._onProgress();
  109480. }
  109481. }
  109482. catch (e) {
  109483. reject(e);
  109484. }
  109485. }
  109486. }, _this._babylonScene.database, true, function (request, exception) {
  109487. if (!_this._disposed) {
  109488. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109489. }
  109490. });
  109491. _this._requests.push(request);
  109492. });
  109493. };
  109494. GLTFLoader.prototype._onProgress = function () {
  109495. if (!this._progressCallback) {
  109496. return;
  109497. }
  109498. var lengthComputable = true;
  109499. var loaded = 0;
  109500. var total = 0;
  109501. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109502. var request = _a[_i];
  109503. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109504. return;
  109505. }
  109506. lengthComputable = lengthComputable && request._lengthComputable;
  109507. loaded += request._loaded;
  109508. total += request._total;
  109509. }
  109510. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109511. };
  109512. GLTFLoader._GetProperty = function (context, array, index) {
  109513. if (!array || index == undefined || !array[index]) {
  109514. throw new Error(context + ": Failed to find index (" + index + ")");
  109515. }
  109516. return array[index];
  109517. };
  109518. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109519. // Set defaults if undefined
  109520. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109521. switch (mode) {
  109522. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109523. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109524. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109525. default:
  109526. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109527. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109528. }
  109529. };
  109530. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109531. // Set defaults if undefined
  109532. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109533. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109534. if (magFilter === 9729 /* LINEAR */) {
  109535. switch (minFilter) {
  109536. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109537. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109538. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109539. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109540. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109541. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109542. default:
  109543. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109544. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109545. }
  109546. }
  109547. else {
  109548. if (magFilter !== 9728 /* NEAREST */) {
  109549. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109550. }
  109551. switch (minFilter) {
  109552. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109553. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109554. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109555. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109556. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109557. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109558. default:
  109559. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109560. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109561. }
  109562. }
  109563. };
  109564. GLTFLoader._GetNumComponents = function (context, type) {
  109565. switch (type) {
  109566. case "SCALAR": return 1;
  109567. case "VEC2": return 2;
  109568. case "VEC3": return 3;
  109569. case "VEC4": return 4;
  109570. case "MAT2": return 4;
  109571. case "MAT3": return 9;
  109572. case "MAT4": return 16;
  109573. }
  109574. throw new Error(context + ": Invalid type (" + type + ")");
  109575. };
  109576. GLTFLoader._ValidateUri = function (uri) {
  109577. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109578. };
  109579. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109580. var promises = new Array();
  109581. if (this._gltf.materials) {
  109582. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109583. var material = _a[_i];
  109584. var babylonMaterial = material._babylonMaterial;
  109585. var babylonMeshes = material._babylonMeshes;
  109586. if (babylonMaterial && babylonMeshes) {
  109587. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109588. var babylonMesh = babylonMeshes_1[_b];
  109589. // Ensure nonUniformScaling is set if necessary.
  109590. babylonMesh.computeWorldMatrix(true);
  109591. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109592. if (this.useClipPlane) {
  109593. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109594. }
  109595. }
  109596. }
  109597. }
  109598. }
  109599. return Promise.all(promises).then(function () { });
  109600. };
  109601. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109602. var promises = new Array();
  109603. var lights = this._babylonScene.lights;
  109604. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109605. var light = lights_1[_i];
  109606. var generator = light.getShadowGenerator();
  109607. if (generator) {
  109608. promises.push(generator.forceCompilationAsync());
  109609. }
  109610. }
  109611. return Promise.all(promises).then(function () { });
  109612. };
  109613. GLTFLoader.prototype._clear = function () {
  109614. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109615. var request = _a[_i];
  109616. request.abort();
  109617. }
  109618. this._requests.length = 0;
  109619. if (this._gltf && this._gltf.images) {
  109620. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109621. var image = _c[_b];
  109622. if (image._objectURL) {
  109623. image._objectURL.then(function (value) {
  109624. URL.revokeObjectURL(value);
  109625. });
  109626. image._objectURL = undefined;
  109627. }
  109628. }
  109629. }
  109630. delete this._gltf;
  109631. delete this._babylonScene;
  109632. this._completePromises.length = 0;
  109633. for (var name_3 in this._extensions) {
  109634. this._extensions[name_3].dispose();
  109635. }
  109636. this._extensions = {};
  109637. delete this._rootBabylonMesh;
  109638. delete this._progressCallback;
  109639. this.onMeshLoadedObservable.clear();
  109640. this.onTextureLoadedObservable.clear();
  109641. this.onMaterialLoadedObservable.clear();
  109642. };
  109643. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109644. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109645. var name_4 = _a[_i];
  109646. var extension = this._extensions[name_4];
  109647. if (extension.enabled) {
  109648. var promise = actionAsync(extension);
  109649. if (promise) {
  109650. return promise;
  109651. }
  109652. }
  109653. }
  109654. return null;
  109655. };
  109656. GLTFLoader._Names = new Array();
  109657. GLTFLoader._Factories = {};
  109658. return GLTFLoader;
  109659. }());
  109660. GLTF2.GLTFLoader = GLTFLoader;
  109661. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  109662. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109663. })(BABYLON || (BABYLON = {}));
  109664. //# sourceMappingURL=babylon.glTFLoader.js.map
  109665. var BABYLON;
  109666. (function (BABYLON) {
  109667. var GLTF2;
  109668. (function (GLTF2) {
  109669. var GLTFLoaderExtension = /** @class */ (function () {
  109670. function GLTFLoaderExtension(loader) {
  109671. this.enabled = true;
  109672. this._loader = loader;
  109673. }
  109674. GLTFLoaderExtension.prototype.dispose = function () {
  109675. delete this._loader;
  109676. };
  109677. // #region Overridable Methods
  109678. /** Override this method to modify the default behavior for loading scenes. */
  109679. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109680. /** Override this method to modify the default behavior for loading nodes. */
  109681. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109682. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  109683. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109684. /** Override this method to modify the default behavior for loading materials. */
  109685. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  109686. /** Override this method to modify the default behavior for loading uris. */
  109687. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109688. // #endregion
  109689. /** Helper method called by a loader extension to load an glTF extension. */
  109690. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109691. if (!property.extensions) {
  109692. return null;
  109693. }
  109694. var extensions = property.extensions;
  109695. var extension = extensions[this.name];
  109696. if (!extension) {
  109697. return null;
  109698. }
  109699. // Clear out the extension before executing the action to avoid recursing into the same property.
  109700. delete extensions[this.name];
  109701. try {
  109702. return actionAsync(context + "/extensions/" + this.name, extension);
  109703. }
  109704. finally {
  109705. // Restore the extension after executing the action.
  109706. extensions[this.name] = extension;
  109707. }
  109708. };
  109709. /** Helper method called by the loader to allow extensions to override loading scenes. */
  109710. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109711. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109712. };
  109713. /** Helper method called by the loader to allow extensions to override loading nodes. */
  109714. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109715. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109716. };
  109717. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  109718. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109719. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109720. };
  109721. /** Helper method called by the loader to allow extensions to override loading materials. */
  109722. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  109723. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  109724. };
  109725. /** Helper method called by the loader to allow extensions to override loading uris. */
  109726. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109727. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109728. };
  109729. return GLTFLoaderExtension;
  109730. }());
  109731. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109732. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109733. })(BABYLON || (BABYLON = {}));
  109734. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109735. var BABYLON;
  109736. (function (BABYLON) {
  109737. var GLTF2;
  109738. (function (GLTF2) {
  109739. var Extensions;
  109740. (function (Extensions) {
  109741. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  109742. var NAME = "MSFT_lod";
  109743. var MSFT_lod = /** @class */ (function (_super) {
  109744. __extends(MSFT_lod, _super);
  109745. function MSFT_lod() {
  109746. var _this = _super !== null && _super.apply(this, arguments) || this;
  109747. _this.name = NAME;
  109748. /**
  109749. * Maximum number of LODs to load, starting from the lowest LOD.
  109750. */
  109751. _this.maxLODsToLoad = Number.MAX_VALUE;
  109752. _this._loadingNodeLOD = null;
  109753. _this._loadNodeSignals = {};
  109754. _this._loadingMaterialLOD = null;
  109755. _this._loadMaterialSignals = {};
  109756. return _this;
  109757. }
  109758. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109759. var _this = this;
  109760. return this._loadExtensionAsync(context, node, function (context, extension) {
  109761. var firstPromise;
  109762. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  109763. var _loop_1 = function (indexLOD) {
  109764. var nodeLOD = nodeLODs[indexLOD];
  109765. if (indexLOD !== 0) {
  109766. _this._loadingNodeLOD = nodeLOD;
  109767. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109768. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109769. }
  109770. }
  109771. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109772. if (indexLOD !== 0) {
  109773. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109774. if (previousNodeLOD._babylonMesh) {
  109775. previousNodeLOD._babylonMesh.dispose();
  109776. delete previousNodeLOD._babylonMesh;
  109777. }
  109778. }
  109779. if (indexLOD !== nodeLODs.length - 1) {
  109780. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109781. if (_this._loadNodeSignals[nodeIndex]) {
  109782. _this._loadNodeSignals[nodeIndex].resolve();
  109783. delete _this._loadNodeSignals[nodeIndex];
  109784. }
  109785. }
  109786. });
  109787. if (indexLOD === 0) {
  109788. firstPromise = promise;
  109789. }
  109790. else {
  109791. _this._loader._completePromises.push(promise);
  109792. _this._loadingNodeLOD = null;
  109793. }
  109794. };
  109795. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109796. _loop_1(indexLOD);
  109797. }
  109798. return firstPromise;
  109799. });
  109800. };
  109801. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109802. var _this = this;
  109803. // Don't load material LODs if already loading a node LOD.
  109804. if (this._loadingNodeLOD) {
  109805. return null;
  109806. }
  109807. return this._loadExtensionAsync(context, material, function (context, extension) {
  109808. var firstPromise;
  109809. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109810. var _loop_2 = function (indexLOD) {
  109811. var materialLOD = materialLODs[indexLOD];
  109812. if (indexLOD !== 0) {
  109813. _this._loadingMaterialLOD = materialLOD;
  109814. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109815. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109816. }
  109817. }
  109818. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  109819. if (indexLOD !== 0) {
  109820. assign(materialLOD._babylonMaterial);
  109821. var previousMaterialLOD = materialLODs[indexLOD - 1];
  109822. if (previousMaterialLOD._babylonMaterial) {
  109823. previousMaterialLOD._babylonMaterial.dispose();
  109824. delete previousMaterialLOD._babylonMaterial;
  109825. }
  109826. }
  109827. if (indexLOD !== materialLODs.length - 1) {
  109828. var materialIndex = materialLODs[indexLOD + 1]._index;
  109829. if (_this._loadMaterialSignals[materialIndex]) {
  109830. _this._loadMaterialSignals[materialIndex].resolve();
  109831. delete _this._loadMaterialSignals[materialIndex];
  109832. }
  109833. }
  109834. });
  109835. if (indexLOD === 0) {
  109836. firstPromise = promise;
  109837. }
  109838. else {
  109839. _this._loader._completePromises.push(promise);
  109840. _this._loadingMaterialLOD = null;
  109841. }
  109842. };
  109843. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109844. _loop_2(indexLOD);
  109845. }
  109846. return firstPromise;
  109847. });
  109848. };
  109849. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109850. var _this = this;
  109851. // Defer the loading of uris if loading a material or node LOD.
  109852. if (this._loadingMaterialLOD) {
  109853. var index = this._loadingMaterialLOD._index;
  109854. return this._loadMaterialSignals[index].promise.then(function () {
  109855. return _this._loader._loadUriAsync(context, uri);
  109856. });
  109857. }
  109858. else if (this._loadingNodeLOD) {
  109859. var index = this._loadingNodeLOD._index;
  109860. return this._loadNodeSignals[index].promise.then(function () {
  109861. return _this._loader._loadUriAsync(context, uri);
  109862. });
  109863. }
  109864. return null;
  109865. };
  109866. /**
  109867. * Gets an array of LOD properties from lowest to highest.
  109868. */
  109869. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109870. if (this.maxLODsToLoad <= 0) {
  109871. throw new Error("maxLODsToLoad must be greater than zero");
  109872. }
  109873. var properties = new Array();
  109874. for (var i = ids.length - 1; i >= 0; i--) {
  109875. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109876. if (properties.length === this.maxLODsToLoad) {
  109877. return properties;
  109878. }
  109879. }
  109880. properties.push(property);
  109881. return properties;
  109882. };
  109883. return MSFT_lod;
  109884. }(GLTF2.GLTFLoaderExtension));
  109885. Extensions.MSFT_lod = MSFT_lod;
  109886. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109887. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109888. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109889. })(BABYLON || (BABYLON = {}));
  109890. //# sourceMappingURL=MSFT_lod.js.map
  109891. var BABYLON;
  109892. (function (BABYLON) {
  109893. var GLTF2;
  109894. (function (GLTF2) {
  109895. var Extensions;
  109896. (function (Extensions) {
  109897. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109898. var NAME = "KHR_draco_mesh_compression";
  109899. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109900. __extends(KHR_draco_mesh_compression, _super);
  109901. function KHR_draco_mesh_compression(loader) {
  109902. var _this = _super.call(this, loader) || this;
  109903. _this.name = NAME;
  109904. _this._dracoCompression = null;
  109905. // Disable extension if decoder is not available.
  109906. if (!BABYLON.DracoCompression.DecoderUrl) {
  109907. _this.enabled = false;
  109908. }
  109909. return _this;
  109910. }
  109911. KHR_draco_mesh_compression.prototype.dispose = function () {
  109912. if (this._dracoCompression) {
  109913. this._dracoCompression.dispose();
  109914. }
  109915. _super.prototype.dispose.call(this);
  109916. };
  109917. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109918. var _this = this;
  109919. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109920. if (primitive.mode != undefined) {
  109921. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109922. primitive.mode !== 4 /* TRIANGLES */) {
  109923. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109924. }
  109925. // TODO: handle triangle strips
  109926. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109927. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109928. }
  109929. }
  109930. var attributes = {};
  109931. var loadAttribute = function (name, kind) {
  109932. var uniqueId = extension.attributes[name];
  109933. if (uniqueId == undefined) {
  109934. return;
  109935. }
  109936. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109937. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109938. babylonMesh._delayInfo.push(kind);
  109939. }
  109940. attributes[kind] = uniqueId;
  109941. };
  109942. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109943. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109944. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109945. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109946. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109947. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109948. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109949. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109950. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109951. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109952. try {
  109953. if (!_this._dracoCompression) {
  109954. _this._dracoCompression = new BABYLON.DracoCompression();
  109955. }
  109956. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  109957. }
  109958. catch (e) {
  109959. throw new Error(context + ": " + e.message);
  109960. }
  109961. });
  109962. });
  109963. };
  109964. return KHR_draco_mesh_compression;
  109965. }(GLTF2.GLTFLoaderExtension));
  109966. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109967. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109968. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109969. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109970. })(BABYLON || (BABYLON = {}));
  109971. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109972. var BABYLON;
  109973. (function (BABYLON) {
  109974. var GLTF2;
  109975. (function (GLTF2) {
  109976. var Extensions;
  109977. (function (Extensions) {
  109978. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  109979. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109980. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109981. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109982. function KHR_materials_pbrSpecularGlossiness() {
  109983. var _this = _super !== null && _super.apply(this, arguments) || this;
  109984. _this.name = NAME;
  109985. return _this;
  109986. }
  109987. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109988. var _this = this;
  109989. return this._loadExtensionAsync(context, material, function (context, extension) {
  109990. material._babylonMeshes = material._babylonMeshes || [];
  109991. material._babylonMeshes.push(babylonMesh);
  109992. if (!material._loaded) {
  109993. var promises = new Array();
  109994. var babylonMaterial = _this._loader._createMaterial(material);
  109995. material._babylonMaterial = babylonMaterial;
  109996. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  109997. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  109998. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109999. material._loaded = Promise.all(promises).then(function () { });
  110000. }
  110001. assign(material._babylonMaterial);
  110002. return material._loaded;
  110003. });
  110004. };
  110005. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  110006. var promises = new Array();
  110007. var babylonMaterial = material._babylonMaterial;
  110008. if (properties.diffuseFactor) {
  110009. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110010. babylonMaterial.alpha = properties.diffuseFactor[3];
  110011. }
  110012. else {
  110013. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110014. }
  110015. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110016. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110017. if (properties.diffuseTexture) {
  110018. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110019. babylonMaterial.albedoTexture = texture;
  110020. }));
  110021. }
  110022. if (properties.specularGlossinessTexture) {
  110023. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110024. babylonMaterial.reflectivityTexture = texture;
  110025. }));
  110026. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110027. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110028. }
  110029. this._loader._loadMaterialAlphaProperties(context, material);
  110030. return Promise.all(promises).then(function () { });
  110031. };
  110032. return KHR_materials_pbrSpecularGlossiness;
  110033. }(GLTF2.GLTFLoaderExtension));
  110034. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110035. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110036. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110037. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110038. })(BABYLON || (BABYLON = {}));
  110039. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110040. var BABYLON;
  110041. (function (BABYLON) {
  110042. var GLTF2;
  110043. (function (GLTF2) {
  110044. var Extensions;
  110045. (function (Extensions) {
  110046. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  110047. var NAME = "KHR_lights";
  110048. var LightType;
  110049. (function (LightType) {
  110050. LightType["AMBIENT"] = "ambient";
  110051. LightType["DIRECTIONAL"] = "directional";
  110052. LightType["POINT"] = "point";
  110053. LightType["SPOT"] = "spot";
  110054. })(LightType || (LightType = {}));
  110055. var KHR_lights = /** @class */ (function (_super) {
  110056. __extends(KHR_lights, _super);
  110057. function KHR_lights() {
  110058. var _this = _super !== null && _super.apply(this, arguments) || this;
  110059. _this.name = NAME;
  110060. return _this;
  110061. }
  110062. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110063. var _this = this;
  110064. return this._loadExtensionAsync(context, scene, function (context, extension) {
  110065. var promise = _this._loader._loadSceneAsync(context, scene);
  110066. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110067. if (light.type !== LightType.AMBIENT) {
  110068. throw new Error(context + ": Only ambient lights are allowed on a scene");
  110069. }
  110070. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110071. return promise;
  110072. });
  110073. };
  110074. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110075. var _this = this;
  110076. return this._loadExtensionAsync(context, node, function (context, extension) {
  110077. var promise = _this._loader._loadNodeAsync(context, node);
  110078. var babylonLight;
  110079. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110080. var name = node._babylonMesh.name;
  110081. switch (light.type) {
  110082. case LightType.AMBIENT: {
  110083. throw new Error(context + ": Ambient lights are not allowed on a node");
  110084. }
  110085. case LightType.DIRECTIONAL: {
  110086. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110087. break;
  110088. }
  110089. case LightType.POINT: {
  110090. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110091. break;
  110092. }
  110093. case LightType.SPOT: {
  110094. var spotLight = light;
  110095. // TODO: support inner and outer cone angles
  110096. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110097. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110098. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110099. break;
  110100. }
  110101. default: {
  110102. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110103. }
  110104. }
  110105. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110106. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110107. babylonLight.parent = node._babylonMesh;
  110108. return promise;
  110109. });
  110110. };
  110111. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110112. get: function () {
  110113. var extensions = this._loader._gltf.extensions;
  110114. if (!extensions || !extensions[this.name]) {
  110115. throw new Error("#/extensions: '" + this.name + "' not found");
  110116. }
  110117. var extension = extensions[this.name];
  110118. return extension.lights;
  110119. },
  110120. enumerable: true,
  110121. configurable: true
  110122. });
  110123. return KHR_lights;
  110124. }(GLTF2.GLTFLoaderExtension));
  110125. Extensions.KHR_lights = KHR_lights;
  110126. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110127. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110128. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110129. })(BABYLON || (BABYLON = {}));
  110130. //# sourceMappingURL=KHR_lights.js.map
  110131. return BABYLON;
  110132. });
  110133. /***/ }),
  110134. /* 33 */
  110135. /***/ (function(module, exports, __webpack_require__) {
  110136. /*!
  110137. * PEP v0.4.3 | https://github.com/jquery/PEP
  110138. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110139. */
  110140. !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);
  110141. // define inherited MouseEvent properties
  110142. // skip bubbles and cancelable since they're set above in initEvent()
  110143. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110144. // Spec requires that pointers without pressure specified use 0.5 for down
  110145. // state and 0 for up state.
  110146. var f=0;
  110147. // add x/y properties aliased to clientX/Y
  110148. // define the properties of the PointerEvent interface
  110149. 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(){
  110150. // only activate if this platform does not have pointer events
  110151. 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}})}/**
  110152. * This is the constructor for new PointerEvents.
  110153. *
  110154. * New Pointer Events must be given a type, and an optional dictionary of
  110155. * initialization properties.
  110156. *
  110157. * Due to certain platform requirements, events returned from the constructor
  110158. * identify as MouseEvents.
  110159. *
  110160. * @constructor
  110161. * @param {String} inType The type of the event to create.
  110162. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110163. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110164. */
  110165. 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},
  110166. // return value, key, map
  110167. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110168. // MouseEvent
  110169. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110170. // DOM Level 3
  110171. "buttons",
  110172. // PointerEvent
  110173. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110174. // event instance
  110175. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110176. // MouseEvent
  110177. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110178. // DOM Level 3
  110179. 0,
  110180. // PointerEvent
  110181. 0,0,0,0,0,0,"",0,!1,
  110182. // event instance
  110183. "",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),
  110184. // Scope objects for native events.
  110185. // This exists for ease of testing.
  110186. eventSources:Object.create(null),eventSourceList:[],/**
  110187. * Add a new event source that will generate pointer events.
  110188. *
  110189. * `inSource` must contain an array of event names named `events`, and
  110190. * functions with the names specified in the `events` array.
  110191. * @param {string} name A name for the event source
  110192. * @param {Object} source A new source of platform events.
  110193. */
  110194. 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++)
  110195. // call eventsource register
  110196. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110197. // call eventsource register
  110198. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110199. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110200. return!1}},
  110201. // EVENTS
  110202. 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)},
  110203. // LISTENER LOGIC
  110204. eventHandler:function(a){
  110205. // This is used to prevent multiple dispatch of pointerevents from
  110206. // platform events. This can happen when two elements in different scopes
  110207. // are set up to create pointer events, which is relevant to Shadow DOM.
  110208. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110209. // set up event listeners
  110210. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110211. // remove event listeners
  110212. 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)},
  110213. // EVENT CREATION AND TRACKING
  110214. /**
  110215. * Creates a new Event of type `inType`, based on the information in
  110216. * `inEvent`.
  110217. *
  110218. * @param {string} inType A string representing the type of event to create
  110219. * @param {Event} inEvent A platform event with a target
  110220. * @return {Event} A PointerEvent of type `inType`
  110221. */
  110222. makeEvent:function(b,c){
  110223. // relatedTarget must be null if pointer is captured
  110224. 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},
  110225. // make and dispatch an event in one call
  110226. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110227. * Returns a snapshot of inEvent, with writable properties.
  110228. *
  110229. * @param {Event} inEvent An event that contains properties to copy.
  110230. * @return {Object} An object containing shallow copies of `inEvent`'s
  110231. * properties.
  110232. */
  110233. 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],
  110234. // Work around SVGInstanceElement shadow tree
  110235. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110236. // This is the behavior implemented by Firefox.
  110237. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110238. // keep the semantics of preventDefault
  110239. 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){
  110240. // Order of conditions due to document.contains() missing in IE.
  110241. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110242. // Touch: Do not propagate if node is detached.
  110243. 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)}},/**
  110244. * Dispatches the event to its target.
  110245. *
  110246. * @param {Event} inEvent The event to be dispatched.
  110247. * @return {Boolean} True if an event handler returns true, false otherwise.
  110248. */
  110249. 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(
  110250. // is element a shadow host?
  110251. e=this.targetingShadow(f);e;){if(
  110252. // find the the element inside the shadow root
  110253. d=e.elementFromPoint(b,c)){
  110254. // shadowed element may contain a shadow root
  110255. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110256. // check for older shadows
  110257. e=this.olderShadow(e)}
  110258. // light dom element is the target
  110259. return f}},owner:function(a){
  110260. // walk up until you hit the shadow root or document
  110261. for(var b=a;b.parentNode;)b=b.parentNode;
  110262. // the owner element is expected to be a Document or ShadowRoot
  110263. 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);
  110264. // if x, y is not in this root, fall back to document search
  110265. 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){
  110266. // Only watch scopes that can target find, as these are top-level.
  110267. // Otherwise we can see duplicate additions and removals that add noise.
  110268. //
  110269. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110270. // a removal without an insertion when a node is redistributed among
  110271. // shadows. Since it all ends up correct in the document, watching only
  110272. // the document will yield the correct mutations to watch.
  110273. 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))},
  110274. // register all touch-action = none nodes on document load
  110275. 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){
  110276. // find children with touch-action
  110277. var b=x(a,this.findElements,this);
  110278. // flatten the list
  110279. // make sure the added nodes are accounted for
  110280. 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){}
  110281. // handler block for native mouse events
  110282. 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:[],
  110283. // collide with the global mouse listener
  110284. 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++){
  110285. // simulated mouse events will be swallowed near a primary touchend
  110286. 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);
  110287. // Update buttons state after possible out-of-document mouseup.
  110288. 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];
  110289. // Produces wrong state of buttons in Browsers without `buttons` support
  110290. // when a mouse button that was pressed outside the document is released
  110291. // inside and other buttons are still pressed down.
  110292. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110293. // Support: Firefox <=44 only
  110294. // FF Ubuntu includes the lifted button in the `buttons` property on
  110295. // mouseup.
  110296. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110297. 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),
  110298. // set touch-action on shadows as well
  110299. 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),
  110300. // remove touch-action from shadow
  110301. 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);
  110302. // simply update scrollType if listeners are already established
  110303. 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){
  110304. // set primary touch if there no pointers, or the only pointer is the mouse
  110305. (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,
  110306. // forward modifier keys
  110307. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110308. // forward touch preventDefaults
  110309. 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))},
  110310. // For single axis scrollers, determines whether the element should emit
  110311. // pointer events or behave as a scroller
  110312. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110313. // this element is a touch-action: none, should never scroll
  110314. b=!1;else if("XY"===c)
  110315. // this element should always scroll
  110316. 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]);
  110317. // if delta in the scroll axis > delta other axis, scroll instead of
  110318. // making events
  110319. 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},
  110320. // In some instances, a touchstart can happen without a touchend. This
  110321. // leaves the pointermap in a broken state.
  110322. // Therefore, on every touchstart, we remove the touches that did not fire a
  110323. // touchend event.
  110324. // To keep state globally consistent, we fire a
  110325. // pointercancel for this "abandoned" touch
  110326. vacuumTouches:function(a){var b=a.touches;
  110327. // pointermap.size should be < tl.length here, as the touchstart has not
  110328. // been processed yet.
  110329. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110330. // Never remove pointerId == 1, which is mouse.
  110331. // Touch identifiers are 2 smaller than their pointerId, which is the
  110332. // index in pointermap.
  110333. 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);
  110334. // a finger drifted off the screen, ignore it
  110335. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110336. // recover from retargeting by shadow
  110337. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110338. // clean up case when finger leaves the screen
  110339. 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)},
  110340. // prevent synth mouse events from creating pointer events
  110341. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110342. // only the primary finger will synth mouse events
  110343. if(this.isPrimaryTouch(c)){
  110344. // remember x/y of last touch
  110345. 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});
  110346. /***/ }),
  110347. /* 34 */
  110348. /***/ (function(module, exports, __webpack_require__) {
  110349. "use strict";
  110350. Object.defineProperty(exports, "__esModule", { value: true });
  110351. var defaultViewer_1 = __webpack_require__(4);
  110352. var mappers_1 = __webpack_require__(1);
  110353. function InitTags(selector) {
  110354. if (selector === void 0) { selector = 'babylon'; }
  110355. var elements = document.querySelectorAll(selector);
  110356. for (var i = 0; i < elements.length; ++i) {
  110357. var element = elements.item(i);
  110358. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110359. var config = configMapper.map(element);
  110360. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110361. }
  110362. }
  110363. exports.InitTags = InitTags;
  110364. /***/ })
  110365. /******/ ]);
  110366. return BabylonViewer;
  110367. });